blob: 030717b8bd5c7d8895531568283d73e0efcbd096 [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
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000015#include "clang/Basic/CharInfo.h"
Chris Lattner710bb872009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/Basic/IdentifierTable.h"
18#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/Module.h"
20#include "clang/Basic/SourceLocation.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000021#include "clang/Basic/SourceManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000022#include "clang/Basic/TokenKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Lex/CodeCompletionHandler.h"
24#include "clang/Lex/HeaderSearch.h"
25#include "clang/Lex/LexDiagnostic.h"
26#include "clang/Lex/LiteralSupport.h"
27#include "clang/Lex/MacroInfo.h"
28#include "clang/Lex/ModuleLoader.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000029#include "clang/Lex/ModuleMap.h"
30#include "clang/Lex/PPCallbacks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Lex/Pragma.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000032#include "clang/Lex/Preprocessor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/Lex/PTHLexer.h"
34#include "clang/Lex/Token.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/SmallVector.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000038#include "llvm/ADT/STLExtras.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000039#include "llvm/ADT/StringSwitch.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "llvm/ADT/StringRef.h"
41#include "llvm/Support/AlignOf.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000042#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaf6002232014-08-08 21:31:04 +000043#include "llvm/Support/Path.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000044#include <algorithm>
45#include <cassert>
46#include <cstring>
47#include <new>
48#include <string>
49#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000050
Chris Lattnerf64b3522008-03-09 01:54:53 +000051using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Utility Methods for Preprocessor Directive Handling.
55//===----------------------------------------------------------------------===//
56
Richard Smith3f6dd7a2017-05-12 23:40:52 +000057MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
58 auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead};
Ted Kremenekc8456f82010-10-19 22:15:20 +000059 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000060 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000061}
62
Richard Smith50474bf2015-04-23 23:29:05 +000063DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
64 SourceLocation Loc) {
Richard Smith713369b2015-04-23 20:40:50 +000065 return new (BP) DefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000066}
67
68UndefMacroDirective *
Richard Smith50474bf2015-04-23 23:29:05 +000069Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
Richard Smith713369b2015-04-23 20:40:50 +000070 return new (BP) UndefMacroDirective(UndefLoc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000071}
72
73VisibilityMacroDirective *
74Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
75 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000076 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000077}
78
James Dennettf6333ac2012-06-22 05:46:07 +000079/// \brief Read and discard all tokens remaining on the current line until
80/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000081void Preprocessor::DiscardUntilEndOfDirective() {
82 Token Tmp;
83 do {
84 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000085 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000086 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000087}
88
Serge Pavlov07c0f042014-12-18 11:14:21 +000089/// \brief Enumerates possible cases of #define/#undef a reserved identifier.
90enum MacroDiag {
91 MD_NoWarn, //> Not a reserved identifier
92 MD_KeywordDef, //> Macro hides keyword, enabled by default
93 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
94};
95
96/// \brief Checks if the specified identifier is reserved in the specified
97/// language.
98/// This function does not check if the identifier is a keyword.
99static bool isReservedId(StringRef Text, const LangOptions &Lang) {
100 // C++ [macro.names], C11 7.1.3:
101 // All identifiers that begin with an underscore and either an uppercase
102 // letter or another underscore are always reserved for any use.
103 if (Text.size() >= 2 && Text[0] == '_' &&
104 (isUppercase(Text[1]) || Text[1] == '_'))
105 return true;
106 // C++ [global.names]
107 // Each name that contains a double underscore ... is reserved to the
108 // implementation for any use.
109 if (Lang.CPlusPlus) {
110 if (Text.find("__") != StringRef::npos)
111 return true;
112 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000113 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000114}
115
Serge Pavlov07c0f042014-12-18 11:14:21 +0000116static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
117 const LangOptions &Lang = PP.getLangOpts();
118 StringRef Text = II->getName();
119 if (isReservedId(Text, Lang))
120 return MD_ReservedMacro;
121 if (II->isKeyword(Lang))
122 return MD_KeywordDef;
123 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
124 return MD_KeywordDef;
125 return MD_NoWarn;
126}
127
128static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
129 const LangOptions &Lang = PP.getLangOpts();
130 StringRef Text = II->getName();
131 // Do not warn on keyword undef. It is generally harmless and widely used.
132 if (isReservedId(Text, Lang))
133 return MD_ReservedMacro;
134 return MD_NoWarn;
135}
136
Taewook Ohf42103c2016-06-13 20:40:21 +0000137// Return true if we want to issue a diagnostic by default if we
138// encounter this name in a #include with the wrong case. For now,
139// this includes the standard C and C++ headers, Posix headers,
140// and Boost headers. Improper case for these #includes is a
141// potential portability issue.
142static bool warnByDefaultOnWrongCase(StringRef Include) {
143 // If the first component of the path is "boost", treat this like a standard header
144 // for the purposes of diagnostics.
145 if (::llvm::sys::path::begin(Include)->equals_lower("boost"))
146 return true;
147
148 // "condition_variable" is the longest standard header name at 18 characters.
149 // If the include file name is longer than that, it can't be a standard header.
Taewook Oh755e4d22016-06-13 21:55:33 +0000150 static const size_t MaxStdHeaderNameLen = 18u;
Taewook Ohf42103c2016-06-13 20:40:21 +0000151 if (Include.size() > MaxStdHeaderNameLen)
152 return false;
153
154 // Lowercase and normalize the search string.
155 SmallString<32> LowerInclude{Include};
156 for (char &Ch : LowerInclude) {
157 // In the ASCII range?
George Burgess IV5d3bd932016-06-16 02:30:33 +0000158 if (static_cast<unsigned char>(Ch) > 0x7f)
Taewook Ohf42103c2016-06-13 20:40:21 +0000159 return false; // Can't be a standard header
160 // ASCII lowercase:
161 if (Ch >= 'A' && Ch <= 'Z')
162 Ch += 'a' - 'A';
163 // Normalize path separators for comparison purposes.
164 else if (::llvm::sys::path::is_separator(Ch))
165 Ch = '/';
166 }
167
168 // The standard C/C++ and Posix headers
169 return llvm::StringSwitch<bool>(LowerInclude)
170 // C library headers
171 .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
172 .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
173 .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
174 .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
175 .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
176 .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
177
178 // C++ headers for C library facilities
179 .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
180 .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
181 .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
182 .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
183 .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
184 .Case("cwctype", true)
185
186 // C++ library headers
187 .Cases("algorithm", "fstream", "list", "regex", "thread", true)
188 .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
189 .Cases("atomic", "future", "map", "set", "type_traits", true)
190 .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
191 .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
192 .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
193 .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
194 .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
195 .Cases("deque", "istream", "queue", "string", "valarray", true)
196 .Cases("exception", "iterator", "random", "strstream", "vector", true)
197 .Cases("forward_list", "limits", "ratio", "system_error", true)
198
199 // POSIX headers (which aren't also C headers)
200 .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
201 .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
202 .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
203 .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
204 .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
205 .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
206 .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
207 .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
208 .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
209 .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
210 .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
211 .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
212 .Default(false);
213}
214
Serge Pavlov07c0f042014-12-18 11:14:21 +0000215bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
216 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000217 // Missing macro name?
218 if (MacroNameTok.is(tok::eod))
219 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
220
221 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
222 if (!II) {
223 bool Invalid = false;
224 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
225 if (Invalid)
226 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000227 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000228
Alp Tokerf33619c2014-05-31 03:38:08 +0000229 if (!II->isCPlusPlusOperatorKeyword())
230 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000231
Alp Tokere03e9e12014-05-31 16:32:22 +0000232 // C++ 2.5p2: Alternative tokens behave the same as its primary token
233 // except for their spellings.
234 Diag(MacroNameTok, getLangOpts().MicrosoftExt
235 ? diag::ext_pp_operator_used_as_macro_name
236 : diag::err_pp_operator_used_as_macro_name)
237 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000238
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000239 // Allow #defining |and| and friends for Microsoft compatibility or
240 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000241 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000242 }
243
Serge Pavlovd024f522014-10-24 17:31:32 +0000244 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000245 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
246 return Diag(MacroNameTok, diag::err_defined_macro_name);
247 }
248
Richard Smith20e883e2015-04-29 23:20:19 +0000249 if (isDefineUndef == MU_Undef) {
250 auto *MI = getMacroInfo(II);
251 if (MI && MI->isBuiltinMacro()) {
252 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
253 // and C++ [cpp.predefined]p4], but allow it as an extension.
254 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
255 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000256 }
257
Serge Pavlov07c0f042014-12-18 11:14:21 +0000258 // If defining/undefining reserved identifier or a keyword, we need to issue
259 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000260 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000261 if (ShadowFlag)
262 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000263 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
Mehdi Amini99d1b292016-10-01 16:38:28 +0000264 (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000265 MacroDiag D = MD_NoWarn;
266 if (isDefineUndef == MU_Define) {
267 D = shouldWarnOnMacroDef(*this, II);
268 }
269 else if (isDefineUndef == MU_Undef)
270 D = shouldWarnOnMacroUndef(*this, II);
271 if (D == MD_KeywordDef) {
272 // We do not want to warn on some patterns widely used in configuration
273 // scripts. This requires analyzing next tokens, so do not issue warnings
274 // now, only inform caller.
275 if (ShadowFlag)
276 *ShadowFlag = true;
277 }
278 if (D == MD_ReservedMacro)
279 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000280 }
281
Alp Tokerb05e0b52014-05-21 06:13:51 +0000282 // Okay, we got a good identifier.
283 return false;
284}
285
James Dennettf6333ac2012-06-22 05:46:07 +0000286/// \brief Lex and validate a macro name, which occurs after a
287/// \#define or \#undef.
288///
Serge Pavlovd024f522014-10-24 17:31:32 +0000289/// This sets the token kind to eod and discards the rest of the macro line if
290/// the macro name is invalid.
291///
292/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000293/// \param isDefineUndef Context in which macro is used.
294/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
295void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
296 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000297 // Read the token, don't allow macro expansion on it.
298 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000299
Douglas Gregor12785102010-08-24 20:21:13 +0000300 if (MacroNameTok.is(tok::code_completion)) {
301 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000302 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000303 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000304 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000305 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000306
Serge Pavlov07c0f042014-12-18 11:14:21 +0000307 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000308 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000309
310 // Invalid macro name, read and discard the rest of the line and set the
311 // token kind to tok::eod if necessary.
312 if (MacroNameTok.isNot(tok::eod)) {
313 MacroNameTok.setKind(tok::eod);
314 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000315 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000316}
317
James Dennettf6333ac2012-06-22 05:46:07 +0000318/// \brief Ensure that the next token is a tok::eod token.
319///
320/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000321/// true, then we consider macros that expand to zero tokens as being ok.
322void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000323 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000324 // Lex unexpanded tokens for most directives: macros might expand to zero
325 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
326 // #line) allow empty macros.
327 if (EnableMacros)
328 Lex(Tmp);
329 else
330 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000331
Chris Lattnerf64b3522008-03-09 01:54:53 +0000332 // There should be no tokens after the directive, but we allow them as an
333 // extension.
334 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
335 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000336
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000337 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000338 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000339 // or if this is a macro-style preprocessing directive, because it is more
340 // trouble than it is worth to insert /**/ and check that there is no /**/
341 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000342 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000343 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000344 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000345 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
346 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000347 DiscardUntilEndOfDirective();
348 }
349}
350
James Dennettf6333ac2012-06-22 05:46:07 +0000351/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
352/// decided that the subsequent tokens are in the \#if'd out portion of the
353/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000354/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000355/// this \#if directive, so \#else/\#elif blocks should never be entered.
356/// If ElseOk is true, then \#else directives are ok, if not, then we have
357/// already seen one so a \#else directive is a duplicate. When this returns,
358/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000359void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
360 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000361 bool FoundElse,
362 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000363 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000364 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000365
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000366 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000367 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000368
Ted Kremenek56572ab2008-12-12 18:34:08 +0000369 if (CurPTHLexer) {
370 PTHSkipExcludedConditionalBlock();
371 return;
372 }
Mike Stump11289f42009-09-09 15:08:12 +0000373
Chris Lattnerf64b3522008-03-09 01:54:53 +0000374 // Enter raw mode to disable identifier lookup (and thus macro expansion),
375 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000376 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000377 Token Tok;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000378 while (true) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000379 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000380
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000381 if (Tok.is(tok::code_completion)) {
382 if (CodeComplete)
383 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000384 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000385 continue;
386 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000387
Chris Lattnerf64b3522008-03-09 01:54:53 +0000388 // If this is the end of the buffer, we have an error.
389 if (Tok.is(tok::eof)) {
390 // Emit errors for each unterminated conditional on the stack, including
391 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000392 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000393 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000394 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
395 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000396 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000397 }
398
Chris Lattnerf64b3522008-03-09 01:54:53 +0000399 // Just return and let the caller lex after this #include.
400 break;
401 }
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattnerf64b3522008-03-09 01:54:53 +0000403 // If this token is not a preprocessor directive, just skip it.
404 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
405 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000406
Chris Lattnerf64b3522008-03-09 01:54:53 +0000407 // We just parsed a # character at the start of a line, so we're in
408 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000409 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000410 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000411 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000412
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattnerf64b3522008-03-09 01:54:53 +0000414 // Read the next token, the directive flavor.
415 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000416
Chris Lattnerf64b3522008-03-09 01:54:53 +0000417 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
418 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000419 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000420 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000421 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000422 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000423 continue;
424 }
425
426 // If the first letter isn't i or e, it isn't intesting to us. We know that
427 // this is safe in the face of spelling differences, because there is no way
428 // to spell an i/e in a strange way that is another letter. Skipping this
429 // allows us to avoid looking up the identifier info for #define/#undef and
430 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000431 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000432
Alp Toker2d57cea2014-05-17 04:53:25 +0000433 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000434 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000435 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000436 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000437 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000438 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000439 continue;
440 }
Mike Stump11289f42009-09-09 15:08:12 +0000441
Chris Lattnerf64b3522008-03-09 01:54:53 +0000442 // Get the identifier name without trigraphs or embedded newlines. Note
443 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
444 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000445 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000446 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000447 if (!Tok.needsCleaning() && RI.size() < 20) {
448 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000449 } else {
450 std::string DirectiveStr = getSpelling(Tok);
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000451 size_t IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000452 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000453 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000454 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000455 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000456 continue;
457 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000458 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000459 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000460 }
Mike Stump11289f42009-09-09 15:08:12 +0000461
Benjamin Kramer144884642009-12-31 13:32:38 +0000462 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000463 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000464 if (Sub.empty() || // "if"
465 Sub == "def" || // "ifdef"
466 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000467 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
468 // bother parsing the condition.
469 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000470 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000471 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000472 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000473 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000474 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000475 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000476 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000477 PPConditionalInfo CondInfo;
478 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000479 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000480 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000481 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000482
Chris Lattnerf64b3522008-03-09 01:54:53 +0000483 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000484 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000485 // Restore the value of LexingRawMode so that trailing comments
486 // are handled correctly, if we've reached the outermost block.
487 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000488 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000489 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000490 if (Callbacks)
491 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000492 break;
Richard Smithd0124572012-06-21 00:35:03 +0000493 } else {
494 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000495 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000496 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000497 // #else directive in a skipping conditional. If not in some other
498 // skipping conditional, and if #else hasn't already been seen, enter it
499 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000500 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000501
Chris Lattnerf64b3522008-03-09 01:54:53 +0000502 // If this is a #else with a #else before it, report the error.
503 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000504
Chris Lattnerf64b3522008-03-09 01:54:53 +0000505 // Note that we've seen a #else in this conditional.
506 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Chris Lattnerf64b3522008-03-09 01:54:53 +0000508 // If the conditional is at the top level, and the #if block wasn't
509 // entered, enter the #else block now.
510 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
511 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000512 // Restore the value of LexingRawMode so that trailing comments
513 // are handled correctly.
514 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000515 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000516 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000517 if (Callbacks)
518 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000519 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000520 } else {
521 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000522 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000523 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000524 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000525
John Thompson17c35732013-12-04 20:19:30 +0000526 // If this is a #elif with a #else before it, report the error.
527 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
528
Chris Lattnerf64b3522008-03-09 01:54:53 +0000529 // If this is in a skipping block or if we're already handled this #if
530 // block, don't bother parsing the condition.
531 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
532 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000533 } else {
John Thompson17c35732013-12-04 20:19:30 +0000534 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000535 // Restore the value of LexingRawMode so that identifiers are
536 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000537 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
538 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000539 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000540 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000541 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000542 if (Callbacks) {
543 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000544 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000545 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000546 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000547 }
548 // If this condition is true, enter it!
549 if (CondValue) {
550 CondInfo.FoundNonSkip = true;
551 break;
552 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000553 }
554 }
555 }
Mike Stump11289f42009-09-09 15:08:12 +0000556
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000557 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000558 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000559 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000560 }
561
562 // Finally, if we are out of the conditional (saw an #endif or ran off the end
563 // of the file, just stop skipping and return to lexing whatever came after
564 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000565 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000566
567 if (Callbacks) {
568 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
569 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
570 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000571}
572
Ted Kremenek56572ab2008-12-12 18:34:08 +0000573void Preprocessor::PTHSkipExcludedConditionalBlock() {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000574 while (true) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000575 assert(CurPTHLexer);
576 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000577
Ted Kremenek56572ab2008-12-12 18:34:08 +0000578 // Skip to the next '#else', '#elif', or #endif.
579 if (CurPTHLexer->SkipBlock()) {
580 // We have reached an #endif. Both the '#' and 'endif' tokens
581 // have been consumed by the PTHLexer. Just pop off the condition level.
582 PPConditionalInfo CondInfo;
583 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000584 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000585 assert(!InCond && "Can't be skipping if not in a conditional!");
586 break;
587 }
Mike Stump11289f42009-09-09 15:08:12 +0000588
Ted Kremenek56572ab2008-12-12 18:34:08 +0000589 // We have reached a '#else' or '#elif'. Lex the next token to get
590 // the directive flavor.
591 Token Tok;
592 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000593
Ted Kremenek56572ab2008-12-12 18:34:08 +0000594 // We can actually look up the IdentifierInfo here since we aren't in
595 // raw mode.
596 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
597
598 if (K == tok::pp_else) {
599 // #else: Enter the else condition. We aren't in a nested condition
600 // since we skip those. We're always in the one matching the last
601 // blocked we skipped.
602 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
603 // Note that we've seen a #else in this conditional.
604 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000605
Ted Kremenek56572ab2008-12-12 18:34:08 +0000606 // If the #if block wasn't entered then enter the #else block now.
607 if (!CondInfo.FoundNonSkip) {
608 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000609
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000610 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000611 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000612 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000613 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000614
Ted Kremenek56572ab2008-12-12 18:34:08 +0000615 break;
616 }
Mike Stump11289f42009-09-09 15:08:12 +0000617
Ted Kremenek56572ab2008-12-12 18:34:08 +0000618 // Otherwise skip this block.
619 continue;
620 }
Mike Stump11289f42009-09-09 15:08:12 +0000621
Ted Kremenek56572ab2008-12-12 18:34:08 +0000622 assert(K == tok::pp_elif);
623 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
624
625 // If this is a #elif with a #else before it, report the error.
626 if (CondInfo.FoundElse)
627 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000628
Ted Kremenek56572ab2008-12-12 18:34:08 +0000629 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000630 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000631 if (CondInfo.FoundNonSkip)
632 continue;
633
634 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000635 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000636 CurPTHLexer->ParsingPreprocessorDirective = true;
637 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
638 CurPTHLexer->ParsingPreprocessorDirective = false;
639
640 // If this condition is true, enter it!
641 if (ShouldEnter) {
642 CondInfo.FoundNonSkip = true;
643 break;
644 }
645
646 // Otherwise, skip this block and go to the next one.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000647 }
648}
649
Richard Smith2a553082015-04-23 22:58:06 +0000650Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000651 if (!SourceMgr.isInMainFile(Loc)) {
652 // Try to determine the module of the include directive.
653 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
654 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
655 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
656 // The include comes from an included file.
657 return HeaderInfo.getModuleMap()
658 .findModuleForHeader(EntryOfIncl)
659 .getModule();
660 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000661 }
Richard Smith7e82e012016-02-19 22:25:36 +0000662
663 // This is either in the main file or not in a file at all. It belongs
664 // to the current module, if there is one.
665 return getLangOpts().CurrentModule.empty()
666 ? nullptr
667 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000668}
669
Richard Smith4eb83932016-04-27 21:57:05 +0000670const FileEntry *
671Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000672 Module *M,
Richard Smith4eb83932016-04-27 21:57:05 +0000673 SourceLocation Loc) {
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000674 assert(M && "no module to include");
675
Richard Smith4eb83932016-04-27 21:57:05 +0000676 // If we have a module import syntax, we shouldn't include a header to
677 // make a particular module visible.
678 if (getLangOpts().ObjC2)
679 return nullptr;
680
Richard Smith4eb83932016-04-27 21:57:05 +0000681 Module *TopM = M->getTopLevelModule();
682 Module *IncM = getModuleForLocation(IncLoc);
683
684 // Walk up through the include stack, looking through textual headers of M
685 // until we hit a non-textual header that we can #include. (We assume textual
686 // headers of a module with non-textual headers aren't meant to be used to
687 // import entities from the module.)
688 auto &SM = getSourceManager();
689 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
690 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
691 auto *FE = SM.getFileEntryForID(ID);
692
693 bool InTextualHeader = false;
694 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
695 if (!Header.getModule()->isSubModuleOf(TopM))
696 continue;
697
698 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
699 // If this is an accessible, non-textual header of M's top-level module
700 // that transitively includes the given location and makes the
701 // corresponding module visible, this is the thing to #include.
702 if (Header.isAccessibleFrom(IncM))
703 return FE;
704
705 // It's in a private header; we can't #include it.
706 // FIXME: If there's a public header in some module that re-exports it,
707 // then we could suggest including that, but it's not clear that's the
708 // expected way to make this entity visible.
709 continue;
710 }
711
712 InTextualHeader = true;
713 }
714
715 if (!InTextualHeader)
716 break;
717
718 Loc = SM.getIncludeLoc(ID);
719 }
720
721 return nullptr;
722}
723
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000724const FileEntry *Preprocessor::LookupFile(
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000725 SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
726 const DirectoryLookup *FromDir, const FileEntry *FromFile,
727 const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000728 SmallVectorImpl<char> *RelativePath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000729 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000730 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000731 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000732
Will Wilson0fafd342013-12-27 19:46:16 +0000733 // If the header lookup mechanism may be relative to the current inclusion
734 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000735 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
736 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000737 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000738 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000739 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000740 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000741
Chris Lattner022923a2009-02-04 19:45:07 +0000742 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000743 // predefines buffer or the module includes buffer. Any other file is not
744 // lexed with a normal lexer, so it won't be scanned for preprocessor
745 // directives.
746 //
747 // If we have the predefines buffer, resolve #include references (which come
748 // from the -include command line argument) from the current working
749 // directory instead of relative to the main file.
750 //
751 // If we have the module includes buffer, resolve #include references (which
752 // come from header declarations in the module map) relative to the module
753 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000754 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000755 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000756 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000757 BuildSystemModule = getCurrentModule()->IsSystem;
758 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000759 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000760 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
761 } else {
762 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
763 }
Will Wilson0fafd342013-12-27 19:46:16 +0000764
765 // MSVC searches the current include stack from top to bottom for
766 // headers included by quoted include directives.
767 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000768 if (LangOpts.MSVCCompat && !isAngled) {
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000769 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000770 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000771 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000772 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000773 }
Chris Lattner022923a2009-02-04 19:45:07 +0000774 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000775 }
Mike Stump11289f42009-09-09 15:08:12 +0000776
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000777 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000778
779 if (FromFile) {
780 // We're supposed to start looking from after a particular file. Search
781 // the include path until we find that file or run out of files.
782 const DirectoryLookup *TmpCurDir = CurDir;
783 const DirectoryLookup *TmpFromDir = nullptr;
784 while (const FileEntry *FE = HeaderInfo.LookupFile(
785 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000786 Includers, SearchPath, RelativePath, RequestingModule,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000787 SuggestedModule, /*IsMapped=*/nullptr, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000788 // Keep looking as if this file did a #include_next.
789 TmpFromDir = TmpCurDir;
790 ++TmpFromDir;
791 if (FE == FromFile) {
792 // Found it.
793 FromDir = TmpFromDir;
794 CurDir = TmpCurDir;
795 break;
796 }
797 }
798 }
799
800 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000801 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000802 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000803 RelativePath, RequestingModule, SuggestedModule, IsMapped, SkipCache,
Manman Rene4a5d372016-05-17 02:15:12 +0000804 BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000805 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000806 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000807 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000808 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
809 Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000810 return FE;
811 }
Mike Stump11289f42009-09-09 15:08:12 +0000812
Will Wilson0fafd342013-12-27 19:46:16 +0000813 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000814 // Otherwise, see if this is a subframework header. If so, this is relative
815 // to one of the headers on the #include stack. Walk the list of the current
816 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000817 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000818 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000819 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000820 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000821 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000822 SuggestedModule))) {
823 if (SuggestedModule && !LangOpts.AsmPreprocessor)
824 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000825 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
826 Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000827 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000828 }
829 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000830 }
Mike Stump11289f42009-09-09 15:08:12 +0000831
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000832 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000833 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000834 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000835 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000836 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000837 RequestingModule, SuggestedModule))) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000838 if (SuggestedModule && !LangOpts.AsmPreprocessor)
839 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000840 RequestingModule, RequestingModuleIsModuleInterface,
841 FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000842 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000843 }
844 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000845 }
846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000848 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000849 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000850}
851
Chris Lattnerf64b3522008-03-09 01:54:53 +0000852//===----------------------------------------------------------------------===//
853// Preprocessor Directive Handling.
854//===----------------------------------------------------------------------===//
855
David Blaikied5321242012-06-06 18:52:13 +0000856class Preprocessor::ResetMacroExpansionHelper {
857public:
858 ResetMacroExpansionHelper(Preprocessor *pp)
859 : PP(pp), save(pp->DisableMacroExpansion) {
860 if (pp->MacroExpansionInDirectivesOverride)
861 pp->DisableMacroExpansion = false;
862 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000863
David Blaikied5321242012-06-06 18:52:13 +0000864 ~ResetMacroExpansionHelper() {
865 PP->DisableMacroExpansion = save;
866 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000867
David Blaikied5321242012-06-06 18:52:13 +0000868private:
869 Preprocessor *PP;
870 bool save;
871};
872
Chris Lattnerf64b3522008-03-09 01:54:53 +0000873/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000874/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000875/// lexer/preprocessor state, and advances the lexer(s) so that the next token
876/// read is the correct one.
877void Preprocessor::HandleDirective(Token &Result) {
878 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattnerf64b3522008-03-09 01:54:53 +0000880 // We just parsed a # character at the start of a line, so we're in directive
881 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000882 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000883 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000884 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000885
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000886 bool ImmediatelyAfterTopLevelIfndef =
887 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
888 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
889
Chris Lattnerf64b3522008-03-09 01:54:53 +0000890 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000891
Chris Lattnerf64b3522008-03-09 01:54:53 +0000892 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000893 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000894 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000895 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000896
Chris Lattner2d17ab72009-03-18 21:00:25 +0000897 // Save the '#' token in case we need to return it later.
898 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000899
Chris Lattnerf64b3522008-03-09 01:54:53 +0000900 // Read the next token, the directive flavor. This isn't expanded due to
901 // C99 6.10.3p8.
902 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000903
Chris Lattnerf64b3522008-03-09 01:54:53 +0000904 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
905 // #define A(x) #x
906 // A(abc
907 // #warning blah
908 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000909 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
910 // not support this for #include-like directives, since that can result in
911 // terrible diagnostics, and does not work in GCC.
912 if (InMacroArgs) {
913 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
914 switch (II->getPPKeywordID()) {
915 case tok::pp_include:
916 case tok::pp_import:
917 case tok::pp_include_next:
918 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000919 case tok::pp_pragma:
920 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000921 DiscardUntilEndOfDirective();
922 return;
923 default:
924 break;
925 }
926 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000927 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000928 }
Mike Stump11289f42009-09-09 15:08:12 +0000929
David Blaikied5321242012-06-06 18:52:13 +0000930 // Temporarily enable macro expansion if set so
931 // and reset to previous state when returning from this function.
932 ResetMacroExpansionHelper helper(this);
933
Chris Lattnerf64b3522008-03-09 01:54:53 +0000934 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000935 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000936 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000937 case tok::code_completion:
938 if (CodeComplete)
939 CodeComplete->CodeCompleteDirective(
940 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000941 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000942 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000943 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000944 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000945 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000946 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000947 default:
948 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000949 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000950
Chris Lattnerf64b3522008-03-09 01:54:53 +0000951 // Ask what the preprocessor keyword ID is.
952 switch (II->getPPKeywordID()) {
953 default: break;
954 // C99 6.10.1 - Conditional Inclusion.
955 case tok::pp_if:
956 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
957 case tok::pp_ifdef:
958 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
959 case tok::pp_ifndef:
960 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
961 case tok::pp_elif:
962 return HandleElifDirective(Result);
963 case tok::pp_else:
964 return HandleElseDirective(Result);
965 case tok::pp_endif:
966 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Chris Lattnerf64b3522008-03-09 01:54:53 +0000968 // C99 6.10.2 - Source File Inclusion.
969 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000970 // Handle #include.
971 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000972 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000973 // Handle -imacros.
Taewook Oh755e4d22016-06-13 21:55:33 +0000974 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Chris Lattnerf64b3522008-03-09 01:54:53 +0000976 // C99 6.10.3 - Macro Replacement.
977 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000978 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000979 case tok::pp_undef:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000980 return HandleUndefDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000981
982 // C99 6.10.4 - Line Control.
983 case tok::pp_line:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000984 return HandleLineDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattnerf64b3522008-03-09 01:54:53 +0000986 // C99 6.10.5 - Error Directive.
987 case tok::pp_error:
988 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000989
Chris Lattnerf64b3522008-03-09 01:54:53 +0000990 // C99 6.10.6 - Pragma Directive.
991 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000992 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000993
Chris Lattnerf64b3522008-03-09 01:54:53 +0000994 // GNU Extensions.
995 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000996 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000997 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000998 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000999
Chris Lattnerf64b3522008-03-09 01:54:53 +00001000 case tok::pp_warning:
1001 Diag(Result, diag::ext_pp_warning_directive);
1002 return HandleUserDiagnosticDirective(Result, true);
1003 case tok::pp_ident:
1004 return HandleIdentSCCSDirective(Result);
1005 case tok::pp_sccs:
1006 return HandleIdentSCCSDirective(Result);
1007 case tok::pp_assert:
1008 //isExtension = true; // FIXME: implement #assert
1009 break;
1010 case tok::pp_unassert:
1011 //isExtension = true; // FIXME: implement #unassert
1012 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001013
Douglas Gregor663b48f2012-01-03 19:48:16 +00001014 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001015 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001016 return HandleMacroPublicDirective(Result);
1017 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001018
Douglas Gregor663b48f2012-01-03 19:48:16 +00001019 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001020 if (getLangOpts().Modules)
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001021 return HandleMacroPrivateDirective();
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001022 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001023 }
1024 break;
1025 }
Mike Stump11289f42009-09-09 15:08:12 +00001026
Chris Lattner2d17ab72009-03-18 21:00:25 +00001027 // If this is a .S file, treat unknown # directives as non-preprocessor
1028 // directives. This is important because # may be a comment or introduce
1029 // various pseudo-ops. Just return the # token and push back the following
1030 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001031 if (getLangOpts().AsmPreprocessor) {
David Blaikie2eabcc92016-02-09 18:52:09 +00001032 auto Toks = llvm::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001033 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001034 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001035 Toks[1] = Result;
Taewook Oh755e4d22016-06-13 21:55:33 +00001036
Chris Lattner56f64c12011-01-06 05:01:51 +00001037 // If the second token is a hashhash token, then we need to translate it to
1038 // unknown so the token lexer doesn't try to perform token pasting.
1039 if (Result.is(tok::hashhash))
1040 Toks[1].setKind(tok::unknown);
Taewook Oh755e4d22016-06-13 21:55:33 +00001041
Chris Lattner2d17ab72009-03-18 21:00:25 +00001042 // Enter this token stream so that we re-lex the tokens. Make sure to
1043 // enable macro expansion, in case the token after the # is an identifier
1044 // that is expanded.
David Blaikie2eabcc92016-02-09 18:52:09 +00001045 EnterTokenStream(std::move(Toks), 2, false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001046 return;
1047 }
Mike Stump11289f42009-09-09 15:08:12 +00001048
Chris Lattnerf64b3522008-03-09 01:54:53 +00001049 // If we reached here, the preprocessing token is not valid!
1050 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001051
Chris Lattnerf64b3522008-03-09 01:54:53 +00001052 // Read the rest of the PP line.
1053 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001054
Chris Lattnerf64b3522008-03-09 01:54:53 +00001055 // Okay, we're done parsing the directive.
1056}
1057
Chris Lattner76e68962009-01-26 06:19:46 +00001058/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1059/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1060static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001061 unsigned DiagID, Preprocessor &PP,
1062 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001063 if (DigitTok.isNot(tok::numeric_constant)) {
1064 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001065
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001066 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001067 PP.DiscardUntilEndOfDirective();
1068 return true;
1069 }
Mike Stump11289f42009-09-09 15:08:12 +00001070
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001071 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001072 IntegerBuffer.resize(DigitTok.getLength());
1073 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001074 bool Invalid = false;
1075 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1076 if (Invalid)
1077 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001078
Chris Lattnerd66f1722009-04-18 18:35:15 +00001079 // Verify that we have a simple digit-sequence, and compute the value. This
1080 // is always a simple digit string computed in decimal, so we do this manually
1081 // here.
1082 Val = 0;
1083 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001084 // C++1y [lex.fcon]p1:
1085 // Optional separating single quotes in a digit-sequence are ignored
1086 if (DigitTokBegin[i] == '\'')
1087 continue;
1088
Jordan Rosea7d03842013-02-08 22:30:41 +00001089 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001090 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001091 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001092 PP.DiscardUntilEndOfDirective();
1093 return true;
1094 }
Mike Stump11289f42009-09-09 15:08:12 +00001095
Chris Lattnerd66f1722009-04-18 18:35:15 +00001096 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1097 if (NextVal < Val) { // overflow.
1098 PP.Diag(DigitTok, DiagID);
1099 PP.DiscardUntilEndOfDirective();
1100 return true;
1101 }
1102 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001103 }
Mike Stump11289f42009-09-09 15:08:12 +00001104
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001105 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001106 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1107 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001108
Chris Lattner76e68962009-01-26 06:19:46 +00001109 return false;
1110}
1111
James Dennettf6333ac2012-06-22 05:46:07 +00001112/// \brief Handle a \#line directive: C99 6.10.4.
1113///
1114/// The two acceptable forms are:
1115/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001116/// # line digit-sequence
1117/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001118/// \endverbatim
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001119void Preprocessor::HandleLineDirective() {
Chris Lattner100c65e2009-01-26 05:29:08 +00001120 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1121 // expanded.
1122 Token DigitTok;
1123 Lex(DigitTok);
1124
Chris Lattner100c65e2009-01-26 05:29:08 +00001125 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001126 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001127 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001128 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001129
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001130 if (LineNo == 0)
1131 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001132
Chris Lattner76e68962009-01-26 06:19:46 +00001133 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1134 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001135 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001136 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001137 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001138 if (LineNo >= LineLimit)
1139 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001140 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001141 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001142
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001143 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001144 Token StrTok;
1145 Lex(StrTok);
1146
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001147 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1148 // string followed by eod.
1149 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001150 ; // ok
1151 else if (StrTok.isNot(tok::string_literal)) {
1152 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001153 return DiscardUntilEndOfDirective();
1154 } else if (StrTok.hasUDSuffix()) {
1155 Diag(StrTok, diag::err_invalid_string_udl);
1156 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001157 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001158 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001159 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001160 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001161 if (Literal.hadError)
1162 return DiscardUntilEndOfDirective();
1163 if (Literal.Pascal) {
1164 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1165 return DiscardUntilEndOfDirective();
1166 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001167 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001168
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001169 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001170 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1171 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001172 }
Mike Stump11289f42009-09-09 15:08:12 +00001173
Reid Klecknereb00ee02017-05-22 21:42:58 +00001174 // Take the file kind of the file containing the #line directive. #line
1175 // directives are often used for generated sources from the same codebase, so
1176 // the new file should generally be classified the same way as the current
1177 // file. This is visible in GCC's pre-processed output, which rewrites #line
1178 // to GNU line markers.
1179 SrcMgr::CharacteristicKind FileKind =
1180 SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1181
1182 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1183 false, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001184
Chris Lattner839150e2009-03-27 17:13:49 +00001185 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001186 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Reid Klecknereb00ee02017-05-22 21:42:58 +00001187 PPCallbacks::RenameFile, FileKind);
Chris Lattner100c65e2009-01-26 05:29:08 +00001188}
1189
Chris Lattner76e68962009-01-26 06:19:46 +00001190/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1191/// marker directive.
1192static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
Reid Klecknereb00ee02017-05-22 21:42:58 +00001193 SrcMgr::CharacteristicKind &FileKind,
Chris Lattner76e68962009-01-26 06:19:46 +00001194 Preprocessor &PP) {
1195 unsigned FlagVal;
1196 Token FlagTok;
1197 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001198 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001199 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1200 return true;
1201
1202 if (FlagVal == 1) {
1203 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001204
Chris Lattner76e68962009-01-26 06:19:46 +00001205 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001206 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001207 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1208 return true;
1209 } else if (FlagVal == 2) {
1210 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001211
Chris Lattner1c967782009-02-04 06:25:26 +00001212 SourceManager &SM = PP.getSourceManager();
1213 // If we are leaving the current presumed file, check to make sure the
1214 // presumed include stack isn't empty!
1215 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001216 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001217 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001218 if (PLoc.isInvalid())
1219 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001220
Chris Lattner1c967782009-02-04 06:25:26 +00001221 // If there is no include loc (main file) or if the include loc is in a
1222 // different physical file, then we aren't in a "1" line marker flag region.
1223 SourceLocation IncLoc = PLoc.getIncludeLoc();
1224 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001225 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001226 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1227 PP.DiscardUntilEndOfDirective();
1228 return true;
1229 }
Mike Stump11289f42009-09-09 15:08:12 +00001230
Chris Lattner76e68962009-01-26 06:19:46 +00001231 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001232 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001233 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1234 return true;
1235 }
1236
1237 // We must have 3 if there are still flags.
1238 if (FlagVal != 3) {
1239 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001240 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001241 return true;
1242 }
Mike Stump11289f42009-09-09 15:08:12 +00001243
Reid Klecknereb00ee02017-05-22 21:42:58 +00001244 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001245
Chris Lattner76e68962009-01-26 06:19:46 +00001246 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001247 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001248 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001249 return true;
1250
1251 // We must have 4 if there is yet another flag.
1252 if (FlagVal != 4) {
1253 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001254 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001255 return true;
1256 }
Mike Stump11289f42009-09-09 15:08:12 +00001257
Reid Klecknereb00ee02017-05-22 21:42:58 +00001258 FileKind = SrcMgr::C_ExternCSystem;
Mike Stump11289f42009-09-09 15:08:12 +00001259
Chris Lattner76e68962009-01-26 06:19:46 +00001260 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001261 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001262
1263 // There are no more valid flags here.
1264 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001265 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001266 return true;
1267}
1268
1269/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1270/// one of the following forms:
1271///
1272/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001273/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001274/// # 42 "file" ('1' | '2')? '3' '4'?
1275///
1276void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1277 // Validate the number and convert it to an unsigned. GNU does not have a
1278 // line # limit other than it fit in 32-bits.
1279 unsigned LineNo;
1280 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001281 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001282 return;
Mike Stump11289f42009-09-09 15:08:12 +00001283
Chris Lattner76e68962009-01-26 06:19:46 +00001284 Token StrTok;
1285 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001286
Chris Lattner76e68962009-01-26 06:19:46 +00001287 bool IsFileEntry = false, IsFileExit = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001288 int FilenameID = -1;
Reid Klecknereb00ee02017-05-22 21:42:58 +00001289 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001290
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001291 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1292 // string followed by eod.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001293 if (StrTok.is(tok::eod)) {
1294 // Treat this like "#line NN", which doesn't change file characteristics.
1295 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1296 } else if (StrTok.isNot(tok::string_literal)) {
Chris Lattner76e68962009-01-26 06:19:46 +00001297 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001298 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001299 } else if (StrTok.hasUDSuffix()) {
1300 Diag(StrTok, diag::err_invalid_string_udl);
1301 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001302 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001303 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001304 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001305 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001306 if (Literal.hadError)
1307 return DiscardUntilEndOfDirective();
1308 if (Literal.Pascal) {
1309 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1310 return DiscardUntilEndOfDirective();
1311 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001312 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001313
Chris Lattner76e68962009-01-26 06:19:46 +00001314 // If a filename was present, read any flags that are present.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001315 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001316 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001319 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001320 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1321 IsFileExit, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattner839150e2009-03-27 17:13:49 +00001323 // If the preprocessor has callbacks installed, notify them of the #line
1324 // change. This is used so that the line marker comes out in -E mode for
1325 // example.
1326 if (Callbacks) {
1327 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1328 if (IsFileEntry)
1329 Reason = PPCallbacks::EnterFile;
1330 else if (IsFileExit)
1331 Reason = PPCallbacks::ExitFile;
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattnerc745cec2010-04-14 04:28:50 +00001333 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001334 }
Chris Lattner76e68962009-01-26 06:19:46 +00001335}
1336
Chris Lattner38d7fd22009-01-26 05:30:54 +00001337/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1338///
Mike Stump11289f42009-09-09 15:08:12 +00001339void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001340 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001341 // PTH doesn't emit #warning or #error directives.
1342 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001343 return CurPTHLexer->DiscardToEndOfLine();
1344
Chris Lattnerf64b3522008-03-09 01:54:53 +00001345 // Read the rest of the line raw. We do this because we don't want macros
1346 // to be expanded and we don't require that the tokens be valid preprocessing
1347 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1348 // collapse multiple consequtive white space between tokens, but this isn't
1349 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001350 SmallString<128> Message;
1351 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001352
1353 // Find the first non-whitespace character, so that we can make the
1354 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001355 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001356
Chris Lattner100c65e2009-01-26 05:29:08 +00001357 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001358 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001359 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001360 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001361}
1362
1363/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1364///
1365void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1366 // Yes, this directive is an extension.
1367 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattnerf64b3522008-03-09 01:54:53 +00001369 // Read the string argument.
1370 Token StrTok;
1371 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001372
Chris Lattnerf64b3522008-03-09 01:54:53 +00001373 // If the token kind isn't a string, it's a malformed directive.
1374 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001375 StrTok.isNot(tok::wide_string_literal)) {
1376 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001377 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001378 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001379 return;
1380 }
Mike Stump11289f42009-09-09 15:08:12 +00001381
Richard Smithd67aea22012-03-06 03:21:47 +00001382 if (StrTok.hasUDSuffix()) {
1383 Diag(StrTok, diag::err_invalid_string_udl);
1384 return DiscardUntilEndOfDirective();
1385 }
1386
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001387 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001388 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001389
Douglas Gregordc970f02010-03-16 22:30:13 +00001390 if (Callbacks) {
1391 bool Invalid = false;
1392 std::string Str = getSpelling(StrTok, &Invalid);
1393 if (!Invalid)
1394 Callbacks->Ident(Tok.getLocation(), Str);
1395 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001396}
1397
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001398/// \brief Handle a #public directive.
1399void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001400 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001401 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001402
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001403 // Error reading macro name? If so, diagnostic already issued.
1404 if (MacroNameTok.is(tok::eod))
1405 return;
1406
Douglas Gregor663b48f2012-01-03 19:48:16 +00001407 // Check to see if this is the last token on the #__public_macro line.
1408 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001409
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001410 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001411 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001412 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001413
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001414 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001415 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001416 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001417 return;
1418 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001419
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001420 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001421 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1422 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001423}
1424
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001425/// \brief Handle a #private directive.
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001426void Preprocessor::HandleMacroPrivateDirective() {
Douglas Gregorebf00492011-10-17 15:32:29 +00001427 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001428 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001429
Douglas Gregorebf00492011-10-17 15:32:29 +00001430 // Error reading macro name? If so, diagnostic already issued.
1431 if (MacroNameTok.is(tok::eod))
1432 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001433
Douglas Gregor663b48f2012-01-03 19:48:16 +00001434 // Check to see if this is the last token on the #__private_macro line.
1435 CheckEndOfDirective("__private_macro");
Taewook Oh755e4d22016-06-13 21:55:33 +00001436
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001437 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001438 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001439 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001440
Douglas Gregorebf00492011-10-17 15:32:29 +00001441 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001442 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001443 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001444 return;
1445 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001446
Douglas Gregorebf00492011-10-17 15:32:29 +00001447 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001448 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1449 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001450}
1451
Chris Lattnerf64b3522008-03-09 01:54:53 +00001452//===----------------------------------------------------------------------===//
1453// Preprocessor Include Directive Handling.
1454//===----------------------------------------------------------------------===//
1455
1456/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001457/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001458/// true if the input filename was in <>'s or false if it were in ""'s. The
1459/// caller is expected to provide a buffer that is large enough to hold the
1460/// spelling of the filename, but is also expected to handle the case when
1461/// this method decides to use a different buffer.
1462bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001463 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001464 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001465 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001466
Chris Lattnerf64b3522008-03-09 01:54:53 +00001467 // Make sure the filename is <x> or "x".
1468 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001469 if (Buffer[0] == '<') {
1470 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001471 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001472 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001473 return true;
1474 }
1475 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001476 } else if (Buffer[0] == '"') {
1477 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001478 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001479 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001480 return true;
1481 }
1482 isAngled = false;
1483 } else {
1484 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001485 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001486 return true;
1487 }
Mike Stump11289f42009-09-09 15:08:12 +00001488
Chris Lattnerf64b3522008-03-09 01:54:53 +00001489 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001490 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001491 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001492 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001493 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001494 }
Mike Stump11289f42009-09-09 15:08:12 +00001495
Chris Lattnerf64b3522008-03-09 01:54:53 +00001496 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001497 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001498 return isAngled;
1499}
1500
James Dennett4a4f72d2013-11-27 01:27:40 +00001501// \brief Handle cases where the \#include name is expanded from a macro
1502// as multiple tokens, which need to be glued together.
1503//
1504// This occurs for code like:
1505// \code
1506// \#define FOO <a/b.h>
1507// \#include FOO
1508// \endcode
1509// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1510//
1511// This code concatenates and consumes tokens up to the '>' token. It returns
1512// false if the > was found, otherwise it returns true if it finds and consumes
1513// the EOD marker.
1514bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001515 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001516 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001517
John Thompsonb5353522009-10-30 13:49:06 +00001518 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001519 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001520 End = CurTok.getLocation();
Taewook Oh755e4d22016-06-13 21:55:33 +00001521
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001522 // FIXME: Provide code completion for #includes.
1523 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001524 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001525 Lex(CurTok);
1526 continue;
1527 }
1528
Chris Lattnerf64b3522008-03-09 01:54:53 +00001529 // Append the spelling of this token to the buffer. If there was a space
1530 // before it, add it now.
1531 if (CurTok.hasLeadingSpace())
1532 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001533
Chris Lattnerf64b3522008-03-09 01:54:53 +00001534 // Get the spelling of the token, directly into FilenameBuffer if possible.
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001535 size_t PreAppendSize = FilenameBuffer.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001536 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001537
Chris Lattnerf64b3522008-03-09 01:54:53 +00001538 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001539 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001540
Chris Lattnerf64b3522008-03-09 01:54:53 +00001541 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1542 if (BufPtr != &FilenameBuffer[PreAppendSize])
1543 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001544
Chris Lattnerf64b3522008-03-09 01:54:53 +00001545 // Resize FilenameBuffer to the correct size.
1546 if (CurTok.getLength() != ActualLen)
1547 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001548
Chris Lattnerf64b3522008-03-09 01:54:53 +00001549 // If we found the '>' marker, return success.
1550 if (CurTok.is(tok::greater))
1551 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001552
John Thompsonb5353522009-10-30 13:49:06 +00001553 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001554 }
1555
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001556 // If we hit the eod marker, emit an error and return true so that the caller
1557 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001558 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001559 return true;
1560}
1561
Richard Smith34f30512013-11-23 04:06:09 +00001562/// \brief Push a token onto the token stream containing an annotation.
Richard Smithc51c38b2017-04-29 00:34:47 +00001563void Preprocessor::EnterAnnotationToken(SourceRange Range,
1564 tok::TokenKind Kind,
1565 void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001566 // FIXME: Produce this as the current token directly, rather than
1567 // allocating a new token for it.
David Blaikie2eabcc92016-02-09 18:52:09 +00001568 auto Tok = llvm::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001569 Tok[0].startToken();
1570 Tok[0].setKind(Kind);
Richard Smithc51c38b2017-04-29 00:34:47 +00001571 Tok[0].setLocation(Range.getBegin());
1572 Tok[0].setAnnotationEndLoc(Range.getEnd());
Richard Smith34f30512013-11-23 04:06:09 +00001573 Tok[0].setAnnotationValue(AnnotationVal);
Richard Smithc51c38b2017-04-29 00:34:47 +00001574 EnterTokenStream(std::move(Tok), 1, true);
Richard Smith34f30512013-11-23 04:06:09 +00001575}
1576
Richard Smith63b6fce2015-05-18 04:45:41 +00001577/// \brief Produce a diagnostic informing the user that a #include or similar
1578/// was implicitly treated as a module import.
1579static void diagnoseAutoModuleImport(
1580 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1581 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1582 SourceLocation PathEnd) {
1583 assert(PP.getLangOpts().ObjC2 && "no import syntax available");
1584
1585 SmallString<128> PathString;
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001586 for (size_t I = 0, N = Path.size(); I != N; ++I) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001587 if (I)
1588 PathString += '.';
1589 PathString += Path[I].first->getName();
1590 }
1591 int IncludeKind = 0;
Taewook Oh755e4d22016-06-13 21:55:33 +00001592
Richard Smith63b6fce2015-05-18 04:45:41 +00001593 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1594 case tok::pp_include:
1595 IncludeKind = 0;
1596 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001597
Richard Smith63b6fce2015-05-18 04:45:41 +00001598 case tok::pp_import:
1599 IncludeKind = 1;
Taewook Oh755e4d22016-06-13 21:55:33 +00001600 break;
1601
Richard Smith63b6fce2015-05-18 04:45:41 +00001602 case tok::pp_include_next:
1603 IncludeKind = 2;
1604 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001605
Richard Smith63b6fce2015-05-18 04:45:41 +00001606 case tok::pp___include_macros:
1607 IncludeKind = 3;
1608 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001609
Richard Smith63b6fce2015-05-18 04:45:41 +00001610 default:
1611 llvm_unreachable("unknown include directive kind");
1612 }
1613
1614 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1615 /*IsTokenRange=*/false);
1616 PP.Diag(HashLoc, diag::warn_auto_module_import)
1617 << IncludeKind << PathString
1618 << FixItHint::CreateReplacement(ReplaceRange,
1619 ("@import " + PathString + ";").str());
1620}
1621
Taewook Ohf42103c2016-06-13 20:40:21 +00001622// Given a vector of path components and a string containing the real
1623// path to the file, build a properly-cased replacement in the vector,
1624// and return true if the replacement should be suggested.
1625static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1626 StringRef RealPathName) {
1627 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1628 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1629 int Cnt = 0;
1630 bool SuggestReplacement = false;
1631 // Below is a best-effort to handle ".." in paths. It is admittedly
1632 // not 100% correct in the presence of symlinks.
1633 for (auto &Component : llvm::reverse(Components)) {
1634 if ("." == Component) {
1635 } else if (".." == Component) {
1636 ++Cnt;
1637 } else if (Cnt) {
1638 --Cnt;
1639 } else if (RealPathComponentIter != RealPathComponentEnd) {
1640 if (Component != *RealPathComponentIter) {
1641 // If these path components differ by more than just case, then we
1642 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1643 // noisy false positives.
1644 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1645 if (!SuggestReplacement)
1646 break;
1647 Component = *RealPathComponentIter;
1648 }
1649 ++RealPathComponentIter;
1650 }
1651 }
1652 return SuggestReplacement;
1653}
1654
James Dennettf6333ac2012-06-22 05:46:07 +00001655/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1656/// the file to be included from the lexer, then include it! This is a common
1657/// routine with functionality shared between \#include, \#include_next and
1658/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001659/// specifies the file to start searching from.
Taewook Oh755e4d22016-06-13 21:55:33 +00001660void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001661 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001662 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001663 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001664 bool isImport) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001665 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001666 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001667
Chris Lattnerf64b3522008-03-09 01:54:53 +00001668 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001669 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001670 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001671 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001672 SourceLocation CharEnd; // the end of this directive, in characters
Taewook Oh755e4d22016-06-13 21:55:33 +00001673
Chris Lattnerf64b3522008-03-09 01:54:53 +00001674 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001675 case tok::eod:
1676 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001677 return;
Mike Stump11289f42009-09-09 15:08:12 +00001678
Chris Lattnerf64b3522008-03-09 01:54:53 +00001679 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001680 case tok::string_literal:
1681 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001682 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001683 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001684 break;
Mike Stump11289f42009-09-09 15:08:12 +00001685
Chris Lattnerf64b3522008-03-09 01:54:53 +00001686 case tok::less:
1687 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1688 // case, glue the tokens together into FilenameBuffer and interpret those.
1689 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001690 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001691 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001692 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001693 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001694 break;
1695 default:
1696 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1697 DiscardUntilEndOfDirective();
1698 return;
1699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001701 CharSourceRange FilenameRange
1702 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001703 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001704 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001705 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001706 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1707 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001708 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001709 DiscardUntilEndOfDirective();
1710 return;
1711 }
Mike Stump11289f42009-09-09 15:08:12 +00001712
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001713 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001714 // we allow macros that expand to nothing after the filename, because this
1715 // falls into the category of "#include pp-tokens new-line" specified in
1716 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001717 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001718
1719 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001720 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1721 Diag(FilenameTok, diag::err_pp_include_too_deep);
1722 return;
1723 }
Mike Stump11289f42009-09-09 15:08:12 +00001724
John McCall32f5fe12011-09-30 05:12:12 +00001725 // Complain about attempts to #include files in an audit pragma.
1726 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1727 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1728 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1729
1730 // Immediately leave the pragma.
1731 PragmaARCCFCodeAuditedLoc = SourceLocation();
1732 }
1733
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001734 // Complain about attempts to #include files in an assume-nonnull pragma.
1735 if (PragmaAssumeNonNullLoc.isValid()) {
1736 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1737 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1738
1739 // Immediately leave the pragma.
1740 PragmaAssumeNonNullLoc = SourceLocation();
1741 }
1742
Aaron Ballman611306e2012-03-02 22:51:54 +00001743 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001744 // Map the filename with the brackets still attached. If the name doesn't
1745 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001746 // spelling for.
1747 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1748 if (!NewName.empty())
1749 Filename = NewName;
1750 }
1751
Chris Lattnerf64b3522008-03-09 01:54:53 +00001752 // Search include directories.
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001753 bool IsMapped = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001754 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001755 SmallString<1024> SearchPath;
1756 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001757 // We get the raw path only if we have 'Callbacks' to which we later pass
1758 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001759 ModuleMap::KnownHeader SuggestedModule;
1760 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001761 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001762 if (LangOpts.MSVCCompat) {
1763 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001764#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001765 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001766#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001767 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001768 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001769 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001770 isAngled, LookupFrom, LookupFromFile, CurDir,
1771 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001772 &SuggestedModule, &IsMapped);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001773
Richard Smithdbbc5232015-05-14 02:25:44 +00001774 if (!File) {
1775 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001776 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001777 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001778 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1779 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1780 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001781 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001782 HeaderInfo.AddSearchPath(DL, isAngled);
Taewook Oh755e4d22016-06-13 21:55:33 +00001783
Douglas Gregor11729f02011-11-30 18:12:06 +00001784 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001785 File = LookupFile(
1786 FilenameLoc,
1787 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1788 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001789 &SuggestedModule, &IsMapped, /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001790 }
1791 }
1792 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001793
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001794 if (!SuppressIncludeNotFoundError) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001795 // If the file could not be located and it was included via angle
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001796 // brackets, we can attempt a lookup as though it were a quoted path to
1797 // provide the user with a possible fixit.
1798 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001799 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001800 FilenameLoc,
1801 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1802 LookupFrom, LookupFromFile, CurDir,
1803 Callbacks ? &SearchPath : nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001804 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001805 if (File) {
1806 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001807 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1808 Filename <<
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001809 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1810 }
1811 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001812
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001813 // If the file is still not found, just go with the vanilla diagnostic
1814 if (!File)
Erik Verbruggen45449542016-10-25 10:13:10 +00001815 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename
1816 << FilenameRange;
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001817 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001818 }
1819
Richard Smith63b6fce2015-05-18 04:45:41 +00001820 // Should we enter the source file? Set to false if either the source file is
1821 // known to have no effect beyond its effect on module visibility -- that is,
1822 // if it's got an include guard that is already defined or is a modular header
1823 // we've imported or already built.
1824 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001825
Richard Smith63b6fce2015-05-18 04:45:41 +00001826 // Determine whether we should try to import the module for this #include, if
1827 // there is one. Don't do so if precompiled module support is disabled or we
1828 // are processing this module textually (because we're building the module).
1829 if (File && SuggestedModule && getLangOpts().Modules &&
1830 SuggestedModule.getModule()->getTopLevelModuleName() !=
Richard Smith7e82e012016-02-19 22:25:36 +00001831 getLangOpts().CurrentModule) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001832 // If this include corresponds to a module but that module is
1833 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001834 // FIXME: Remove this; loadModule does the same check (but produces
1835 // slightly worse diagnostics).
Richard Smitha114c462016-12-06 00:40:17 +00001836 if (!SuggestedModule.getModule()->isAvailable()) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001837 Module::Requirement Requirement;
1838 Module::UnresolvedHeaderDirective MissingHeader;
Sean Silva8b7c0392015-08-17 16:39:30 +00001839 Module *M = SuggestedModule.getModule();
1840 // Identify the cause.
1841 (void)M->isAvailable(getLangOpts(), getTargetInfo(), Requirement,
1842 MissingHeader);
1843 if (MissingHeader.FileNameLoc.isValid()) {
1844 Diag(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1845 << MissingHeader.IsUmbrella << MissingHeader.FileName;
1846 } else {
1847 Diag(M->DefinitionLoc, diag::err_module_unavailable)
1848 << M->getFullModuleName() << Requirement.second << Requirement.first;
1849 }
1850 Diag(FilenameTok.getLocation(),
1851 diag::note_implicit_top_level_module_import_here)
1852 << M->getTopLevelModuleName();
1853 return;
1854 }
1855
Douglas Gregor71944202011-11-30 00:36:36 +00001856 // Compute the module access path corresponding to this module.
1857 // FIXME: Should we have a second loadModule() overload to avoid this
1858 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001859 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001860 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001861 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1862 FilenameTok.getLocation()));
1863 std::reverse(Path.begin(), Path.end());
1864
Douglas Gregor41e115a2011-11-30 18:02:36 +00001865 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001866 // We only do this in Objective-C, where we have a module-import syntax.
1867 if (getLangOpts().ObjC2)
1868 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001869
Richard Smith10434f32015-05-02 02:08:26 +00001870 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001871 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001872 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1873 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001874 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1875 IncludeTok.getLocation(), Path, Module::Hidden,
1876 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001877 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001878 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001879
Richard Smith63b6fce2015-05-18 04:45:41 +00001880 if (Imported)
1881 ShouldEnter = false;
1882 else if (Imported.isMissingExpected()) {
1883 // We failed to find a submodule that we assumed would exist (because it
1884 // was in the directory of an umbrella header, for instance), but no
Richard Smitha114c462016-12-06 00:40:17 +00001885 // actual module containing it exists (because the umbrella header is
Richard Smith63b6fce2015-05-18 04:45:41 +00001886 // incomplete). Treat this as a textual inclusion.
1887 SuggestedModule = ModuleMap::KnownHeader();
Richard Smitha114c462016-12-06 00:40:17 +00001888 } else if (Imported.isConfigMismatch()) {
1889 // On a configuration mismatch, enter the header textually. We still know
1890 // that it's part of the corresponding module.
Richard Smith63b6fce2015-05-18 04:45:41 +00001891 } else {
1892 // We hit an error processing the import. Bail out.
1893 if (hadModuleLoaderFatalFailure()) {
1894 // With a fatal failure in the module loader, we abort parsing.
1895 Token &Result = IncludeTok;
1896 if (CurLexer) {
1897 Result.startToken();
1898 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1899 CurLexer->cutOffLexing();
1900 } else {
1901 assert(CurPTHLexer && "#include but no current lexer set!");
1902 CurPTHLexer->getEOF(Result);
1903 }
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001904 }
1905 return;
1906 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001907 }
1908
Richard Smith63b6fce2015-05-18 04:45:41 +00001909 if (Callbacks) {
1910 // Notify the callback object that we've seen an inclusion directive.
1911 Callbacks->InclusionDirective(
1912 HashLoc, IncludeTok,
1913 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1914 FilenameRange, File, SearchPath, RelativePath,
1915 ShouldEnter ? nullptr : SuggestedModule.getModule());
Douglas Gregor97eec242011-09-15 22:00:41 +00001916 }
Richard Smith63b6fce2015-05-18 04:45:41 +00001917
1918 if (!File)
1919 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001920
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001921 // The #included file will be considered to be a system header if either it is
1922 // in a system include directory, or if the #includer is a system include
1923 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001924 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001925 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001926 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001927
Richard Smith54ef4c32015-05-19 19:58:11 +00001928 // FIXME: If we have a suggested module, and we've already visited this file,
1929 // don't bother entering it again. We know it has no further effect.
1930
Taewook Ohf42103c2016-06-13 20:40:21 +00001931 // Issue a diagnostic if the name of the file on disk has a different case
1932 // than the one we're about to open.
1933 const bool CheckIncludePathPortability =
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001934 !IsMapped && File && !File->tryGetRealPathName().empty();
Taewook Ohf42103c2016-06-13 20:40:21 +00001935
1936 if (CheckIncludePathPortability) {
1937 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
1938 StringRef RealPathName = File->tryGetRealPathName();
1939 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
1940 llvm::sys::path::end(Name));
1941
1942 if (trySimplifyPath(Components, RealPathName)) {
1943 SmallString<128> Path;
1944 Path.reserve(Name.size()+2);
1945 Path.push_back(isAngled ? '<' : '"');
Taewook Ohcc89bac2017-02-21 22:30:55 +00001946 bool isLeadingSeparator = llvm::sys::path::is_absolute(Name);
Taewook Ohf42103c2016-06-13 20:40:21 +00001947 for (auto Component : Components) {
Taewook Ohcc89bac2017-02-21 22:30:55 +00001948 if (isLeadingSeparator)
1949 isLeadingSeparator = false;
1950 else
1951 Path.append(Component);
Taewook Ohf42103c2016-06-13 20:40:21 +00001952 // Append the separator the user used, or the close quote
1953 Path.push_back(
1954 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
1955 (isAngled ? '>' : '"'));
1956 }
Taewook Ohf42103c2016-06-13 20:40:21 +00001957 // For user files and known standard headers, by default we issue a diagnostic.
1958 // For other system headers, we don't. They can be controlled separately.
1959 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
1960 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
1961 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Reid Kleckner273895b2017-02-14 18:38:40 +00001962 Diag(FilenameTok, DiagId) << Path <<
1963 FixItHint::CreateReplacement(Range, Path);
Taewook Ohf42103c2016-06-13 20:40:21 +00001964 }
1965 }
1966
Chris Lattner72286d62010-04-19 20:44:31 +00001967 // Ask HeaderInfo if we should enter this #include file. If not, #including
Richard Smith54ef4c32015-05-19 19:58:11 +00001968 // this file will have no effect.
Manman Renffd3e9d2017-01-09 19:20:18 +00001969 bool SkipHeader = false;
Richard Smith63b6fce2015-05-18 04:45:41 +00001970 if (ShouldEnter &&
Richard Smith035f6dc2015-07-01 01:51:38 +00001971 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001972 getLangOpts().Modules,
Richard Smith035f6dc2015-07-01 01:51:38 +00001973 SuggestedModule.getModule())) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001974 ShouldEnter = false;
Manman Renffd3e9d2017-01-09 19:20:18 +00001975 SkipHeader = true;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001976 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001977 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Richard Smith63b6fce2015-05-18 04:45:41 +00001978 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001979
Richard Smith63b6fce2015-05-18 04:45:41 +00001980 // If we don't need to enter the file, stop now.
1981 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001982 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00001983 if (auto *M = SuggestedModule.getModule()) {
Manman Renffd3e9d2017-01-09 19:20:18 +00001984 // When building a pch, -fmodule-name tells the compiler to textually
1985 // include headers in the specified module. But it is possible that
1986 // ShouldEnter is false because we are skipping the header. In that
1987 // case, We are not importing the specified module.
1988 if (SkipHeader && getLangOpts().CompilingPCH &&
1989 M->getTopLevelModuleName() == getLangOpts().CurrentModule)
1990 return;
1991
Richard Smitha0aafa32015-05-18 03:52:30 +00001992 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00001993
1994 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
1995 tok::pp___include_macros)
Richard Smithc51c38b2017-04-29 00:34:47 +00001996 EnterAnnotationToken(SourceRange(HashLoc, End),
1997 tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00001998 }
Chris Lattner72286d62010-04-19 20:44:31 +00001999 return;
2000 }
2001
Chris Lattnerf64b3522008-03-09 01:54:53 +00002002 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002003 SourceLocation IncludePos = End;
2004 // If the filename string was the result of macro expansions, set the include
2005 // position on the file where it will be included and after the expansions.
2006 if (IncludePos.isMacroID())
2007 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
2008 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002009 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002010
Richard Smith34f30512013-11-23 04:06:09 +00002011 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002012 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
2013 return;
Richard Smith34f30512013-11-23 04:06:09 +00002014
Richard Smitha0aafa32015-05-18 03:52:30 +00002015 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002016 if (auto *M = SuggestedModule.getModule()) {
Manman Renffd3e9d2017-01-09 19:20:18 +00002017 // When building a pch, -fmodule-name tells the compiler to textually
2018 // include headers in the specified module. We are not building the
2019 // specified module.
2020 if (getLangOpts().CompilingPCH &&
2021 M->getTopLevelModuleName() == getLangOpts().CurrentModule)
2022 return;
2023
Richard Smithd1386302017-05-04 00:29:54 +00002024 assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2025 CurLexerSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002026
Richard Smitha0aafa32015-05-18 03:52:30 +00002027 // Let the macro handling code know that any future macros are within
2028 // the new submodule.
Richard Smithd1386302017-05-04 00:29:54 +00002029 EnterSubmodule(M, HashLoc, /*ForPragma*/false);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002030
Richard Smitha0aafa32015-05-18 03:52:30 +00002031 // Let the parser know that any future declarations are within the new
2032 // submodule.
2033 // FIXME: There's no point doing this if we're handling a #__include_macros
2034 // directive.
Richard Smithc51c38b2017-04-29 00:34:47 +00002035 EnterAnnotationToken(SourceRange(HashLoc, End), tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00002036 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002037}
2038
James Dennettf6333ac2012-06-22 05:46:07 +00002039/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002040///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002041void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2042 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002043 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002044
Chris Lattnerf64b3522008-03-09 01:54:53 +00002045 // #include_next is like #include, except that we start searching after
2046 // the current found directory. If we can't do this, issue a
2047 // diagnostic.
2048 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002049 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00002050 if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2051 // If the main file is a header, then it's either for PCH/AST generation,
2052 // or libclang opened it. Either way, handle it as a normal include below
2053 // and do not complain about include_next.
2054 } else if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002055 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002056 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smithd1386302017-05-04 00:29:54 +00002057 } else if (CurLexerSubmodule) {
Richard Smith25d50752014-10-20 00:15:49 +00002058 // Start looking up in the directory *after* the one in which the current
2059 // file would be found, if any.
2060 assert(CurPPLexer && "#include_next directive in macro?");
2061 LookupFromFile = CurPPLexer->getFileEntry();
2062 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002063 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002064 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2065 } else {
2066 // Start looking up in the next directory.
2067 ++Lookup;
2068 }
Mike Stump11289f42009-09-09 15:08:12 +00002069
Richard Smith25d50752014-10-20 00:15:49 +00002070 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2071 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002072}
2073
James Dennettf6333ac2012-06-22 05:46:07 +00002074/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002075void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2076 // The Microsoft #import directive takes a type library and generates header
2077 // files from it, and includes those. This is beyond the scope of what clang
2078 // does, so we ignore it and error out. However, #import can optionally have
2079 // trailing attributes that span multiple lines. We're going to eat those
2080 // so we can continue processing from there.
2081 Diag(Tok, diag::err_pp_import_directive_ms );
2082
Taewook Oh755e4d22016-06-13 21:55:33 +00002083 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002084 // directive can be split over multiple lines using the backslash character.
2085 DiscardUntilEndOfDirective();
2086}
2087
James Dennettf6333ac2012-06-22 05:46:07 +00002088/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002089///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002090void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2091 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00002092 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002093 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002094 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002095 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002096 }
Richard Smith25d50752014-10-20 00:15:49 +00002097 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002098}
2099
Chris Lattner58a1eb02009-04-08 18:46:40 +00002100/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2101/// pseudo directive in the predefines buffer. This handles it by sucking all
2102/// tokens through the preprocessor and discarding them (only keeping the side
2103/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002104void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2105 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002106 // This directive should only occur in the predefines buffer. If not, emit an
2107 // error and reject it.
2108 SourceLocation Loc = IncludeMacrosTok.getLocation();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002109 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002110 Diag(IncludeMacrosTok.getLocation(),
2111 diag::pp_include_macros_out_of_predefines);
2112 DiscardUntilEndOfDirective();
2113 return;
2114 }
Mike Stump11289f42009-09-09 15:08:12 +00002115
Chris Lattnere01d82b2009-04-08 20:53:24 +00002116 // Treat this as a normal #include for checking purposes. If this is
2117 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002118 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002119
Chris Lattnere01d82b2009-04-08 20:53:24 +00002120 Token TmpTok;
2121 do {
2122 Lex(TmpTok);
2123 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2124 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002125}
2126
Chris Lattnerf64b3522008-03-09 01:54:53 +00002127//===----------------------------------------------------------------------===//
2128// Preprocessor Macro Directive Handling.
2129//===----------------------------------------------------------------------===//
2130
2131/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
2132/// definition has just been read. Lex the rest of the arguments and the
2133/// closing ), updating MI with what we learn. Return true if an error occurs
2134/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002135bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002136 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00002137
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002138 while (true) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002139 LexUnexpandedToken(Tok);
2140 switch (Tok.getKind()) {
2141 case tok::r_paren:
2142 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00002143 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002144 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002145 // Otherwise we have #define FOO(A,)
2146 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2147 return true;
2148 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002149 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002150 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002151 diag::warn_cxx98_compat_variadic_macro :
2152 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002153
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002154 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2155 if (LangOpts.OpenCL) {
2156 Diag(Tok, diag::err_pp_opencl_variadic_macros);
2157 return true;
2158 }
2159
Chris Lattnerf64b3522008-03-09 01:54:53 +00002160 // Lex the token after the identifier.
2161 LexUnexpandedToken(Tok);
2162 if (Tok.isNot(tok::r_paren)) {
2163 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2164 return true;
2165 }
2166 // Add the __VA_ARGS__ identifier as an argument.
2167 Arguments.push_back(Ident__VA_ARGS__);
2168 MI->setIsC99Varargs();
Craig Topperd96b3f92015-10-22 04:59:52 +00002169 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002170 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002171 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002172 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2173 return true;
2174 default:
2175 // Handle keywords and identifiers here to accept things like
2176 // #define Foo(for) for.
2177 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002178 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002179 // #define X(1
2180 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2181 return true;
2182 }
2183
2184 // If this is already used as an argument, it is used multiple times (e.g.
2185 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00002186 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00002187 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002188 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002189 return true;
2190 }
Mike Stump11289f42009-09-09 15:08:12 +00002191
Chris Lattnerf64b3522008-03-09 01:54:53 +00002192 // Add the argument to the macro info.
2193 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002194
Chris Lattnerf64b3522008-03-09 01:54:53 +00002195 // Lex the token after the identifier.
2196 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002197
Chris Lattnerf64b3522008-03-09 01:54:53 +00002198 switch (Tok.getKind()) {
2199 default: // #define X(A B
2200 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2201 return true;
2202 case tok::r_paren: // #define X(A)
Craig Topperd96b3f92015-10-22 04:59:52 +00002203 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002204 return false;
2205 case tok::comma: // #define X(A,
2206 break;
2207 case tok::ellipsis: // #define X(A... -> GCC extension
2208 // Diagnose extension.
2209 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattnerf64b3522008-03-09 01:54:53 +00002211 // Lex the token after the identifier.
2212 LexUnexpandedToken(Tok);
2213 if (Tok.isNot(tok::r_paren)) {
2214 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2215 return true;
2216 }
Mike Stump11289f42009-09-09 15:08:12 +00002217
Chris Lattnerf64b3522008-03-09 01:54:53 +00002218 MI->setIsGNUVarargs();
Craig Topperd96b3f92015-10-22 04:59:52 +00002219 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002220 return false;
2221 }
2222 }
2223 }
2224}
2225
Serge Pavlov07c0f042014-12-18 11:14:21 +00002226static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2227 const LangOptions &LOptions) {
2228 if (MI->getNumTokens() == 1) {
2229 const Token &Value = MI->getReplacementToken(0);
2230
2231 // Macro that is identity, like '#define inline inline' is a valid pattern.
2232 if (MacroName.getKind() == Value.getKind())
2233 return true;
2234
2235 // Macro that maps a keyword to the same keyword decorated with leading/
2236 // trailing underscores is a valid pattern:
2237 // #define inline __inline
2238 // #define inline __inline__
2239 // #define inline _inline (in MS compatibility mode)
2240 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2241 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2242 if (!II->isKeyword(LOptions))
2243 return false;
2244 StringRef ValueText = II->getName();
2245 StringRef TrimmedValue = ValueText;
2246 if (!ValueText.startswith("__")) {
2247 if (ValueText.startswith("_"))
2248 TrimmedValue = TrimmedValue.drop_front(1);
2249 else
2250 return false;
2251 } else {
2252 TrimmedValue = TrimmedValue.drop_front(2);
2253 if (TrimmedValue.endswith("__"))
2254 TrimmedValue = TrimmedValue.drop_back(2);
2255 }
2256 return TrimmedValue.equals(MacroText);
2257 } else {
2258 return false;
2259 }
2260 }
2261
2262 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002263 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2264 tok::kw_const) &&
2265 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002266}
2267
James Dennettf6333ac2012-06-22 05:46:07 +00002268/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00002269/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002270void Preprocessor::HandleDefineDirective(Token &DefineTok,
2271 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002272 ++NumDefined;
2273
2274 Token MacroNameTok;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002275 bool MacroShadowsKeyword;
2276 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
Mike Stump11289f42009-09-09 15:08:12 +00002277
Chris Lattnerf64b3522008-03-09 01:54:53 +00002278 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002279 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002280 return;
2281
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002282 Token LastTok = MacroNameTok;
2283
Chris Lattnerf64b3522008-03-09 01:54:53 +00002284 // If we are supposed to keep comments in #defines, reenable comment saving
2285 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00002286 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00002287
Chris Lattnerf64b3522008-03-09 01:54:53 +00002288 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002289 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002290
Chris Lattnerf64b3522008-03-09 01:54:53 +00002291 Token Tok;
2292 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002293
Chris Lattnerf64b3522008-03-09 01:54:53 +00002294 // If this is a function-like macro definition, parse the argument list,
2295 // marking each of the identifiers as being used as macro arguments. Also,
2296 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002297 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002298 if (ImmediatelyAfterHeaderGuard) {
2299 // Save this macro information since it may part of a header guard.
2300 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2301 MacroNameTok.getLocation());
2302 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002303 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002304 } else if (Tok.hasLeadingSpace()) {
2305 // This is a normal token with leading space. Clear the leading space
2306 // marker on the first token to get proper expansion.
2307 Tok.clearFlag(Token::LeadingSpace);
2308 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002309 // This is a function-like macro definition. Read the argument list.
2310 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002311 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002312 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002313 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002314 DiscardUntilEndOfDirective();
2315 return;
2316 }
2317
Chris Lattner249c38b2009-04-19 18:26:34 +00002318 // If this is a definition of a variadic C99 function-like macro, not using
2319 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00002320
Chris Lattner249c38b2009-04-19 18:26:34 +00002321 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2322 // This gets unpoisoned where it is allowed.
2323 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2324 if (MI->isC99Varargs())
2325 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00002326
Chris Lattnerf64b3522008-03-09 01:54:53 +00002327 // Read the first token after the arg list for down below.
2328 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002329 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002330 // C99 requires whitespace between the macro definition and the body. Emit
2331 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002332 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002333 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002334 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2335 // first character of a replacement list is not a character required by
2336 // subclause 5.2.1, then there shall be white-space separation between the
2337 // identifier and the replacement list.". 5.2.1 lists this set:
2338 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2339 // is irrelevant here.
2340 bool isInvalid = false;
2341 if (Tok.is(tok::at)) // @ is not in the list above.
2342 isInvalid = true;
2343 else if (Tok.is(tok::unknown)) {
2344 // If we have an unknown token, it is something strange like "`". Since
2345 // all of valid characters would have lexed into a single character
2346 // token of some sort, we know this is not a valid case.
2347 isInvalid = true;
2348 }
2349 if (isInvalid)
2350 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2351 else
2352 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002353 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002354
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002355 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002356 LastTok = Tok;
2357
Chris Lattnerf64b3522008-03-09 01:54:53 +00002358 // Read the rest of the macro body.
2359 if (MI->isObjectLike()) {
2360 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002361 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002362 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002363 MI->AddTokenToBody(Tok);
2364 // Get the next token of the macro.
2365 LexUnexpandedToken(Tok);
2366 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002367 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002368 // Otherwise, read the body of a function-like macro. While we are at it,
2369 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2370 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002371 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002372 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002373
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002374 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002375 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002376
Chris Lattnerf64b3522008-03-09 01:54:53 +00002377 // Get the next token of the macro.
2378 LexUnexpandedToken(Tok);
2379 continue;
2380 }
Mike Stump11289f42009-09-09 15:08:12 +00002381
Richard Smith701a3522013-07-09 01:00:29 +00002382 // If we're in -traditional mode, then we should ignore stringification
2383 // and token pasting. Mark the tokens as unknown so as not to confuse
2384 // things.
2385 if (getLangOpts().TraditionalCPP) {
2386 Tok.setKind(tok::unknown);
2387 MI->AddTokenToBody(Tok);
2388
2389 // Get the next token of the macro.
2390 LexUnexpandedToken(Tok);
2391 continue;
2392 }
2393
Eli Friedman14d3c792012-11-14 02:18:46 +00002394 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002395 // If we see token pasting, check if it looks like the gcc comma
2396 // pasting extension. We'll use this information to suppress
2397 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002398
Eli Friedman14d3c792012-11-14 02:18:46 +00002399 // Get the next token of the macro.
2400 LexUnexpandedToken(Tok);
2401
2402 if (Tok.is(tok::eod)) {
2403 MI->AddTokenToBody(LastTok);
2404 break;
2405 }
2406
2407 unsigned NumTokens = MI->getNumTokens();
2408 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2409 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2410 MI->setHasCommaPasting();
2411
David Majnemer76faf1f2013-11-05 09:30:17 +00002412 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002413 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002414 continue;
2415 }
2416
Chris Lattnerf64b3522008-03-09 01:54:53 +00002417 // Get the next token of the macro.
2418 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002419
Chris Lattner83bd8282009-05-25 17:16:10 +00002420 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002421 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002422 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2423
2424 // If this is assembler-with-cpp mode, we accept random gibberish after
2425 // the '#' because '#' is often a comment character. However, change
2426 // the kind of the token to tok::unknown so that the preprocessor isn't
2427 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002428 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002429 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002430 MI->AddTokenToBody(LastTok);
2431 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002432 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002433 Diag(Tok, diag::err_pp_stringize_not_parameter)
2434 << LastTok.is(tok::hashat);
Mike Stump11289f42009-09-09 15:08:12 +00002435
Chris Lattner83bd8282009-05-25 17:16:10 +00002436 // Disable __VA_ARGS__ again.
2437 Ident__VA_ARGS__->setIsPoisoned(true);
2438 return;
2439 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002440 }
Mike Stump11289f42009-09-09 15:08:12 +00002441
Chris Lattner83bd8282009-05-25 17:16:10 +00002442 // Things look ok, add the '#' and param name tokens to the macro.
2443 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002444 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002445 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002446
Chris Lattnerf64b3522008-03-09 01:54:53 +00002447 // Get the next token of the macro.
2448 LexUnexpandedToken(Tok);
2449 }
2450 }
Mike Stump11289f42009-09-09 15:08:12 +00002451
Serge Pavlov07c0f042014-12-18 11:14:21 +00002452 if (MacroShadowsKeyword &&
2453 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2454 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2455 }
Mike Stump11289f42009-09-09 15:08:12 +00002456
Chris Lattnerf64b3522008-03-09 01:54:53 +00002457 // Disable __VA_ARGS__ again.
2458 Ident__VA_ARGS__->setIsPoisoned(true);
2459
Chris Lattner57540c52011-04-15 05:22:18 +00002460 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002461 // replacement list.
2462 unsigned NumTokens = MI->getNumTokens();
2463 if (NumTokens != 0) {
2464 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2465 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002466 return;
2467 }
2468 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2469 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002470 return;
2471 }
2472 }
Mike Stump11289f42009-09-09 15:08:12 +00002473
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002474 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002475
Chris Lattnerf64b3522008-03-09 01:54:53 +00002476 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002477 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002478 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002479 // In Objective-C, ignore attempts to directly redefine the builtin
2480 // definitions of the ownership qualifiers. It's still possible to
2481 // #undef them.
2482 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2483 return II->isStr("__strong") ||
2484 II->isStr("__weak") ||
2485 II->isStr("__unsafe_unretained") ||
2486 II->isStr("__autoreleasing");
2487 };
2488 if (getLangOpts().ObjC1 &&
2489 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2490 == getPredefinesFileID() &&
2491 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2492 // Warn if it changes the tokens.
2493 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2494 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2495 !MI->isIdenticalTo(*OtherMI, *this,
2496 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2497 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2498 }
2499 assert(!OtherMI->isWarnIfUnused());
2500 return;
2501 }
2502
Chris Lattner5244f342009-01-16 19:50:11 +00002503 // It is very common for system headers to have tons of macro redefinitions
2504 // and for warnings to be disabled in system headers. If this is the case,
2505 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002506 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002507 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002508 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002509 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002510
Taewook Oh755e4d22016-06-13 21:55:33 +00002511 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002512 // C++ [cpp.predefined]p4, but allow it as an extension.
2513 if (OtherMI->isBuiltinMacro())
2514 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002515 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002516 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002517 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002518 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002519 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2520 << MacroNameTok.getIdentifierInfo();
2521 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2522 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002523 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002524 if (OtherMI->isWarnIfUnused())
2525 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002526 }
Mike Stump11289f42009-09-09 15:08:12 +00002527
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002528 DefMacroDirective *MD =
2529 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002530
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002531 assert(!MI->isUsed());
2532 // If we need warning for not using the macro, add its location in the
2533 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002534 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002535 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002536 MI->setIsWarnIfUnused(true);
2537 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2538 }
2539
Chris Lattner928e9092009-04-12 01:39:54 +00002540 // If the callbacks want to know, tell them about the macro definition.
2541 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002542 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002543}
2544
James Dennettf6333ac2012-06-22 05:46:07 +00002545/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002546///
Erik Verbruggen4bddef92016-10-26 08:52:41 +00002547void Preprocessor::HandleUndefDirective() {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002548 ++NumUndefined;
2549
2550 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002551 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002552
Chris Lattnerf64b3522008-03-09 01:54:53 +00002553 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002554 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002555 return;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Chris Lattnerf64b3522008-03-09 01:54:53 +00002557 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002558 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002559
Richard Smith20e883e2015-04-29 23:20:19 +00002560 // Okay, we have a valid identifier to undef.
2561 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002562 auto MD = getMacroDefinition(II);
Vedant Kumar349a6242017-04-26 21:05:44 +00002563 UndefMacroDirective *Undef = nullptr;
2564
2565 // If the macro is not defined, this is a noop undef.
2566 if (const MacroInfo *MI = MD.getMacroInfo()) {
2567 if (!MI->isUsed() && MI->isWarnIfUnused())
2568 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2569
2570 if (MI->isWarnIfUnused())
2571 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2572
2573 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
2574 }
Mike Stump11289f42009-09-09 15:08:12 +00002575
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002576 // If the callbacks want to know, tell them about the macro #undef.
2577 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002578 if (Callbacks)
Vedant Kumar349a6242017-04-26 21:05:44 +00002579 Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002580
Vedant Kumar349a6242017-04-26 21:05:44 +00002581 if (Undef)
2582 appendMacroDirective(II, Undef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002583}
2584
Chris Lattnerf64b3522008-03-09 01:54:53 +00002585//===----------------------------------------------------------------------===//
2586// Preprocessor Conditional Directive Handling.
2587//===----------------------------------------------------------------------===//
2588
James Dennettf6333ac2012-06-22 05:46:07 +00002589/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2590/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2591/// true if any tokens have been returned or pp-directives activated before this
2592/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002593///
2594void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2595 bool ReadAnyTokensBeforeDirective) {
2596 ++NumIf;
2597 Token DirectiveTok = Result;
2598
2599 Token MacroNameTok;
2600 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002601
Chris Lattnerf64b3522008-03-09 01:54:53 +00002602 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002603 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002604 // Skip code until we get to #endif. This helps with recovery by not
2605 // emitting an error when the #endif is reached.
2606 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2607 /*Foundnonskip*/false, /*FoundElse*/false);
2608 return;
2609 }
Mike Stump11289f42009-09-09 15:08:12 +00002610
Chris Lattnerf64b3522008-03-09 01:54:53 +00002611 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002612 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002613
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002614 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002615 auto MD = getMacroDefinition(MII);
2616 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002617
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002618 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002619 // If the start of a top-level #ifdef and if the macro is not defined,
2620 // inform MIOpt that this might be the start of a proper include guard.
2621 // Otherwise it is some other form of unknown conditional which we can't
2622 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002623 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002624 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002625 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002626 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002627 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002628 }
2629
Chris Lattnerf64b3522008-03-09 01:54:53 +00002630 // If there is a macro, process it.
2631 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002632 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002633
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002634 if (Callbacks) {
2635 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002636 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002637 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002638 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002639 }
2640
Chris Lattnerf64b3522008-03-09 01:54:53 +00002641 // Should we include the stuff contained by this directive?
2642 if (!MI == isIfndef) {
2643 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002644 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2645 /*wasskip*/false, /*foundnonskip*/true,
2646 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002647 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002648 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002649 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002650 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002651 /*FoundElse*/false);
2652 }
2653}
2654
James Dennettf6333ac2012-06-22 05:46:07 +00002655/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002656///
2657void Preprocessor::HandleIfDirective(Token &IfToken,
2658 bool ReadAnyTokensBeforeDirective) {
2659 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002660
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002661 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002662 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002663 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2664 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2665 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002666
2667 // If this condition is equivalent to #ifndef X, and if this is the first
2668 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002669 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002670 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002671 // FIXME: Pass in the location of the macro name, not the 'if' token.
2672 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002673 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002674 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002675 }
2676
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002677 if (Callbacks)
2678 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002679 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002680 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002681
Chris Lattnerf64b3522008-03-09 01:54:53 +00002682 // Should we include the stuff contained by this directive?
2683 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002684 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002685 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002686 /*foundnonskip*/true, /*foundelse*/false);
2687 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002688 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002689 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002690 /*FoundElse*/false);
2691 }
2692}
2693
James Dennettf6333ac2012-06-22 05:46:07 +00002694/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002695///
2696void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2697 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002698
Chris Lattnerf64b3522008-03-09 01:54:53 +00002699 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002700 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002701
Chris Lattnerf64b3522008-03-09 01:54:53 +00002702 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002703 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002704 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002705 Diag(EndifToken, diag::err_pp_endif_without_if);
2706 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002707 }
Mike Stump11289f42009-09-09 15:08:12 +00002708
Chris Lattnerf64b3522008-03-09 01:54:53 +00002709 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002710 if (CurPPLexer->getConditionalStackDepth() == 0)
2711 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002712
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002713 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002714 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002715
2716 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002717 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002718}
2719
James Dennettf6333ac2012-06-22 05:46:07 +00002720/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002721///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002722void Preprocessor::HandleElseDirective(Token &Result) {
2723 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002724
Chris Lattnerf64b3522008-03-09 01:54:53 +00002725 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002726 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002727
Chris Lattnerf64b3522008-03-09 01:54:53 +00002728 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002729 if (CurPPLexer->popConditionalLevel(CI)) {
2730 Diag(Result, diag::pp_err_else_without_if);
2731 return;
2732 }
Mike Stump11289f42009-09-09 15:08:12 +00002733
Chris Lattnerf64b3522008-03-09 01:54:53 +00002734 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002735 if (CurPPLexer->getConditionalStackDepth() == 0)
2736 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002737
2738 // If this is a #else with a #else before it, report the error.
2739 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002740
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002741 if (Callbacks)
2742 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2743
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002744 // Finally, skip the rest of the contents of this block.
2745 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002746 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002747}
2748
James Dennettf6333ac2012-06-22 05:46:07 +00002749/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002750///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002751void Preprocessor::HandleElifDirective(Token &ElifToken) {
2752 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002753
Chris Lattnerf64b3522008-03-09 01:54:53 +00002754 // #elif directive in a non-skipping conditional... start skipping.
2755 // We don't care what the condition is, because we will always skip it (since
2756 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002757 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002758 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002759 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002760
2761 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002762 if (CurPPLexer->popConditionalLevel(CI)) {
2763 Diag(ElifToken, diag::pp_err_elif_without_if);
2764 return;
2765 }
Mike Stump11289f42009-09-09 15:08:12 +00002766
Chris Lattnerf64b3522008-03-09 01:54:53 +00002767 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002768 if (CurPPLexer->getConditionalStackDepth() == 0)
2769 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002770
Chris Lattnerf64b3522008-03-09 01:54:53 +00002771 // If this is a #elif with a #else before it, report the error.
2772 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Taewook Oh755e4d22016-06-13 21:55:33 +00002773
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002774 if (Callbacks)
2775 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002776 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002777 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002778
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002779 // Finally, skip the rest of the contents of this block.
2780 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002781 /*FoundElse*/CI.FoundElse,
2782 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002783}