blob: 3f94d21c0f59bf511660381b5ec9af6111881324 [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
Chris Lattner710bb872009-11-30 04:18:44 +000015#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000016#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Lex/CodeCompletionHandler.h"
18#include "clang/Lex/HeaderSearch.h"
Daniel Jasper07e6c402013-08-05 20:26:17 +000019#include "clang/Lex/HeaderSearchOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Lex/LexDiagnostic.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/ModuleLoader.h"
24#include "clang/Lex/Pragma.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000025#include "clang/Lex/Preprocessor.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000026#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/ADT/StringSwitch.h"
29#include "llvm/ADT/iterator_range.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000030#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaf6002232014-08-08 21:31:04 +000031#include "llvm/Support/Path.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000032#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000033
Chris Lattnerf64b3522008-03-09 01:54:53 +000034using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// Utility Methods for Preprocessor Directive Handling.
38//===----------------------------------------------------------------------===//
39
Chris Lattnerc0a585d2010-08-17 15:55:45 +000040MacroInfo *Preprocessor::AllocateMacroInfo() {
Richard Smithee0c4c12014-07-24 01:13:23 +000041 MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>();
Ted Kremenekc8456f82010-10-19 22:15:20 +000042 MIChain->Next = MIChainHead;
Ted Kremenekc8456f82010-10-19 22:15:20 +000043 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000044 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000045}
46
47MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
48 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000049 new (MI) MacroInfo(L);
50 return MI;
51}
52
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000053MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
54 unsigned SubModuleID) {
Chandler Carruth06dde922014-03-02 13:02:01 +000055 static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
56 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000057 DeserializedMacroInfoChain *MIChain =
58 BP.Allocate<DeserializedMacroInfoChain>();
59 MIChain->Next = DeserialMIChainHead;
60 DeserialMIChainHead = MIChain;
61
62 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000063 new (MI) MacroInfo(L);
64 MI->FromASTFile = true;
65 MI->setOwningModuleID(SubModuleID);
66 return MI;
67}
68
Richard Smith50474bf2015-04-23 23:29:05 +000069DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
70 SourceLocation Loc) {
Richard Smith713369b2015-04-23 20:40:50 +000071 return new (BP) DefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000072}
73
74UndefMacroDirective *
Richard Smith50474bf2015-04-23 23:29:05 +000075Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
Richard Smith713369b2015-04-23 20:40:50 +000076 return new (BP) UndefMacroDirective(UndefLoc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000077}
78
79VisibilityMacroDirective *
80Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
81 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000082 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000083}
84
James Dennettf6333ac2012-06-22 05:46:07 +000085/// \brief Read and discard all tokens remaining on the current line until
86/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000087void Preprocessor::DiscardUntilEndOfDirective() {
88 Token Tmp;
89 do {
90 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000091 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000092 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000093}
94
Serge Pavlov07c0f042014-12-18 11:14:21 +000095/// \brief Enumerates possible cases of #define/#undef a reserved identifier.
96enum MacroDiag {
97 MD_NoWarn, //> Not a reserved identifier
98 MD_KeywordDef, //> Macro hides keyword, enabled by default
99 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
100};
101
102/// \brief Checks if the specified identifier is reserved in the specified
103/// language.
104/// This function does not check if the identifier is a keyword.
105static bool isReservedId(StringRef Text, const LangOptions &Lang) {
106 // C++ [macro.names], C11 7.1.3:
107 // All identifiers that begin with an underscore and either an uppercase
108 // letter or another underscore are always reserved for any use.
109 if (Text.size() >= 2 && Text[0] == '_' &&
110 (isUppercase(Text[1]) || Text[1] == '_'))
111 return true;
112 // C++ [global.names]
113 // Each name that contains a double underscore ... is reserved to the
114 // implementation for any use.
115 if (Lang.CPlusPlus) {
116 if (Text.find("__") != StringRef::npos)
117 return true;
118 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000119 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000120}
121
Serge Pavlov07c0f042014-12-18 11:14:21 +0000122static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
123 const LangOptions &Lang = PP.getLangOpts();
124 StringRef Text = II->getName();
125 if (isReservedId(Text, Lang))
126 return MD_ReservedMacro;
127 if (II->isKeyword(Lang))
128 return MD_KeywordDef;
129 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
130 return MD_KeywordDef;
131 return MD_NoWarn;
132}
133
134static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
135 const LangOptions &Lang = PP.getLangOpts();
136 StringRef Text = II->getName();
137 // Do not warn on keyword undef. It is generally harmless and widely used.
138 if (isReservedId(Text, Lang))
139 return MD_ReservedMacro;
140 return MD_NoWarn;
141}
142
Taewook Ohf42103c2016-06-13 20:40:21 +0000143// Return true if we want to issue a diagnostic by default if we
144// encounter this name in a #include with the wrong case. For now,
145// this includes the standard C and C++ headers, Posix headers,
146// and Boost headers. Improper case for these #includes is a
147// potential portability issue.
148static bool warnByDefaultOnWrongCase(StringRef Include) {
149 // If the first component of the path is "boost", treat this like a standard header
150 // for the purposes of diagnostics.
151 if (::llvm::sys::path::begin(Include)->equals_lower("boost"))
152 return true;
153
154 // "condition_variable" is the longest standard header name at 18 characters.
155 // If the include file name is longer than that, it can't be a standard header.
Taewook Oh755e4d22016-06-13 21:55:33 +0000156 static const size_t MaxStdHeaderNameLen = 18u;
Taewook Ohf42103c2016-06-13 20:40:21 +0000157 if (Include.size() > MaxStdHeaderNameLen)
158 return false;
159
160 // Lowercase and normalize the search string.
161 SmallString<32> LowerInclude{Include};
162 for (char &Ch : LowerInclude) {
163 // In the ASCII range?
George Burgess IV5d3bd932016-06-16 02:30:33 +0000164 if (static_cast<unsigned char>(Ch) > 0x7f)
Taewook Ohf42103c2016-06-13 20:40:21 +0000165 return false; // Can't be a standard header
166 // ASCII lowercase:
167 if (Ch >= 'A' && Ch <= 'Z')
168 Ch += 'a' - 'A';
169 // Normalize path separators for comparison purposes.
170 else if (::llvm::sys::path::is_separator(Ch))
171 Ch = '/';
172 }
173
174 // The standard C/C++ and Posix headers
175 return llvm::StringSwitch<bool>(LowerInclude)
176 // C library headers
177 .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
178 .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
179 .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
180 .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
181 .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
182 .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
183
184 // C++ headers for C library facilities
185 .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
186 .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
187 .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
188 .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
189 .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
190 .Case("cwctype", true)
191
192 // C++ library headers
193 .Cases("algorithm", "fstream", "list", "regex", "thread", true)
194 .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
195 .Cases("atomic", "future", "map", "set", "type_traits", true)
196 .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
197 .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
198 .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
199 .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
200 .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
201 .Cases("deque", "istream", "queue", "string", "valarray", true)
202 .Cases("exception", "iterator", "random", "strstream", "vector", true)
203 .Cases("forward_list", "limits", "ratio", "system_error", true)
204
205 // POSIX headers (which aren't also C headers)
206 .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
207 .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
208 .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
209 .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
210 .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
211 .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
212 .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
213 .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
214 .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
215 .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
216 .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
217 .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
218 .Default(false);
219}
220
Serge Pavlov07c0f042014-12-18 11:14:21 +0000221bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
222 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000223 // Missing macro name?
224 if (MacroNameTok.is(tok::eod))
225 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
226
227 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
228 if (!II) {
229 bool Invalid = false;
230 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
231 if (Invalid)
232 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000233 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000234
Alp Tokerf33619c2014-05-31 03:38:08 +0000235 if (!II->isCPlusPlusOperatorKeyword())
236 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000237
Alp Tokere03e9e12014-05-31 16:32:22 +0000238 // C++ 2.5p2: Alternative tokens behave the same as its primary token
239 // except for their spellings.
240 Diag(MacroNameTok, getLangOpts().MicrosoftExt
241 ? diag::ext_pp_operator_used_as_macro_name
242 : diag::err_pp_operator_used_as_macro_name)
243 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000244
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000245 // Allow #defining |and| and friends for Microsoft compatibility or
246 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000247 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000248 }
249
Serge Pavlovd024f522014-10-24 17:31:32 +0000250 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000251 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
252 return Diag(MacroNameTok, diag::err_defined_macro_name);
253 }
254
Richard Smith20e883e2015-04-29 23:20:19 +0000255 if (isDefineUndef == MU_Undef) {
256 auto *MI = getMacroInfo(II);
257 if (MI && MI->isBuiltinMacro()) {
258 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
259 // and C++ [cpp.predefined]p4], but allow it as an extension.
260 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
261 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000262 }
263
Serge Pavlov07c0f042014-12-18 11:14:21 +0000264 // If defining/undefining reserved identifier or a keyword, we need to issue
265 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000266 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000267 if (ShadowFlag)
268 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000269 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
270 (strcmp(SourceMgr.getBufferName(MacroNameLoc), "<built-in>") != 0)) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000271 MacroDiag D = MD_NoWarn;
272 if (isDefineUndef == MU_Define) {
273 D = shouldWarnOnMacroDef(*this, II);
274 }
275 else if (isDefineUndef == MU_Undef)
276 D = shouldWarnOnMacroUndef(*this, II);
277 if (D == MD_KeywordDef) {
278 // We do not want to warn on some patterns widely used in configuration
279 // scripts. This requires analyzing next tokens, so do not issue warnings
280 // now, only inform caller.
281 if (ShadowFlag)
282 *ShadowFlag = true;
283 }
284 if (D == MD_ReservedMacro)
285 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000286 }
287
Alp Tokerb05e0b52014-05-21 06:13:51 +0000288 // Okay, we got a good identifier.
289 return false;
290}
291
James Dennettf6333ac2012-06-22 05:46:07 +0000292/// \brief Lex and validate a macro name, which occurs after a
293/// \#define or \#undef.
294///
Serge Pavlovd024f522014-10-24 17:31:32 +0000295/// This sets the token kind to eod and discards the rest of the macro line if
296/// the macro name is invalid.
297///
298/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000299/// \param isDefineUndef Context in which macro is used.
300/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
301void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
302 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000303 // Read the token, don't allow macro expansion on it.
304 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000305
Douglas Gregor12785102010-08-24 20:21:13 +0000306 if (MacroNameTok.is(tok::code_completion)) {
307 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000308 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000309 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000310 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000311 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000312
Serge Pavlov07c0f042014-12-18 11:14:21 +0000313 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000314 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000315
316 // Invalid macro name, read and discard the rest of the line and set the
317 // token kind to tok::eod if necessary.
318 if (MacroNameTok.isNot(tok::eod)) {
319 MacroNameTok.setKind(tok::eod);
320 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000321 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000322}
323
James Dennettf6333ac2012-06-22 05:46:07 +0000324/// \brief Ensure that the next token is a tok::eod token.
325///
326/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000327/// true, then we consider macros that expand to zero tokens as being ok.
328void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000330 // Lex unexpanded tokens for most directives: macros might expand to zero
331 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
332 // #line) allow empty macros.
333 if (EnableMacros)
334 Lex(Tmp);
335 else
336 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000337
Chris Lattnerf64b3522008-03-09 01:54:53 +0000338 // There should be no tokens after the directive, but we allow them as an
339 // extension.
340 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
341 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000342
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000343 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000344 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000345 // or if this is a macro-style preprocessing directive, because it is more
346 // trouble than it is worth to insert /**/ and check that there is no /**/
347 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000348 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000349 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000350 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000351 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
352 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000353 DiscardUntilEndOfDirective();
354 }
355}
356
James Dennettf6333ac2012-06-22 05:46:07 +0000357/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
358/// decided that the subsequent tokens are in the \#if'd out portion of the
359/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000360/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000361/// this \#if directive, so \#else/\#elif blocks should never be entered.
362/// If ElseOk is true, then \#else directives are ok, if not, then we have
363/// already seen one so a \#else directive is a duplicate. When this returns,
364/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000365void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
366 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000367 bool FoundElse,
368 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000369 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000370 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000371
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000372 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000373 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000374
Ted Kremenek56572ab2008-12-12 18:34:08 +0000375 if (CurPTHLexer) {
376 PTHSkipExcludedConditionalBlock();
377 return;
378 }
Mike Stump11289f42009-09-09 15:08:12 +0000379
Chris Lattnerf64b3522008-03-09 01:54:53 +0000380 // Enter raw mode to disable identifier lookup (and thus macro expansion),
381 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000382 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000383 Token Tok;
384 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000385 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000386
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000387 if (Tok.is(tok::code_completion)) {
388 if (CodeComplete)
389 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000390 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000391 continue;
392 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000393
Chris Lattnerf64b3522008-03-09 01:54:53 +0000394 // If this is the end of the buffer, we have an error.
395 if (Tok.is(tok::eof)) {
396 // Emit errors for each unterminated conditional on the stack, including
397 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000398 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000399 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000400 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
401 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000402 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000403 }
404
Chris Lattnerf64b3522008-03-09 01:54:53 +0000405 // Just return and let the caller lex after this #include.
406 break;
407 }
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattnerf64b3522008-03-09 01:54:53 +0000409 // If this token is not a preprocessor directive, just skip it.
410 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
411 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattnerf64b3522008-03-09 01:54:53 +0000413 // We just parsed a # character at the start of a line, so we're in
414 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000415 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000416 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000417 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000418
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattnerf64b3522008-03-09 01:54:53 +0000420 // Read the next token, the directive flavor.
421 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000422
Chris Lattnerf64b3522008-03-09 01:54:53 +0000423 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
424 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000425 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000426 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000427 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000428 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000429 continue;
430 }
431
432 // If the first letter isn't i or e, it isn't intesting to us. We know that
433 // this is safe in the face of spelling differences, because there is no way
434 // to spell an i/e in a strange way that is another letter. Skipping this
435 // allows us to avoid looking up the identifier info for #define/#undef and
436 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000437 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000438
Alp Toker2d57cea2014-05-17 04:53:25 +0000439 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000440 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000441 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000442 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000443 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000444 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000445 continue;
446 }
Mike Stump11289f42009-09-09 15:08:12 +0000447
Chris Lattnerf64b3522008-03-09 01:54:53 +0000448 // Get the identifier name without trigraphs or embedded newlines. Note
449 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
450 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000451 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000452 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000453 if (!Tok.needsCleaning() && RI.size() < 20) {
454 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000455 } else {
456 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000457 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000458 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000459 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000460 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000461 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000462 continue;
463 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000464 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000465 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000466 }
Mike Stump11289f42009-09-09 15:08:12 +0000467
Benjamin Kramer144884642009-12-31 13:32:38 +0000468 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000469 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000470 if (Sub.empty() || // "if"
471 Sub == "def" || // "ifdef"
472 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000473 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
474 // bother parsing the condition.
475 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000476 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000477 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000478 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000479 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000480 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000481 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000482 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000483 PPConditionalInfo CondInfo;
484 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000485 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000486 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000487 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000488
Chris Lattnerf64b3522008-03-09 01:54:53 +0000489 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000490 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000491 // Restore the value of LexingRawMode so that trailing comments
492 // are handled correctly, if we've reached the outermost block.
493 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000494 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000495 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000496 if (Callbacks)
497 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000498 break;
Richard Smithd0124572012-06-21 00:35:03 +0000499 } else {
500 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000501 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000502 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000503 // #else directive in a skipping conditional. If not in some other
504 // skipping conditional, and if #else hasn't already been seen, enter it
505 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000506 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000507
Chris Lattnerf64b3522008-03-09 01:54:53 +0000508 // If this is a #else with a #else before it, report the error.
509 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattnerf64b3522008-03-09 01:54:53 +0000511 // Note that we've seen a #else in this conditional.
512 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000513
Chris Lattnerf64b3522008-03-09 01:54:53 +0000514 // If the conditional is at the top level, and the #if block wasn't
515 // entered, enter the #else block now.
516 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
517 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000518 // Restore the value of LexingRawMode so that trailing comments
519 // are handled correctly.
520 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000521 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000522 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000523 if (Callbacks)
524 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000525 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000526 } else {
527 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000528 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000529 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000530 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000531
John Thompson17c35732013-12-04 20:19:30 +0000532 // If this is a #elif with a #else before it, report the error.
533 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
534
Chris Lattnerf64b3522008-03-09 01:54:53 +0000535 // If this is in a skipping block or if we're already handled this #if
536 // block, don't bother parsing the condition.
537 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
538 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000539 } else {
John Thompson17c35732013-12-04 20:19:30 +0000540 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000541 // Restore the value of LexingRawMode so that identifiers are
542 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000543 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
544 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000545 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000546 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000547 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000548 if (Callbacks) {
549 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000550 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000551 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000552 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000553 }
554 // If this condition is true, enter it!
555 if (CondValue) {
556 CondInfo.FoundNonSkip = true;
557 break;
558 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000559 }
560 }
561 }
Mike Stump11289f42009-09-09 15:08:12 +0000562
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000563 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000564 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000565 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000566 }
567
568 // Finally, if we are out of the conditional (saw an #endif or ran off the end
569 // of the file, just stop skipping and return to lexing whatever came after
570 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000571 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000572
573 if (Callbacks) {
574 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
575 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
576 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000577}
578
Ted Kremenek56572ab2008-12-12 18:34:08 +0000579void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000580 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000581 assert(CurPTHLexer);
582 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000583
Ted Kremenek56572ab2008-12-12 18:34:08 +0000584 // Skip to the next '#else', '#elif', or #endif.
585 if (CurPTHLexer->SkipBlock()) {
586 // We have reached an #endif. Both the '#' and 'endif' tokens
587 // have been consumed by the PTHLexer. Just pop off the condition level.
588 PPConditionalInfo CondInfo;
589 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000590 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000591 assert(!InCond && "Can't be skipping if not in a conditional!");
592 break;
593 }
Mike Stump11289f42009-09-09 15:08:12 +0000594
Ted Kremenek56572ab2008-12-12 18:34:08 +0000595 // We have reached a '#else' or '#elif'. Lex the next token to get
596 // the directive flavor.
597 Token Tok;
598 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000599
Ted Kremenek56572ab2008-12-12 18:34:08 +0000600 // We can actually look up the IdentifierInfo here since we aren't in
601 // raw mode.
602 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
603
604 if (K == tok::pp_else) {
605 // #else: Enter the else condition. We aren't in a nested condition
606 // since we skip those. We're always in the one matching the last
607 // blocked we skipped.
608 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
609 // Note that we've seen a #else in this conditional.
610 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000611
Ted Kremenek56572ab2008-12-12 18:34:08 +0000612 // If the #if block wasn't entered then enter the #else block now.
613 if (!CondInfo.FoundNonSkip) {
614 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000615
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000616 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000617 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000618 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000619 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000620
Ted Kremenek56572ab2008-12-12 18:34:08 +0000621 break;
622 }
Mike Stump11289f42009-09-09 15:08:12 +0000623
Ted Kremenek56572ab2008-12-12 18:34:08 +0000624 // Otherwise skip this block.
625 continue;
626 }
Mike Stump11289f42009-09-09 15:08:12 +0000627
Ted Kremenek56572ab2008-12-12 18:34:08 +0000628 assert(K == tok::pp_elif);
629 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
630
631 // If this is a #elif with a #else before it, report the error.
632 if (CondInfo.FoundElse)
633 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000634
Ted Kremenek56572ab2008-12-12 18:34:08 +0000635 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000636 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000637 if (CondInfo.FoundNonSkip)
638 continue;
639
640 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000641 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000642 CurPTHLexer->ParsingPreprocessorDirective = true;
643 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
644 CurPTHLexer->ParsingPreprocessorDirective = false;
645
646 // If this condition is true, enter it!
647 if (ShouldEnter) {
648 CondInfo.FoundNonSkip = true;
649 break;
650 }
651
652 // Otherwise, skip this block and go to the next one.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000653 }
654}
655
Richard Smith2a553082015-04-23 22:58:06 +0000656Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000657 if (!SourceMgr.isInMainFile(Loc)) {
658 // Try to determine the module of the include directive.
659 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
660 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
661 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
662 // The include comes from an included file.
663 return HeaderInfo.getModuleMap()
664 .findModuleForHeader(EntryOfIncl)
665 .getModule();
666 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000667 }
Richard Smith7e82e012016-02-19 22:25:36 +0000668
669 // This is either in the main file or not in a file at all. It belongs
670 // to the current module, if there is one.
671 return getLangOpts().CurrentModule.empty()
672 ? nullptr
673 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000674}
675
Richard Smith2a553082015-04-23 22:58:06 +0000676Module *Preprocessor::getModuleContainingLocation(SourceLocation Loc) {
677 return HeaderInfo.getModuleMap().inferModuleFromLocation(
678 FullSourceLoc(Loc, SourceMgr));
679}
680
Richard Smith4eb83932016-04-27 21:57:05 +0000681const FileEntry *
682Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
683 SourceLocation Loc) {
684 // If we have a module import syntax, we shouldn't include a header to
685 // make a particular module visible.
686 if (getLangOpts().ObjC2)
687 return nullptr;
688
689 // Figure out which module we'd want to import.
690 Module *M = getModuleContainingLocation(Loc);
691 if (!M)
692 return nullptr;
693
694 Module *TopM = M->getTopLevelModule();
695 Module *IncM = getModuleForLocation(IncLoc);
696
697 // Walk up through the include stack, looking through textual headers of M
698 // until we hit a non-textual header that we can #include. (We assume textual
699 // headers of a module with non-textual headers aren't meant to be used to
700 // import entities from the module.)
701 auto &SM = getSourceManager();
702 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
703 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
704 auto *FE = SM.getFileEntryForID(ID);
705
706 bool InTextualHeader = false;
707 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
708 if (!Header.getModule()->isSubModuleOf(TopM))
709 continue;
710
711 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
712 // If this is an accessible, non-textual header of M's top-level module
713 // that transitively includes the given location and makes the
714 // corresponding module visible, this is the thing to #include.
715 if (Header.isAccessibleFrom(IncM))
716 return FE;
717
718 // It's in a private header; we can't #include it.
719 // FIXME: If there's a public header in some module that re-exports it,
720 // then we could suggest including that, but it's not clear that's the
721 // expected way to make this entity visible.
722 continue;
723 }
724
725 InTextualHeader = true;
726 }
727
728 if (!InTextualHeader)
729 break;
730
731 Loc = SM.getIncludeLoc(ID);
732 }
733
734 return nullptr;
735}
736
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000737const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000738 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000739 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000740 bool isAngled,
741 const DirectoryLookup *FromDir,
Richard Smith25d50752014-10-20 00:15:49 +0000742 const FileEntry *FromFile,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000743 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000744 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000745 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000746 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000747 bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000748 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000749 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000750
Will Wilson0fafd342013-12-27 19:46:16 +0000751 // If the header lookup mechanism may be relative to the current inclusion
752 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000753 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
754 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000755 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000756 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000757 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000758 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000759
Chris Lattner022923a2009-02-04 19:45:07 +0000760 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000761 // predefines buffer or the module includes buffer. Any other file is not
762 // lexed with a normal lexer, so it won't be scanned for preprocessor
763 // directives.
764 //
765 // If we have the predefines buffer, resolve #include references (which come
766 // from the -include command line argument) from the current working
767 // directory instead of relative to the main file.
768 //
769 // If we have the module includes buffer, resolve #include references (which
770 // come from header declarations in the module map) relative to the module
771 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000772 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000773 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000774 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000775 BuildSystemModule = getCurrentModule()->IsSystem;
776 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000777 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000778 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
779 } else {
780 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
781 }
Will Wilson0fafd342013-12-27 19:46:16 +0000782
783 // MSVC searches the current include stack from top to bottom for
784 // headers included by quoted include directives.
785 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000786 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000787 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
788 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
789 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000790 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000791 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000792 }
Chris Lattner022923a2009-02-04 19:45:07 +0000793 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000794 }
Mike Stump11289f42009-09-09 15:08:12 +0000795
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000796 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000797
798 if (FromFile) {
799 // We're supposed to start looking from after a particular file. Search
800 // the include path until we find that file or run out of files.
801 const DirectoryLookup *TmpCurDir = CurDir;
802 const DirectoryLookup *TmpFromDir = nullptr;
803 while (const FileEntry *FE = HeaderInfo.LookupFile(
804 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000805 Includers, SearchPath, RelativePath, RequestingModule,
806 SuggestedModule, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000807 // Keep looking as if this file did a #include_next.
808 TmpFromDir = TmpCurDir;
809 ++TmpFromDir;
810 if (FE == FromFile) {
811 // Found it.
812 FromDir = TmpFromDir;
813 CurDir = TmpCurDir;
814 break;
815 }
816 }
817 }
818
819 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000820 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000821 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Manman Rene4a5d372016-05-17 02:15:12 +0000822 RelativePath, RequestingModule, SuggestedModule, SkipCache,
823 BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000824 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000825 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000826 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000827 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
828 Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000829 return FE;
830 }
Mike Stump11289f42009-09-09 15:08:12 +0000831
Will Wilson0fafd342013-12-27 19:46:16 +0000832 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000833 // Otherwise, see if this is a subframework header. If so, this is relative
834 // to one of the headers on the #include stack. Walk the list of the current
835 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000836 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000837 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000838 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000839 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000840 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000841 SuggestedModule))) {
842 if (SuggestedModule && !LangOpts.AsmPreprocessor)
843 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000844 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
845 Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000846 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000847 }
848 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000849 }
Mike Stump11289f42009-09-09 15:08:12 +0000850
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000851 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
852 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000853 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000854 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000855 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000856 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000857 RequestingModule, SuggestedModule))) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000858 if (SuggestedModule && !LangOpts.AsmPreprocessor)
859 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000860 RequestingModule, RequestingModuleIsModuleInterface,
861 FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000862 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000863 }
864 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000865 }
866 }
Mike Stump11289f42009-09-09 15:08:12 +0000867
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000868 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000869 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000870}
871
Chris Lattnerf64b3522008-03-09 01:54:53 +0000872//===----------------------------------------------------------------------===//
873// Preprocessor Directive Handling.
874//===----------------------------------------------------------------------===//
875
David Blaikied5321242012-06-06 18:52:13 +0000876class Preprocessor::ResetMacroExpansionHelper {
877public:
878 ResetMacroExpansionHelper(Preprocessor *pp)
879 : PP(pp), save(pp->DisableMacroExpansion) {
880 if (pp->MacroExpansionInDirectivesOverride)
881 pp->DisableMacroExpansion = false;
882 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000883
David Blaikied5321242012-06-06 18:52:13 +0000884 ~ResetMacroExpansionHelper() {
885 PP->DisableMacroExpansion = save;
886 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000887
David Blaikied5321242012-06-06 18:52:13 +0000888private:
889 Preprocessor *PP;
890 bool save;
891};
892
Chris Lattnerf64b3522008-03-09 01:54:53 +0000893/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000894/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000895/// lexer/preprocessor state, and advances the lexer(s) so that the next token
896/// read is the correct one.
897void Preprocessor::HandleDirective(Token &Result) {
898 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000899
Chris Lattnerf64b3522008-03-09 01:54:53 +0000900 // We just parsed a # character at the start of a line, so we're in directive
901 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000902 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000903 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000904 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000905
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000906 bool ImmediatelyAfterTopLevelIfndef =
907 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
908 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
909
Chris Lattnerf64b3522008-03-09 01:54:53 +0000910 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000911
Chris Lattnerf64b3522008-03-09 01:54:53 +0000912 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000913 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000914 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000915 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000916
Chris Lattner2d17ab72009-03-18 21:00:25 +0000917 // Save the '#' token in case we need to return it later.
918 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000919
Chris Lattnerf64b3522008-03-09 01:54:53 +0000920 // Read the next token, the directive flavor. This isn't expanded due to
921 // C99 6.10.3p8.
922 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000923
Chris Lattnerf64b3522008-03-09 01:54:53 +0000924 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
925 // #define A(x) #x
926 // A(abc
927 // #warning blah
928 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000929 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
930 // not support this for #include-like directives, since that can result in
931 // terrible diagnostics, and does not work in GCC.
932 if (InMacroArgs) {
933 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
934 switch (II->getPPKeywordID()) {
935 case tok::pp_include:
936 case tok::pp_import:
937 case tok::pp_include_next:
938 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000939 case tok::pp_pragma:
940 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000941 DiscardUntilEndOfDirective();
942 return;
943 default:
944 break;
945 }
946 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000947 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000948 }
Mike Stump11289f42009-09-09 15:08:12 +0000949
David Blaikied5321242012-06-06 18:52:13 +0000950 // Temporarily enable macro expansion if set so
951 // and reset to previous state when returning from this function.
952 ResetMacroExpansionHelper helper(this);
953
Chris Lattnerf64b3522008-03-09 01:54:53 +0000954 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000955 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000956 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000957 case tok::code_completion:
958 if (CodeComplete)
959 CodeComplete->CodeCompleteDirective(
960 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000961 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000962 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000963 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000964 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000965 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000966 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000967 default:
968 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000969 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000970
Chris Lattnerf64b3522008-03-09 01:54:53 +0000971 // Ask what the preprocessor keyword ID is.
972 switch (II->getPPKeywordID()) {
973 default: break;
974 // C99 6.10.1 - Conditional Inclusion.
975 case tok::pp_if:
976 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
977 case tok::pp_ifdef:
978 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
979 case tok::pp_ifndef:
980 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
981 case tok::pp_elif:
982 return HandleElifDirective(Result);
983 case tok::pp_else:
984 return HandleElseDirective(Result);
985 case tok::pp_endif:
986 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000987
Chris Lattnerf64b3522008-03-09 01:54:53 +0000988 // C99 6.10.2 - Source File Inclusion.
989 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000990 // Handle #include.
991 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000992 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000993 // Handle -imacros.
Taewook Oh755e4d22016-06-13 21:55:33 +0000994 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000995
Chris Lattnerf64b3522008-03-09 01:54:53 +0000996 // C99 6.10.3 - Macro Replacement.
997 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000998 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000999 case tok::pp_undef:
1000 return HandleUndefDirective(Result);
1001
1002 // C99 6.10.4 - Line Control.
1003 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +00001004 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001005
Chris Lattnerf64b3522008-03-09 01:54:53 +00001006 // C99 6.10.5 - Error Directive.
1007 case tok::pp_error:
1008 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +00001009
Chris Lattnerf64b3522008-03-09 01:54:53 +00001010 // C99 6.10.6 - Pragma Directive.
1011 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +00001012 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +00001013
Chris Lattnerf64b3522008-03-09 01:54:53 +00001014 // GNU Extensions.
1015 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001016 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001017 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001018 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00001019
Chris Lattnerf64b3522008-03-09 01:54:53 +00001020 case tok::pp_warning:
1021 Diag(Result, diag::ext_pp_warning_directive);
1022 return HandleUserDiagnosticDirective(Result, true);
1023 case tok::pp_ident:
1024 return HandleIdentSCCSDirective(Result);
1025 case tok::pp_sccs:
1026 return HandleIdentSCCSDirective(Result);
1027 case tok::pp_assert:
1028 //isExtension = true; // FIXME: implement #assert
1029 break;
1030 case tok::pp_unassert:
1031 //isExtension = true; // FIXME: implement #unassert
1032 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001033
Douglas Gregor663b48f2012-01-03 19:48:16 +00001034 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001035 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001036 return HandleMacroPublicDirective(Result);
1037 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001038
Douglas Gregor663b48f2012-01-03 19:48:16 +00001039 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001040 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001041 return HandleMacroPrivateDirective(Result);
1042 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001043 }
1044 break;
1045 }
Mike Stump11289f42009-09-09 15:08:12 +00001046
Chris Lattner2d17ab72009-03-18 21:00:25 +00001047 // If this is a .S file, treat unknown # directives as non-preprocessor
1048 // directives. This is important because # may be a comment or introduce
1049 // various pseudo-ops. Just return the # token and push back the following
1050 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001051 if (getLangOpts().AsmPreprocessor) {
David Blaikie2eabcc92016-02-09 18:52:09 +00001052 auto Toks = llvm::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001053 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001054 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001055 Toks[1] = Result;
Taewook Oh755e4d22016-06-13 21:55:33 +00001056
Chris Lattner56f64c12011-01-06 05:01:51 +00001057 // If the second token is a hashhash token, then we need to translate it to
1058 // unknown so the token lexer doesn't try to perform token pasting.
1059 if (Result.is(tok::hashhash))
1060 Toks[1].setKind(tok::unknown);
Taewook Oh755e4d22016-06-13 21:55:33 +00001061
Chris Lattner2d17ab72009-03-18 21:00:25 +00001062 // Enter this token stream so that we re-lex the tokens. Make sure to
1063 // enable macro expansion, in case the token after the # is an identifier
1064 // that is expanded.
David Blaikie2eabcc92016-02-09 18:52:09 +00001065 EnterTokenStream(std::move(Toks), 2, false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001066 return;
1067 }
Mike Stump11289f42009-09-09 15:08:12 +00001068
Chris Lattnerf64b3522008-03-09 01:54:53 +00001069 // If we reached here, the preprocessing token is not valid!
1070 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001071
Chris Lattnerf64b3522008-03-09 01:54:53 +00001072 // Read the rest of the PP line.
1073 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001074
Chris Lattnerf64b3522008-03-09 01:54:53 +00001075 // Okay, we're done parsing the directive.
1076}
1077
Chris Lattner76e68962009-01-26 06:19:46 +00001078/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1079/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1080static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001081 unsigned DiagID, Preprocessor &PP,
1082 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001083 if (DigitTok.isNot(tok::numeric_constant)) {
1084 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001085
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001086 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001087 PP.DiscardUntilEndOfDirective();
1088 return true;
1089 }
Mike Stump11289f42009-09-09 15:08:12 +00001090
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001091 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001092 IntegerBuffer.resize(DigitTok.getLength());
1093 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001094 bool Invalid = false;
1095 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1096 if (Invalid)
1097 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001098
Chris Lattnerd66f1722009-04-18 18:35:15 +00001099 // Verify that we have a simple digit-sequence, and compute the value. This
1100 // is always a simple digit string computed in decimal, so we do this manually
1101 // here.
1102 Val = 0;
1103 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001104 // C++1y [lex.fcon]p1:
1105 // Optional separating single quotes in a digit-sequence are ignored
1106 if (DigitTokBegin[i] == '\'')
1107 continue;
1108
Jordan Rosea7d03842013-02-08 22:30:41 +00001109 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001110 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001111 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001112 PP.DiscardUntilEndOfDirective();
1113 return true;
1114 }
Mike Stump11289f42009-09-09 15:08:12 +00001115
Chris Lattnerd66f1722009-04-18 18:35:15 +00001116 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1117 if (NextVal < Val) { // overflow.
1118 PP.Diag(DigitTok, DiagID);
1119 PP.DiscardUntilEndOfDirective();
1120 return true;
1121 }
1122 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001123 }
Mike Stump11289f42009-09-09 15:08:12 +00001124
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001125 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001126 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1127 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001128
Chris Lattner76e68962009-01-26 06:19:46 +00001129 return false;
1130}
1131
James Dennettf6333ac2012-06-22 05:46:07 +00001132/// \brief Handle a \#line directive: C99 6.10.4.
1133///
1134/// The two acceptable forms are:
1135/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001136/// # line digit-sequence
1137/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001138/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001139void Preprocessor::HandleLineDirective(Token &Tok) {
1140 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1141 // expanded.
1142 Token DigitTok;
1143 Lex(DigitTok);
1144
Chris Lattner100c65e2009-01-26 05:29:08 +00001145 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001146 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001147 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001148 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001149
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001150 if (LineNo == 0)
1151 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001152
Chris Lattner76e68962009-01-26 06:19:46 +00001153 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1154 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001155 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001156 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001157 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001158 if (LineNo >= LineLimit)
1159 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001160 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001161 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001162
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001163 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001164 Token StrTok;
1165 Lex(StrTok);
1166
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001167 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1168 // string followed by eod.
1169 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001170 ; // ok
1171 else if (StrTok.isNot(tok::string_literal)) {
1172 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001173 return DiscardUntilEndOfDirective();
1174 } else if (StrTok.hasUDSuffix()) {
1175 Diag(StrTok, diag::err_invalid_string_udl);
1176 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001177 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001178 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001179 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001180 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001181 if (Literal.hadError)
1182 return DiscardUntilEndOfDirective();
1183 if (Literal.Pascal) {
1184 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1185 return DiscardUntilEndOfDirective();
1186 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001187 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001188
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001189 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001190 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1191 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001192 }
Mike Stump11289f42009-09-09 15:08:12 +00001193
Chris Lattner1eaa70a2009-02-03 21:52:55 +00001194 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +00001195
Chris Lattner839150e2009-03-27 17:13:49 +00001196 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001197 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1198 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +00001199 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +00001200}
1201
Chris Lattner76e68962009-01-26 06:19:46 +00001202/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1203/// marker directive.
1204static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1205 bool &IsSystemHeader, bool &IsExternCHeader,
1206 Preprocessor &PP) {
1207 unsigned FlagVal;
1208 Token FlagTok;
1209 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001210 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001211 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1212 return true;
1213
1214 if (FlagVal == 1) {
1215 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001216
Chris Lattner76e68962009-01-26 06:19:46 +00001217 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001218 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001219 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1220 return true;
1221 } else if (FlagVal == 2) {
1222 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001223
Chris Lattner1c967782009-02-04 06:25:26 +00001224 SourceManager &SM = PP.getSourceManager();
1225 // If we are leaving the current presumed file, check to make sure the
1226 // presumed include stack isn't empty!
1227 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001228 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001229 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001230 if (PLoc.isInvalid())
1231 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001232
Chris Lattner1c967782009-02-04 06:25:26 +00001233 // If there is no include loc (main file) or if the include loc is in a
1234 // different physical file, then we aren't in a "1" line marker flag region.
1235 SourceLocation IncLoc = PLoc.getIncludeLoc();
1236 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001237 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001238 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1239 PP.DiscardUntilEndOfDirective();
1240 return true;
1241 }
Mike Stump11289f42009-09-09 15:08:12 +00001242
Chris Lattner76e68962009-01-26 06:19:46 +00001243 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001244 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001245 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1246 return true;
1247 }
1248
1249 // We must have 3 if there are still flags.
1250 if (FlagVal != 3) {
1251 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001252 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001253 return true;
1254 }
Mike Stump11289f42009-09-09 15:08:12 +00001255
Chris Lattner76e68962009-01-26 06:19:46 +00001256 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001257
Chris Lattner76e68962009-01-26 06:19:46 +00001258 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001259 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001260 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001261 return true;
1262
1263 // We must have 4 if there is yet another flag.
1264 if (FlagVal != 4) {
1265 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001266 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001267 return true;
1268 }
Mike Stump11289f42009-09-09 15:08:12 +00001269
Chris Lattner76e68962009-01-26 06:19:46 +00001270 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001271
Chris Lattner76e68962009-01-26 06:19:46 +00001272 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001273 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001274
1275 // There are no more valid flags here.
1276 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001277 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001278 return true;
1279}
1280
1281/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1282/// one of the following forms:
1283///
1284/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001285/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001286/// # 42 "file" ('1' | '2')? '3' '4'?
1287///
1288void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1289 // Validate the number and convert it to an unsigned. GNU does not have a
1290 // line # limit other than it fit in 32-bits.
1291 unsigned LineNo;
1292 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001293 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001294 return;
Mike Stump11289f42009-09-09 15:08:12 +00001295
Chris Lattner76e68962009-01-26 06:19:46 +00001296 Token StrTok;
1297 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001298
Chris Lattner76e68962009-01-26 06:19:46 +00001299 bool IsFileEntry = false, IsFileExit = false;
1300 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001301 int FilenameID = -1;
1302
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001303 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1304 // string followed by eod.
1305 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001306 ; // ok
1307 else if (StrTok.isNot(tok::string_literal)) {
1308 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001309 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001310 } else if (StrTok.hasUDSuffix()) {
1311 Diag(StrTok, diag::err_invalid_string_udl);
1312 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001313 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001314 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001315 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001316 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001317 if (Literal.hadError)
1318 return DiscardUntilEndOfDirective();
1319 if (Literal.Pascal) {
1320 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1321 return DiscardUntilEndOfDirective();
1322 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001323 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001324
Chris Lattner76e68962009-01-26 06:19:46 +00001325 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001326 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001327 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001328 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001331 // Create a line note with this information.
1332 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001333 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001334 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001335
Chris Lattner839150e2009-03-27 17:13:49 +00001336 // If the preprocessor has callbacks installed, notify them of the #line
1337 // change. This is used so that the line marker comes out in -E mode for
1338 // example.
1339 if (Callbacks) {
1340 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1341 if (IsFileEntry)
1342 Reason = PPCallbacks::EnterFile;
1343 else if (IsFileExit)
1344 Reason = PPCallbacks::ExitFile;
1345 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1346 if (IsExternCHeader)
1347 FileKind = SrcMgr::C_ExternCSystem;
1348 else if (IsSystemHeader)
1349 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001350
Chris Lattnerc745cec2010-04-14 04:28:50 +00001351 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001352 }
Chris Lattner76e68962009-01-26 06:19:46 +00001353}
1354
Chris Lattner38d7fd22009-01-26 05:30:54 +00001355/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1356///
Mike Stump11289f42009-09-09 15:08:12 +00001357void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001358 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001359 // PTH doesn't emit #warning or #error directives.
1360 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001361 return CurPTHLexer->DiscardToEndOfLine();
1362
Chris Lattnerf64b3522008-03-09 01:54:53 +00001363 // Read the rest of the line raw. We do this because we don't want macros
1364 // to be expanded and we don't require that the tokens be valid preprocessing
1365 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1366 // collapse multiple consequtive white space between tokens, but this isn't
1367 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001368 SmallString<128> Message;
1369 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001370
1371 // Find the first non-whitespace character, so that we can make the
1372 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001373 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001374
Chris Lattner100c65e2009-01-26 05:29:08 +00001375 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001376 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001377 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001378 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001379}
1380
1381/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1382///
1383void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1384 // Yes, this directive is an extension.
1385 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001386
Chris Lattnerf64b3522008-03-09 01:54:53 +00001387 // Read the string argument.
1388 Token StrTok;
1389 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001390
Chris Lattnerf64b3522008-03-09 01:54:53 +00001391 // If the token kind isn't a string, it's a malformed directive.
1392 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001393 StrTok.isNot(tok::wide_string_literal)) {
1394 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001395 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001396 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001397 return;
1398 }
Mike Stump11289f42009-09-09 15:08:12 +00001399
Richard Smithd67aea22012-03-06 03:21:47 +00001400 if (StrTok.hasUDSuffix()) {
1401 Diag(StrTok, diag::err_invalid_string_udl);
1402 return DiscardUntilEndOfDirective();
1403 }
1404
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001405 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001406 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001407
Douglas Gregordc970f02010-03-16 22:30:13 +00001408 if (Callbacks) {
1409 bool Invalid = false;
1410 std::string Str = getSpelling(StrTok, &Invalid);
1411 if (!Invalid)
1412 Callbacks->Ident(Tok.getLocation(), Str);
1413 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001414}
1415
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001416/// \brief Handle a #public directive.
1417void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001418 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001419 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001420
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001421 // Error reading macro name? If so, diagnostic already issued.
1422 if (MacroNameTok.is(tok::eod))
1423 return;
1424
Douglas Gregor663b48f2012-01-03 19:48:16 +00001425 // Check to see if this is the last token on the #__public_macro line.
1426 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001427
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001428 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001429 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001430 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001431
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001432 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001433 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001434 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001435 return;
1436 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001437
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001438 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001439 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1440 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001441}
1442
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001443/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001444void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1445 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001446 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001447
Douglas Gregorebf00492011-10-17 15:32:29 +00001448 // Error reading macro name? If so, diagnostic already issued.
1449 if (MacroNameTok.is(tok::eod))
1450 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001451
Douglas Gregor663b48f2012-01-03 19:48:16 +00001452 // Check to see if this is the last token on the #__private_macro line.
1453 CheckEndOfDirective("__private_macro");
Taewook Oh755e4d22016-06-13 21:55:33 +00001454
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001455 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001456 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001457 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001458
Douglas Gregorebf00492011-10-17 15:32:29 +00001459 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001460 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001461 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001462 return;
1463 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001464
Douglas Gregorebf00492011-10-17 15:32:29 +00001465 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001466 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1467 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001468}
1469
Chris Lattnerf64b3522008-03-09 01:54:53 +00001470//===----------------------------------------------------------------------===//
1471// Preprocessor Include Directive Handling.
1472//===----------------------------------------------------------------------===//
1473
1474/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001475/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001476/// true if the input filename was in <>'s or false if it were in ""'s. The
1477/// caller is expected to provide a buffer that is large enough to hold the
1478/// spelling of the filename, but is also expected to handle the case when
1479/// this method decides to use a different buffer.
1480bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001481 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001482 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001483 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001484
Chris Lattnerf64b3522008-03-09 01:54:53 +00001485 // Make sure the filename is <x> or "x".
1486 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001487 if (Buffer[0] == '<') {
1488 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001489 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001490 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001491 return true;
1492 }
1493 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001494 } else if (Buffer[0] == '"') {
1495 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001496 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001497 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001498 return true;
1499 }
1500 isAngled = false;
1501 } else {
1502 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001503 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001504 return true;
1505 }
Mike Stump11289f42009-09-09 15:08:12 +00001506
Chris Lattnerf64b3522008-03-09 01:54:53 +00001507 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001508 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001509 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001510 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001511 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001512 }
Mike Stump11289f42009-09-09 15:08:12 +00001513
Chris Lattnerf64b3522008-03-09 01:54:53 +00001514 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001515 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001516 return isAngled;
1517}
1518
James Dennett4a4f72d2013-11-27 01:27:40 +00001519// \brief Handle cases where the \#include name is expanded from a macro
1520// as multiple tokens, which need to be glued together.
1521//
1522// This occurs for code like:
1523// \code
1524// \#define FOO <a/b.h>
1525// \#include FOO
1526// \endcode
1527// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1528//
1529// This code concatenates and consumes tokens up to the '>' token. It returns
1530// false if the > was found, otherwise it returns true if it finds and consumes
1531// the EOD marker.
1532bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001533 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001534 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001535
John Thompsonb5353522009-10-30 13:49:06 +00001536 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001537 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001538 End = CurTok.getLocation();
Taewook Oh755e4d22016-06-13 21:55:33 +00001539
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001540 // FIXME: Provide code completion for #includes.
1541 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001542 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001543 Lex(CurTok);
1544 continue;
1545 }
1546
Chris Lattnerf64b3522008-03-09 01:54:53 +00001547 // Append the spelling of this token to the buffer. If there was a space
1548 // before it, add it now.
1549 if (CurTok.hasLeadingSpace())
1550 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001551
Chris Lattnerf64b3522008-03-09 01:54:53 +00001552 // Get the spelling of the token, directly into FilenameBuffer if possible.
1553 unsigned PreAppendSize = FilenameBuffer.size();
1554 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001555
Chris Lattnerf64b3522008-03-09 01:54:53 +00001556 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001557 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001558
Chris Lattnerf64b3522008-03-09 01:54:53 +00001559 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1560 if (BufPtr != &FilenameBuffer[PreAppendSize])
1561 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001562
Chris Lattnerf64b3522008-03-09 01:54:53 +00001563 // Resize FilenameBuffer to the correct size.
1564 if (CurTok.getLength() != ActualLen)
1565 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001566
Chris Lattnerf64b3522008-03-09 01:54:53 +00001567 // If we found the '>' marker, return success.
1568 if (CurTok.is(tok::greater))
1569 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001570
John Thompsonb5353522009-10-30 13:49:06 +00001571 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001572 }
1573
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001574 // If we hit the eod marker, emit an error and return true so that the caller
1575 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001576 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001577 return true;
1578}
1579
Richard Smith34f30512013-11-23 04:06:09 +00001580/// \brief Push a token onto the token stream containing an annotation.
1581static void EnterAnnotationToken(Preprocessor &PP,
1582 SourceLocation Begin, SourceLocation End,
1583 tok::TokenKind Kind, void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001584 // FIXME: Produce this as the current token directly, rather than
1585 // allocating a new token for it.
David Blaikie2eabcc92016-02-09 18:52:09 +00001586 auto Tok = llvm::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001587 Tok[0].startToken();
1588 Tok[0].setKind(Kind);
1589 Tok[0].setLocation(Begin);
1590 Tok[0].setAnnotationEndLoc(End);
1591 Tok[0].setAnnotationValue(AnnotationVal);
David Blaikie2eabcc92016-02-09 18:52:09 +00001592 PP.EnterTokenStream(std::move(Tok), 1, true);
Richard Smith34f30512013-11-23 04:06:09 +00001593}
1594
Richard Smith63b6fce2015-05-18 04:45:41 +00001595/// \brief Produce a diagnostic informing the user that a #include or similar
1596/// was implicitly treated as a module import.
1597static void diagnoseAutoModuleImport(
1598 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1599 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1600 SourceLocation PathEnd) {
1601 assert(PP.getLangOpts().ObjC2 && "no import syntax available");
1602
1603 SmallString<128> PathString;
1604 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1605 if (I)
1606 PathString += '.';
1607 PathString += Path[I].first->getName();
1608 }
1609 int IncludeKind = 0;
Taewook Oh755e4d22016-06-13 21:55:33 +00001610
Richard Smith63b6fce2015-05-18 04:45:41 +00001611 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1612 case tok::pp_include:
1613 IncludeKind = 0;
1614 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001615
Richard Smith63b6fce2015-05-18 04:45:41 +00001616 case tok::pp_import:
1617 IncludeKind = 1;
Taewook Oh755e4d22016-06-13 21:55:33 +00001618 break;
1619
Richard Smith63b6fce2015-05-18 04:45:41 +00001620 case tok::pp_include_next:
1621 IncludeKind = 2;
1622 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001623
Richard Smith63b6fce2015-05-18 04:45:41 +00001624 case tok::pp___include_macros:
1625 IncludeKind = 3;
1626 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001627
Richard Smith63b6fce2015-05-18 04:45:41 +00001628 default:
1629 llvm_unreachable("unknown include directive kind");
1630 }
1631
1632 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1633 /*IsTokenRange=*/false);
1634 PP.Diag(HashLoc, diag::warn_auto_module_import)
1635 << IncludeKind << PathString
1636 << FixItHint::CreateReplacement(ReplaceRange,
1637 ("@import " + PathString + ";").str());
1638}
1639
Taewook Ohf42103c2016-06-13 20:40:21 +00001640// Given a vector of path components and a string containing the real
1641// path to the file, build a properly-cased replacement in the vector,
1642// and return true if the replacement should be suggested.
1643static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1644 StringRef RealPathName) {
1645 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1646 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1647 int Cnt = 0;
1648 bool SuggestReplacement = false;
1649 // Below is a best-effort to handle ".." in paths. It is admittedly
1650 // not 100% correct in the presence of symlinks.
1651 for (auto &Component : llvm::reverse(Components)) {
1652 if ("." == Component) {
1653 } else if (".." == Component) {
1654 ++Cnt;
1655 } else if (Cnt) {
1656 --Cnt;
1657 } else if (RealPathComponentIter != RealPathComponentEnd) {
1658 if (Component != *RealPathComponentIter) {
1659 // If these path components differ by more than just case, then we
1660 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1661 // noisy false positives.
1662 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1663 if (!SuggestReplacement)
1664 break;
1665 Component = *RealPathComponentIter;
1666 }
1667 ++RealPathComponentIter;
1668 }
1669 }
1670 return SuggestReplacement;
1671}
1672
James Dennettf6333ac2012-06-22 05:46:07 +00001673/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1674/// the file to be included from the lexer, then include it! This is a common
1675/// routine with functionality shared between \#include, \#include_next and
1676/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001677/// specifies the file to start searching from.
Taewook Oh755e4d22016-06-13 21:55:33 +00001678void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001679 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001680 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001681 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001682 bool isImport) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001683 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001684 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001685
Chris Lattnerf64b3522008-03-09 01:54:53 +00001686 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001687 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001688 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001689 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001690 SourceLocation CharEnd; // the end of this directive, in characters
Taewook Oh755e4d22016-06-13 21:55:33 +00001691
Chris Lattnerf64b3522008-03-09 01:54:53 +00001692 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001693 case tok::eod:
1694 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001695 return;
Mike Stump11289f42009-09-09 15:08:12 +00001696
Chris Lattnerf64b3522008-03-09 01:54:53 +00001697 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001698 case tok::string_literal:
1699 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001700 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001701 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001702 break;
Mike Stump11289f42009-09-09 15:08:12 +00001703
Chris Lattnerf64b3522008-03-09 01:54:53 +00001704 case tok::less:
1705 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1706 // case, glue the tokens together into FilenameBuffer and interpret those.
1707 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001708 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001709 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001710 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001711 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001712 break;
1713 default:
1714 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1715 DiscardUntilEndOfDirective();
1716 return;
1717 }
Mike Stump11289f42009-09-09 15:08:12 +00001718
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001719 CharSourceRange FilenameRange
1720 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001721 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001722 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001723 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001724 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1725 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001726 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001727 DiscardUntilEndOfDirective();
1728 return;
1729 }
Mike Stump11289f42009-09-09 15:08:12 +00001730
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001731 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001732 // we allow macros that expand to nothing after the filename, because this
1733 // falls into the category of "#include pp-tokens new-line" specified in
1734 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001735 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001736
1737 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001738 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1739 Diag(FilenameTok, diag::err_pp_include_too_deep);
1740 return;
1741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
John McCall32f5fe12011-09-30 05:12:12 +00001743 // Complain about attempts to #include files in an audit pragma.
1744 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1745 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1746 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1747
1748 // Immediately leave the pragma.
1749 PragmaARCCFCodeAuditedLoc = SourceLocation();
1750 }
1751
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001752 // Complain about attempts to #include files in an assume-nonnull pragma.
1753 if (PragmaAssumeNonNullLoc.isValid()) {
1754 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1755 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1756
1757 // Immediately leave the pragma.
1758 PragmaAssumeNonNullLoc = SourceLocation();
1759 }
1760
Aaron Ballman611306e2012-03-02 22:51:54 +00001761 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001762 // Map the filename with the brackets still attached. If the name doesn't
1763 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001764 // spelling for.
1765 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1766 if (!NewName.empty())
1767 Filename = NewName;
1768 }
1769
Chris Lattnerf64b3522008-03-09 01:54:53 +00001770 // Search include directories.
1771 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001772 SmallString<1024> SearchPath;
1773 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001774 // We get the raw path only if we have 'Callbacks' to which we later pass
1775 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001776 ModuleMap::KnownHeader SuggestedModule;
1777 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001778 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001779 if (LangOpts.MSVCCompat) {
1780 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001781#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001782 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001783#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001784 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001785 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001786 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001787 isAngled, LookupFrom, LookupFromFile, CurDir,
1788 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001789 &SuggestedModule);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001790
Richard Smithdbbc5232015-05-14 02:25:44 +00001791 if (!File) {
1792 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001793 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001794 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001795 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1796 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1797 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001798 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001799 HeaderInfo.AddSearchPath(DL, isAngled);
Taewook Oh755e4d22016-06-13 21:55:33 +00001800
Douglas Gregor11729f02011-11-30 18:12:06 +00001801 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001802 File = LookupFile(
1803 FilenameLoc,
1804 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1805 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001806 &SuggestedModule, /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001807 }
1808 }
1809 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001810
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001811 if (!SuppressIncludeNotFoundError) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001812 // If the file could not be located and it was included via angle
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001813 // brackets, we can attempt a lookup as though it were a quoted path to
1814 // provide the user with a possible fixit.
1815 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001816 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001817 FilenameLoc,
1818 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1819 LookupFrom, LookupFromFile, CurDir,
1820 Callbacks ? &SearchPath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001821 Callbacks ? &RelativePath : nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001822 &SuggestedModule);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001823 if (File) {
1824 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001825 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1826 Filename <<
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001827 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1828 }
1829 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001830
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001831 // If the file is still not found, just go with the vanilla diagnostic
1832 if (!File)
1833 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1834 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001835 }
1836
Richard Smith63b6fce2015-05-18 04:45:41 +00001837 // Should we enter the source file? Set to false if either the source file is
1838 // known to have no effect beyond its effect on module visibility -- that is,
1839 // if it's got an include guard that is already defined or is a modular header
1840 // we've imported or already built.
1841 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001842
Richard Smith63b6fce2015-05-18 04:45:41 +00001843 // Determine whether we should try to import the module for this #include, if
1844 // there is one. Don't do so if precompiled module support is disabled or we
1845 // are processing this module textually (because we're building the module).
1846 if (File && SuggestedModule && getLangOpts().Modules &&
1847 SuggestedModule.getModule()->getTopLevelModuleName() !=
Richard Smith7e82e012016-02-19 22:25:36 +00001848 getLangOpts().CurrentModule) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001849 // If this include corresponds to a module but that module is
1850 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001851 // FIXME: Remove this; loadModule does the same check (but produces
1852 // slightly worse diagnostics).
1853 if (!SuggestedModule.getModule()->isAvailable() &&
Richard Smith68935702016-04-12 20:20:33 +00001854 !SuggestedModule.getModule()
1855 ->getTopLevelModule()
1856 ->HasIncompatibleModuleFile) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001857 clang::Module::Requirement Requirement;
1858 clang::Module::UnresolvedHeaderDirective MissingHeader;
1859 Module *M = SuggestedModule.getModule();
1860 // Identify the cause.
1861 (void)M->isAvailable(getLangOpts(), getTargetInfo(), Requirement,
1862 MissingHeader);
1863 if (MissingHeader.FileNameLoc.isValid()) {
1864 Diag(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1865 << MissingHeader.IsUmbrella << MissingHeader.FileName;
1866 } else {
1867 Diag(M->DefinitionLoc, diag::err_module_unavailable)
1868 << M->getFullModuleName() << Requirement.second << Requirement.first;
1869 }
1870 Diag(FilenameTok.getLocation(),
1871 diag::note_implicit_top_level_module_import_here)
1872 << M->getTopLevelModuleName();
1873 return;
1874 }
1875
Douglas Gregor71944202011-11-30 00:36:36 +00001876 // Compute the module access path corresponding to this module.
1877 // FIXME: Should we have a second loadModule() overload to avoid this
1878 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001879 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001880 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001881 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1882 FilenameTok.getLocation()));
1883 std::reverse(Path.begin(), Path.end());
1884
Douglas Gregor41e115a2011-11-30 18:02:36 +00001885 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001886 // We only do this in Objective-C, where we have a module-import syntax.
1887 if (getLangOpts().ObjC2)
1888 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001889
Richard Smith10434f32015-05-02 02:08:26 +00001890 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001891 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001892 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1893 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001894 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1895 IncludeTok.getLocation(), Path, Module::Hidden,
1896 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001897 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001898 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001899
Richard Smith63b6fce2015-05-18 04:45:41 +00001900 if (Imported)
1901 ShouldEnter = false;
1902 else if (Imported.isMissingExpected()) {
1903 // We failed to find a submodule that we assumed would exist (because it
1904 // was in the directory of an umbrella header, for instance), but no
1905 // actual module exists for it (because the umbrella header is
1906 // incomplete). Treat this as a textual inclusion.
1907 SuggestedModule = ModuleMap::KnownHeader();
1908 } else {
1909 // We hit an error processing the import. Bail out.
1910 if (hadModuleLoaderFatalFailure()) {
1911 // With a fatal failure in the module loader, we abort parsing.
1912 Token &Result = IncludeTok;
1913 if (CurLexer) {
1914 Result.startToken();
1915 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1916 CurLexer->cutOffLexing();
1917 } else {
1918 assert(CurPTHLexer && "#include but no current lexer set!");
1919 CurPTHLexer->getEOF(Result);
1920 }
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001921 }
1922 return;
1923 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001924 }
1925
Richard Smith63b6fce2015-05-18 04:45:41 +00001926 if (Callbacks) {
1927 // Notify the callback object that we've seen an inclusion directive.
1928 Callbacks->InclusionDirective(
1929 HashLoc, IncludeTok,
1930 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1931 FilenameRange, File, SearchPath, RelativePath,
1932 ShouldEnter ? nullptr : SuggestedModule.getModule());
Douglas Gregor97eec242011-09-15 22:00:41 +00001933 }
Richard Smith63b6fce2015-05-18 04:45:41 +00001934
1935 if (!File)
1936 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001937
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001938 // The #included file will be considered to be a system header if either it is
1939 // in a system include directory, or if the #includer is a system include
1940 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001941 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001942 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001943 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001944
Richard Smith54ef4c32015-05-19 19:58:11 +00001945 // FIXME: If we have a suggested module, and we've already visited this file,
1946 // don't bother entering it again. We know it has no further effect.
1947
Taewook Ohf42103c2016-06-13 20:40:21 +00001948 // Issue a diagnostic if the name of the file on disk has a different case
1949 // than the one we're about to open.
1950 const bool CheckIncludePathPortability =
1951 File && !File->tryGetRealPathName().empty();
1952
1953 if (CheckIncludePathPortability) {
1954 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
1955 StringRef RealPathName = File->tryGetRealPathName();
1956 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
1957 llvm::sys::path::end(Name));
1958
1959 if (trySimplifyPath(Components, RealPathName)) {
1960 SmallString<128> Path;
1961 Path.reserve(Name.size()+2);
1962 Path.push_back(isAngled ? '<' : '"');
1963 for (auto Component : Components) {
1964 Path.append(Component);
1965 // Append the separator the user used, or the close quote
1966 Path.push_back(
1967 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
1968 (isAngled ? '>' : '"'));
1969 }
1970 auto Replacement = Path.str().str();
1971 // For user files and known standard headers, by default we issue a diagnostic.
1972 // For other system headers, we don't. They can be controlled separately.
1973 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
1974 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
1975 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1976 Diag(FilenameTok, DiagId) << Replacement <<
1977 FixItHint::CreateReplacement(Range, Replacement);
1978 }
1979 }
1980
Chris Lattner72286d62010-04-19 20:44:31 +00001981 // Ask HeaderInfo if we should enter this #include file. If not, #including
Richard Smith54ef4c32015-05-19 19:58:11 +00001982 // this file will have no effect.
Richard Smith63b6fce2015-05-18 04:45:41 +00001983 if (ShouldEnter &&
Richard Smith035f6dc2015-07-01 01:51:38 +00001984 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
1985 SuggestedModule.getModule())) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001986 ShouldEnter = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001987 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001988 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Richard Smith63b6fce2015-05-18 04:45:41 +00001989 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001990
Richard Smith63b6fce2015-05-18 04:45:41 +00001991 // If we don't need to enter the file, stop now.
1992 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001993 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00001994 if (auto *M = SuggestedModule.getModule()) {
1995 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00001996
1997 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
1998 tok::pp___include_macros)
Richard Smitha0aafa32015-05-18 03:52:30 +00001999 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00002000 }
Chris Lattner72286d62010-04-19 20:44:31 +00002001 return;
2002 }
2003
Chris Lattnerf64b3522008-03-09 01:54:53 +00002004 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002005 SourceLocation IncludePos = End;
2006 // If the filename string was the result of macro expansions, set the include
2007 // position on the file where it will be included and after the expansions.
2008 if (IncludePos.isMacroID())
2009 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
2010 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002011 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002012
Richard Smith34f30512013-11-23 04:06:09 +00002013 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002014 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
2015 return;
Richard Smith34f30512013-11-23 04:06:09 +00002016
Richard Smitha0aafa32015-05-18 03:52:30 +00002017 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002018 if (auto *M = SuggestedModule.getModule()) {
Richard Smith67294e22014-01-31 20:47:44 +00002019 assert(!CurSubmodule && "should not have marked this as a module yet");
Richard Smitha0aafa32015-05-18 03:52:30 +00002020 CurSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002021
Richard Smitha0aafa32015-05-18 03:52:30 +00002022 // Let the macro handling code know that any future macros are within
2023 // the new submodule.
2024 EnterSubmodule(M, HashLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002025
Richard Smitha0aafa32015-05-18 03:52:30 +00002026 // Let the parser know that any future declarations are within the new
2027 // submodule.
2028 // FIXME: There's no point doing this if we're handling a #__include_macros
2029 // directive.
2030 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00002031 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002032}
2033
James Dennettf6333ac2012-06-22 05:46:07 +00002034/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002035///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002036void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2037 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002038 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002039
Chris Lattnerf64b3522008-03-09 01:54:53 +00002040 // #include_next is like #include, except that we start searching after
2041 // the current found directory. If we can't do this, issue a
2042 // diagnostic.
2043 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002044 const FileEntry *LookupFromFile = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002045 if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002046 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002047 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00002048 } else if (CurSubmodule) {
2049 // Start looking up in the directory *after* the one in which the current
2050 // file would be found, if any.
2051 assert(CurPPLexer && "#include_next directive in macro?");
2052 LookupFromFile = CurPPLexer->getFileEntry();
2053 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002054 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002055 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2056 } else {
2057 // Start looking up in the next directory.
2058 ++Lookup;
2059 }
Mike Stump11289f42009-09-09 15:08:12 +00002060
Richard Smith25d50752014-10-20 00:15:49 +00002061 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2062 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002063}
2064
James Dennettf6333ac2012-06-22 05:46:07 +00002065/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002066void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2067 // The Microsoft #import directive takes a type library and generates header
2068 // files from it, and includes those. This is beyond the scope of what clang
2069 // does, so we ignore it and error out. However, #import can optionally have
2070 // trailing attributes that span multiple lines. We're going to eat those
2071 // so we can continue processing from there.
2072 Diag(Tok, diag::err_pp_import_directive_ms );
2073
Taewook Oh755e4d22016-06-13 21:55:33 +00002074 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002075 // directive can be split over multiple lines using the backslash character.
2076 DiscardUntilEndOfDirective();
2077}
2078
James Dennettf6333ac2012-06-22 05:46:07 +00002079/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002080///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002081void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2082 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00002083 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002084 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002085 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002086 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002087 }
Richard Smith25d50752014-10-20 00:15:49 +00002088 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002089}
2090
Chris Lattner58a1eb02009-04-08 18:46:40 +00002091/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2092/// pseudo directive in the predefines buffer. This handles it by sucking all
2093/// tokens through the preprocessor and discarding them (only keeping the side
2094/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002095void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2096 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002097 // This directive should only occur in the predefines buffer. If not, emit an
2098 // error and reject it.
2099 SourceLocation Loc = IncludeMacrosTok.getLocation();
2100 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
2101 Diag(IncludeMacrosTok.getLocation(),
2102 diag::pp_include_macros_out_of_predefines);
2103 DiscardUntilEndOfDirective();
2104 return;
2105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
Chris Lattnere01d82b2009-04-08 20:53:24 +00002107 // Treat this as a normal #include for checking purposes. If this is
2108 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002109 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002110
Chris Lattnere01d82b2009-04-08 20:53:24 +00002111 Token TmpTok;
2112 do {
2113 Lex(TmpTok);
2114 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2115 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002116}
2117
Chris Lattnerf64b3522008-03-09 01:54:53 +00002118//===----------------------------------------------------------------------===//
2119// Preprocessor Macro Directive Handling.
2120//===----------------------------------------------------------------------===//
2121
2122/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
2123/// definition has just been read. Lex the rest of the arguments and the
2124/// closing ), updating MI with what we learn. Return true if an error occurs
2125/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002126bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002127 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00002128
Chris Lattnerf64b3522008-03-09 01:54:53 +00002129 while (1) {
2130 LexUnexpandedToken(Tok);
2131 switch (Tok.getKind()) {
2132 case tok::r_paren:
2133 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00002134 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002135 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002136 // Otherwise we have #define FOO(A,)
2137 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2138 return true;
2139 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002140 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002141 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002142 diag::warn_cxx98_compat_variadic_macro :
2143 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002144
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002145 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2146 if (LangOpts.OpenCL) {
2147 Diag(Tok, diag::err_pp_opencl_variadic_macros);
2148 return true;
2149 }
2150
Chris Lattnerf64b3522008-03-09 01:54:53 +00002151 // Lex the token after the identifier.
2152 LexUnexpandedToken(Tok);
2153 if (Tok.isNot(tok::r_paren)) {
2154 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2155 return true;
2156 }
2157 // Add the __VA_ARGS__ identifier as an argument.
2158 Arguments.push_back(Ident__VA_ARGS__);
2159 MI->setIsC99Varargs();
Craig Topperd96b3f92015-10-22 04:59:52 +00002160 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002161 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002162 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002163 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2164 return true;
2165 default:
2166 // Handle keywords and identifiers here to accept things like
2167 // #define Foo(for) for.
2168 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002169 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002170 // #define X(1
2171 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2172 return true;
2173 }
2174
2175 // If this is already used as an argument, it is used multiple times (e.g.
2176 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00002177 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00002178 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002179 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002180 return true;
2181 }
Mike Stump11289f42009-09-09 15:08:12 +00002182
Chris Lattnerf64b3522008-03-09 01:54:53 +00002183 // Add the argument to the macro info.
2184 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002185
Chris Lattnerf64b3522008-03-09 01:54:53 +00002186 // Lex the token after the identifier.
2187 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002188
Chris Lattnerf64b3522008-03-09 01:54:53 +00002189 switch (Tok.getKind()) {
2190 default: // #define X(A B
2191 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2192 return true;
2193 case tok::r_paren: // #define X(A)
Craig Topperd96b3f92015-10-22 04:59:52 +00002194 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002195 return false;
2196 case tok::comma: // #define X(A,
2197 break;
2198 case tok::ellipsis: // #define X(A... -> GCC extension
2199 // Diagnose extension.
2200 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002201
Chris Lattnerf64b3522008-03-09 01:54:53 +00002202 // Lex the token after the identifier.
2203 LexUnexpandedToken(Tok);
2204 if (Tok.isNot(tok::r_paren)) {
2205 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2206 return true;
2207 }
Mike Stump11289f42009-09-09 15:08:12 +00002208
Chris Lattnerf64b3522008-03-09 01:54:53 +00002209 MI->setIsGNUVarargs();
Craig Topperd96b3f92015-10-22 04:59:52 +00002210 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002211 return false;
2212 }
2213 }
2214 }
2215}
2216
Serge Pavlov07c0f042014-12-18 11:14:21 +00002217static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2218 const LangOptions &LOptions) {
2219 if (MI->getNumTokens() == 1) {
2220 const Token &Value = MI->getReplacementToken(0);
2221
2222 // Macro that is identity, like '#define inline inline' is a valid pattern.
2223 if (MacroName.getKind() == Value.getKind())
2224 return true;
2225
2226 // Macro that maps a keyword to the same keyword decorated with leading/
2227 // trailing underscores is a valid pattern:
2228 // #define inline __inline
2229 // #define inline __inline__
2230 // #define inline _inline (in MS compatibility mode)
2231 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2232 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2233 if (!II->isKeyword(LOptions))
2234 return false;
2235 StringRef ValueText = II->getName();
2236 StringRef TrimmedValue = ValueText;
2237 if (!ValueText.startswith("__")) {
2238 if (ValueText.startswith("_"))
2239 TrimmedValue = TrimmedValue.drop_front(1);
2240 else
2241 return false;
2242 } else {
2243 TrimmedValue = TrimmedValue.drop_front(2);
2244 if (TrimmedValue.endswith("__"))
2245 TrimmedValue = TrimmedValue.drop_back(2);
2246 }
2247 return TrimmedValue.equals(MacroText);
2248 } else {
2249 return false;
2250 }
2251 }
2252
2253 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002254 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2255 tok::kw_const) &&
2256 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002257}
2258
James Dennettf6333ac2012-06-22 05:46:07 +00002259/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00002260/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002261void Preprocessor::HandleDefineDirective(Token &DefineTok,
2262 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002263 ++NumDefined;
2264
2265 Token MacroNameTok;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002266 bool MacroShadowsKeyword;
2267 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattnerf64b3522008-03-09 01:54:53 +00002269 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002270 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002271 return;
2272
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002273 Token LastTok = MacroNameTok;
2274
Chris Lattnerf64b3522008-03-09 01:54:53 +00002275 // If we are supposed to keep comments in #defines, reenable comment saving
2276 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00002277 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00002278
Chris Lattnerf64b3522008-03-09 01:54:53 +00002279 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002280 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002281
Chris Lattnerf64b3522008-03-09 01:54:53 +00002282 Token Tok;
2283 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002284
Chris Lattnerf64b3522008-03-09 01:54:53 +00002285 // If this is a function-like macro definition, parse the argument list,
2286 // marking each of the identifiers as being used as macro arguments. Also,
2287 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002288 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002289 if (ImmediatelyAfterHeaderGuard) {
2290 // Save this macro information since it may part of a header guard.
2291 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2292 MacroNameTok.getLocation());
2293 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002294 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002295 } else if (Tok.hasLeadingSpace()) {
2296 // This is a normal token with leading space. Clear the leading space
2297 // marker on the first token to get proper expansion.
2298 Tok.clearFlag(Token::LeadingSpace);
2299 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002300 // This is a function-like macro definition. Read the argument list.
2301 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002302 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002303 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002304 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002305 DiscardUntilEndOfDirective();
2306 return;
2307 }
2308
Chris Lattner249c38b2009-04-19 18:26:34 +00002309 // If this is a definition of a variadic C99 function-like macro, not using
2310 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00002311
Chris Lattner249c38b2009-04-19 18:26:34 +00002312 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2313 // This gets unpoisoned where it is allowed.
2314 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2315 if (MI->isC99Varargs())
2316 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00002317
Chris Lattnerf64b3522008-03-09 01:54:53 +00002318 // Read the first token after the arg list for down below.
2319 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002320 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002321 // C99 requires whitespace between the macro definition and the body. Emit
2322 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002323 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002324 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002325 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2326 // first character of a replacement list is not a character required by
2327 // subclause 5.2.1, then there shall be white-space separation between the
2328 // identifier and the replacement list.". 5.2.1 lists this set:
2329 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2330 // is irrelevant here.
2331 bool isInvalid = false;
2332 if (Tok.is(tok::at)) // @ is not in the list above.
2333 isInvalid = true;
2334 else if (Tok.is(tok::unknown)) {
2335 // If we have an unknown token, it is something strange like "`". Since
2336 // all of valid characters would have lexed into a single character
2337 // token of some sort, we know this is not a valid case.
2338 isInvalid = true;
2339 }
2340 if (isInvalid)
2341 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2342 else
2343 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002344 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002345
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002346 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002347 LastTok = Tok;
2348
Chris Lattnerf64b3522008-03-09 01:54:53 +00002349 // Read the rest of the macro body.
2350 if (MI->isObjectLike()) {
2351 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002352 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002353 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002354 MI->AddTokenToBody(Tok);
2355 // Get the next token of the macro.
2356 LexUnexpandedToken(Tok);
2357 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002358 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002359 // Otherwise, read the body of a function-like macro. While we are at it,
2360 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2361 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002362 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002363 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002364
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002365 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002366 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002367
Chris Lattnerf64b3522008-03-09 01:54:53 +00002368 // Get the next token of the macro.
2369 LexUnexpandedToken(Tok);
2370 continue;
2371 }
Mike Stump11289f42009-09-09 15:08:12 +00002372
Richard Smith701a3522013-07-09 01:00:29 +00002373 // If we're in -traditional mode, then we should ignore stringification
2374 // and token pasting. Mark the tokens as unknown so as not to confuse
2375 // things.
2376 if (getLangOpts().TraditionalCPP) {
2377 Tok.setKind(tok::unknown);
2378 MI->AddTokenToBody(Tok);
2379
2380 // Get the next token of the macro.
2381 LexUnexpandedToken(Tok);
2382 continue;
2383 }
2384
Eli Friedman14d3c792012-11-14 02:18:46 +00002385 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002386 // If we see token pasting, check if it looks like the gcc comma
2387 // pasting extension. We'll use this information to suppress
2388 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002389
Eli Friedman14d3c792012-11-14 02:18:46 +00002390 // Get the next token of the macro.
2391 LexUnexpandedToken(Tok);
2392
2393 if (Tok.is(tok::eod)) {
2394 MI->AddTokenToBody(LastTok);
2395 break;
2396 }
2397
2398 unsigned NumTokens = MI->getNumTokens();
2399 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2400 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2401 MI->setHasCommaPasting();
2402
David Majnemer76faf1f2013-11-05 09:30:17 +00002403 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002404 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002405 continue;
2406 }
2407
Chris Lattnerf64b3522008-03-09 01:54:53 +00002408 // Get the next token of the macro.
2409 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002410
Chris Lattner83bd8282009-05-25 17:16:10 +00002411 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002412 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002413 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2414
2415 // If this is assembler-with-cpp mode, we accept random gibberish after
2416 // the '#' because '#' is often a comment character. However, change
2417 // the kind of the token to tok::unknown so that the preprocessor isn't
2418 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002419 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002420 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002421 MI->AddTokenToBody(LastTok);
2422 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002423 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002424 Diag(Tok, diag::err_pp_stringize_not_parameter)
2425 << LastTok.is(tok::hashat);
Mike Stump11289f42009-09-09 15:08:12 +00002426
Chris Lattner83bd8282009-05-25 17:16:10 +00002427 // Disable __VA_ARGS__ again.
2428 Ident__VA_ARGS__->setIsPoisoned(true);
2429 return;
2430 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002431 }
Mike Stump11289f42009-09-09 15:08:12 +00002432
Chris Lattner83bd8282009-05-25 17:16:10 +00002433 // Things look ok, add the '#' and param name tokens to the macro.
2434 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002435 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002436 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002437
Chris Lattnerf64b3522008-03-09 01:54:53 +00002438 // Get the next token of the macro.
2439 LexUnexpandedToken(Tok);
2440 }
2441 }
Mike Stump11289f42009-09-09 15:08:12 +00002442
Serge Pavlov07c0f042014-12-18 11:14:21 +00002443 if (MacroShadowsKeyword &&
2444 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2445 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2446 }
Mike Stump11289f42009-09-09 15:08:12 +00002447
Chris Lattnerf64b3522008-03-09 01:54:53 +00002448 // Disable __VA_ARGS__ again.
2449 Ident__VA_ARGS__->setIsPoisoned(true);
2450
Chris Lattner57540c52011-04-15 05:22:18 +00002451 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002452 // replacement list.
2453 unsigned NumTokens = MI->getNumTokens();
2454 if (NumTokens != 0) {
2455 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2456 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002457 return;
2458 }
2459 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2460 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002461 return;
2462 }
2463 }
Mike Stump11289f42009-09-09 15:08:12 +00002464
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002465 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002466
Chris Lattnerf64b3522008-03-09 01:54:53 +00002467 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002468 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002469 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002470 // In Objective-C, ignore attempts to directly redefine the builtin
2471 // definitions of the ownership qualifiers. It's still possible to
2472 // #undef them.
2473 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2474 return II->isStr("__strong") ||
2475 II->isStr("__weak") ||
2476 II->isStr("__unsafe_unretained") ||
2477 II->isStr("__autoreleasing");
2478 };
2479 if (getLangOpts().ObjC1 &&
2480 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2481 == getPredefinesFileID() &&
2482 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2483 // Warn if it changes the tokens.
2484 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2485 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2486 !MI->isIdenticalTo(*OtherMI, *this,
2487 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2488 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2489 }
2490 assert(!OtherMI->isWarnIfUnused());
2491 return;
2492 }
2493
Chris Lattner5244f342009-01-16 19:50:11 +00002494 // It is very common for system headers to have tons of macro redefinitions
2495 // and for warnings to be disabled in system headers. If this is the case,
2496 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002497 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002498 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002499 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002500 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002501
Taewook Oh755e4d22016-06-13 21:55:33 +00002502 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002503 // C++ [cpp.predefined]p4, but allow it as an extension.
2504 if (OtherMI->isBuiltinMacro())
2505 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002506 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002507 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002508 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002509 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002510 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2511 << MacroNameTok.getIdentifierInfo();
2512 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2513 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002514 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002515 if (OtherMI->isWarnIfUnused())
2516 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002517 }
Mike Stump11289f42009-09-09 15:08:12 +00002518
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002519 DefMacroDirective *MD =
2520 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002521
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002522 assert(!MI->isUsed());
2523 // If we need warning for not using the macro, add its location in the
2524 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002525 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002526 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002527 MI->setIsWarnIfUnused(true);
2528 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2529 }
2530
Chris Lattner928e9092009-04-12 01:39:54 +00002531 // If the callbacks want to know, tell them about the macro definition.
2532 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002533 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002534}
2535
James Dennettf6333ac2012-06-22 05:46:07 +00002536/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002537///
2538void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2539 ++NumUndefined;
2540
2541 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002542 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002543
Chris Lattnerf64b3522008-03-09 01:54:53 +00002544 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002545 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002546 return;
Mike Stump11289f42009-09-09 15:08:12 +00002547
Chris Lattnerf64b3522008-03-09 01:54:53 +00002548 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002549 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002550
Richard Smith20e883e2015-04-29 23:20:19 +00002551 // Okay, we have a valid identifier to undef.
2552 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002553 auto MD = getMacroDefinition(II);
Mike Stump11289f42009-09-09 15:08:12 +00002554
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002555 // If the callbacks want to know, tell them about the macro #undef.
2556 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002557 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002558 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002559
Chris Lattnerf64b3522008-03-09 01:54:53 +00002560 // If the macro is not defined, this is a noop undef, just return.
Richard Smith36bd40d2015-05-04 03:15:40 +00002561 const MacroInfo *MI = MD.getMacroInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002562 if (!MI)
2563 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002564
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002565 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002566 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002567
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002568 if (MI->isWarnIfUnused())
2569 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2570
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002571 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2572 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002573}
2574
Chris Lattnerf64b3522008-03-09 01:54:53 +00002575//===----------------------------------------------------------------------===//
2576// Preprocessor Conditional Directive Handling.
2577//===----------------------------------------------------------------------===//
2578
James Dennettf6333ac2012-06-22 05:46:07 +00002579/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2580/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2581/// true if any tokens have been returned or pp-directives activated before this
2582/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002583///
2584void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2585 bool ReadAnyTokensBeforeDirective) {
2586 ++NumIf;
2587 Token DirectiveTok = Result;
2588
2589 Token MacroNameTok;
2590 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002591
Chris Lattnerf64b3522008-03-09 01:54:53 +00002592 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002593 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002594 // Skip code until we get to #endif. This helps with recovery by not
2595 // emitting an error when the #endif is reached.
2596 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2597 /*Foundnonskip*/false, /*FoundElse*/false);
2598 return;
2599 }
Mike Stump11289f42009-09-09 15:08:12 +00002600
Chris Lattnerf64b3522008-03-09 01:54:53 +00002601 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002602 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002603
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002604 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002605 auto MD = getMacroDefinition(MII);
2606 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002607
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002608 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002609 // If the start of a top-level #ifdef and if the macro is not defined,
2610 // inform MIOpt that this might be the start of a proper include guard.
2611 // Otherwise it is some other form of unknown conditional which we can't
2612 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002613 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002614 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002615 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002616 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002617 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002618 }
2619
Chris Lattnerf64b3522008-03-09 01:54:53 +00002620 // If there is a macro, process it.
2621 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002622 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002623
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002624 if (Callbacks) {
2625 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002626 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002627 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002628 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002629 }
2630
Chris Lattnerf64b3522008-03-09 01:54:53 +00002631 // Should we include the stuff contained by this directive?
2632 if (!MI == isIfndef) {
2633 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002634 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2635 /*wasskip*/false, /*foundnonskip*/true,
2636 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002637 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002638 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002639 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002640 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002641 /*FoundElse*/false);
2642 }
2643}
2644
James Dennettf6333ac2012-06-22 05:46:07 +00002645/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002646///
2647void Preprocessor::HandleIfDirective(Token &IfToken,
2648 bool ReadAnyTokensBeforeDirective) {
2649 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002650
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002651 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002652 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002653 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2654 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2655 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002656
2657 // If this condition is equivalent to #ifndef X, and if this is the first
2658 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002659 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002660 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002661 // FIXME: Pass in the location of the macro name, not the 'if' token.
2662 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002663 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002664 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002665 }
2666
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002667 if (Callbacks)
2668 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002669 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002670 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002671
Chris Lattnerf64b3522008-03-09 01:54:53 +00002672 // Should we include the stuff contained by this directive?
2673 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002674 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002675 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002676 /*foundnonskip*/true, /*foundelse*/false);
2677 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002678 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002679 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002680 /*FoundElse*/false);
2681 }
2682}
2683
James Dennettf6333ac2012-06-22 05:46:07 +00002684/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002685///
2686void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2687 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002688
Chris Lattnerf64b3522008-03-09 01:54:53 +00002689 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002690 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002691
Chris Lattnerf64b3522008-03-09 01:54:53 +00002692 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002693 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002694 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002695 Diag(EndifToken, diag::err_pp_endif_without_if);
2696 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002697 }
Mike Stump11289f42009-09-09 15:08:12 +00002698
Chris Lattnerf64b3522008-03-09 01:54:53 +00002699 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002700 if (CurPPLexer->getConditionalStackDepth() == 0)
2701 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002702
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002703 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002704 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002705
2706 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002707 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002708}
2709
James Dennettf6333ac2012-06-22 05:46:07 +00002710/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002711///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002712void Preprocessor::HandleElseDirective(Token &Result) {
2713 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002714
Chris Lattnerf64b3522008-03-09 01:54:53 +00002715 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002716 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002717
Chris Lattnerf64b3522008-03-09 01:54:53 +00002718 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002719 if (CurPPLexer->popConditionalLevel(CI)) {
2720 Diag(Result, diag::pp_err_else_without_if);
2721 return;
2722 }
Mike Stump11289f42009-09-09 15:08:12 +00002723
Chris Lattnerf64b3522008-03-09 01:54:53 +00002724 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002725 if (CurPPLexer->getConditionalStackDepth() == 0)
2726 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002727
2728 // If this is a #else with a #else before it, report the error.
2729 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002730
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002731 if (Callbacks)
2732 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2733
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002734 // Finally, skip the rest of the contents of this block.
2735 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002736 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002737}
2738
James Dennettf6333ac2012-06-22 05:46:07 +00002739/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002740///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002741void Preprocessor::HandleElifDirective(Token &ElifToken) {
2742 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002743
Chris Lattnerf64b3522008-03-09 01:54:53 +00002744 // #elif directive in a non-skipping conditional... start skipping.
2745 // We don't care what the condition is, because we will always skip it (since
2746 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002747 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002748 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002749 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002750
2751 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002752 if (CurPPLexer->popConditionalLevel(CI)) {
2753 Diag(ElifToken, diag::pp_err_elif_without_if);
2754 return;
2755 }
Mike Stump11289f42009-09-09 15:08:12 +00002756
Chris Lattnerf64b3522008-03-09 01:54:53 +00002757 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002758 if (CurPPLexer->getConditionalStackDepth() == 0)
2759 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002760
Chris Lattnerf64b3522008-03-09 01:54:53 +00002761 // If this is a #elif with a #else before it, report the error.
2762 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Taewook Oh755e4d22016-06-13 21:55:33 +00002763
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002764 if (Callbacks)
2765 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002766 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002767 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002768
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002769 // Finally, skip the rest of the contents of this block.
2770 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002771 /*FoundElse*/CI.FoundElse,
2772 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002773}