blob: 84c13b286e689329e1c9b74c493041ac85271165 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerf64b3522008-03-09 01:54:53 +00006//
7//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00008///
9/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010/// Implements # directive processing for the Preprocessor.
James Dennettf6333ac2012-06-22 05:46:07 +000011///
Chris Lattnerf64b3522008-03-09 01:54:53 +000012//===----------------------------------------------------------------------===//
13
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000014#include "clang/Basic/CharInfo.h"
Chris Lattner710bb872009-11-30 04:18:44 +000015#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000016#include "clang/Basic/IdentifierTable.h"
17#include "clang/Basic/LangOptions.h"
18#include "clang/Basic/Module.h"
19#include "clang/Basic/SourceLocation.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000020#include "clang/Basic/SourceManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000021#include "clang/Basic/TokenKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Lex/CodeCompletionHandler.h"
23#include "clang/Lex/HeaderSearch.h"
24#include "clang/Lex/LexDiagnostic.h"
25#include "clang/Lex/LiteralSupport.h"
26#include "clang/Lex/MacroInfo.h"
27#include "clang/Lex/ModuleLoader.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000028#include "clang/Lex/ModuleMap.h"
29#include "clang/Lex/PPCallbacks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/Pragma.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000031#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +000032#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/Lex/Token.h"
Faisal Vali6bf67912017-07-25 03:15:36 +000034#include "clang/Lex/VariadicMacroSupport.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000035#include "llvm/ADT/ArrayRef.h"
Ilya Biryukovb455fc42019-08-01 09:10:37 +000036#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000037#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/SmallVector.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000039#include "llvm/ADT/STLExtras.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000040#include "llvm/ADT/StringSwitch.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000041#include "llvm/ADT/StringRef.h"
42#include "llvm/Support/AlignOf.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000043#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaf6002232014-08-08 21:31:04 +000044#include "llvm/Support/Path.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include <algorithm>
46#include <cassert>
47#include <cstring>
48#include <new>
49#include <string>
50#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000051
Chris Lattnerf64b3522008-03-09 01:54:53 +000052using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Utility Methods for Preprocessor Directive Handling.
56//===----------------------------------------------------------------------===//
57
Richard Smith3f6dd7a2017-05-12 23:40:52 +000058MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
59 auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead};
Ted Kremenekc8456f82010-10-19 22:15:20 +000060 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000061 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000062}
63
Richard Smith50474bf2015-04-23 23:29:05 +000064DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
65 SourceLocation Loc) {
Richard Smith713369b2015-04-23 20:40:50 +000066 return new (BP) DefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000067}
68
69UndefMacroDirective *
Richard Smith50474bf2015-04-23 23:29:05 +000070Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
Richard Smith713369b2015-04-23 20:40:50 +000071 return new (BP) UndefMacroDirective(UndefLoc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000072}
73
74VisibilityMacroDirective *
75Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
76 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000077 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000078}
Chandler Carruthd92d70b2019-01-19 06:36:00 +000079
80/// Read and discard all tokens remaining on the current line until
81/// the tok::eod token is found.
82SourceRange Preprocessor::DiscardUntilEndOfDirective() {
83 Token Tmp;
84 SourceRange Res;
85
86 LexUnexpandedToken(Tmp);
87 Res.setBegin(Tmp.getLocation());
88 while (Tmp.isNot(tok::eod)) {
89 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
90 LexUnexpandedToken(Tmp);
91 }
92 Res.setEnd(Tmp.getLocation());
93 return Res;
94}
95
96/// Enumerates possible cases of #define/#undef a reserved identifier.
Serge Pavlov07c0f042014-12-18 11:14:21 +000097enum MacroDiag {
98 MD_NoWarn, //> Not a reserved identifier
99 MD_KeywordDef, //> Macro hides keyword, enabled by default
100 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
101};
102
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000103/// Checks if the specified identifier is reserved in the specified
Serge Pavlov07c0f042014-12-18 11:14:21 +0000104/// language.
105/// This function does not check if the identifier is a keyword.
106static bool isReservedId(StringRef Text, const LangOptions &Lang) {
107 // C++ [macro.names], C11 7.1.3:
108 // All identifiers that begin with an underscore and either an uppercase
109 // letter or another underscore are always reserved for any use.
110 if (Text.size() >= 2 && Text[0] == '_' &&
111 (isUppercase(Text[1]) || Text[1] == '_'))
112 return true;
113 // C++ [global.names]
114 // Each name that contains a double underscore ... is reserved to the
115 // implementation for any use.
116 if (Lang.CPlusPlus) {
117 if (Text.find("__") != StringRef::npos)
118 return true;
119 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000120 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000121}
122
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +0000123// The -fmodule-name option tells the compiler to textually include headers in
124// the specified module, meaning clang won't build the specified module. This is
125// useful in a number of situations, for instance, when building a library that
126// vends a module map, one might want to avoid hitting intermediate build
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000127// products containimg the the module map or avoid finding the system installed
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +0000128// modulemap for that library.
129static bool isForModuleBuilding(Module *M, StringRef CurrentModule,
130 StringRef ModuleName) {
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +0000131 StringRef TopLevelName = M->getTopLevelModuleName();
132
133 // When building framework Foo, we wanna make sure that Foo *and* Foo_Private
134 // are textually included and no modules are built for both.
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +0000135 if (M->getTopLevelModule()->IsFramework && CurrentModule == ModuleName &&
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +0000136 !CurrentModule.endswith("_Private") && TopLevelName.endswith("_Private"))
137 TopLevelName = TopLevelName.drop_back(8);
138
139 return TopLevelName == CurrentModule;
140}
141
Serge Pavlov07c0f042014-12-18 11:14:21 +0000142static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
143 const LangOptions &Lang = PP.getLangOpts();
144 StringRef Text = II->getName();
145 if (isReservedId(Text, Lang))
146 return MD_ReservedMacro;
147 if (II->isKeyword(Lang))
148 return MD_KeywordDef;
149 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
150 return MD_KeywordDef;
151 return MD_NoWarn;
152}
153
154static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
155 const LangOptions &Lang = PP.getLangOpts();
156 StringRef Text = II->getName();
157 // Do not warn on keyword undef. It is generally harmless and widely used.
158 if (isReservedId(Text, Lang))
159 return MD_ReservedMacro;
160 return MD_NoWarn;
161}
162
Taewook Ohf42103c2016-06-13 20:40:21 +0000163// Return true if we want to issue a diagnostic by default if we
164// encounter this name in a #include with the wrong case. For now,
165// this includes the standard C and C++ headers, Posix headers,
166// and Boost headers. Improper case for these #includes is a
167// potential portability issue.
168static bool warnByDefaultOnWrongCase(StringRef Include) {
169 // If the first component of the path is "boost", treat this like a standard header
170 // for the purposes of diagnostics.
171 if (::llvm::sys::path::begin(Include)->equals_lower("boost"))
172 return true;
173
174 // "condition_variable" is the longest standard header name at 18 characters.
175 // If the include file name is longer than that, it can't be a standard header.
Taewook Oh755e4d22016-06-13 21:55:33 +0000176 static const size_t MaxStdHeaderNameLen = 18u;
Taewook Ohf42103c2016-06-13 20:40:21 +0000177 if (Include.size() > MaxStdHeaderNameLen)
178 return false;
179
180 // Lowercase and normalize the search string.
181 SmallString<32> LowerInclude{Include};
182 for (char &Ch : LowerInclude) {
183 // In the ASCII range?
George Burgess IV5d3bd932016-06-16 02:30:33 +0000184 if (static_cast<unsigned char>(Ch) > 0x7f)
Taewook Ohf42103c2016-06-13 20:40:21 +0000185 return false; // Can't be a standard header
186 // ASCII lowercase:
187 if (Ch >= 'A' && Ch <= 'Z')
188 Ch += 'a' - 'A';
189 // Normalize path separators for comparison purposes.
190 else if (::llvm::sys::path::is_separator(Ch))
191 Ch = '/';
192 }
193
194 // The standard C/C++ and Posix headers
195 return llvm::StringSwitch<bool>(LowerInclude)
196 // C library headers
197 .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
198 .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
199 .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
200 .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
201 .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
202 .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
203
204 // C++ headers for C library facilities
205 .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
206 .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
207 .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
208 .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
209 .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
210 .Case("cwctype", true)
211
212 // C++ library headers
213 .Cases("algorithm", "fstream", "list", "regex", "thread", true)
214 .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
215 .Cases("atomic", "future", "map", "set", "type_traits", true)
216 .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
217 .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
218 .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
219 .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
220 .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
221 .Cases("deque", "istream", "queue", "string", "valarray", true)
222 .Cases("exception", "iterator", "random", "strstream", "vector", true)
223 .Cases("forward_list", "limits", "ratio", "system_error", true)
224
225 // POSIX headers (which aren't also C headers)
226 .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
227 .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
228 .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
229 .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
230 .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
231 .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
232 .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
233 .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
234 .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
235 .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
236 .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
237 .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
238 .Default(false);
239}
240
Serge Pavlov07c0f042014-12-18 11:14:21 +0000241bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
242 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000243 // Missing macro name?
244 if (MacroNameTok.is(tok::eod))
245 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
246
247 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Olivier Goffart90f981b2017-07-14 09:23:40 +0000248 if (!II)
249 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000250
Olivier Goffart90f981b2017-07-14 09:23:40 +0000251 if (II->isCPlusPlusOperatorKeyword()) {
Alp Tokere03e9e12014-05-31 16:32:22 +0000252 // C++ 2.5p2: Alternative tokens behave the same as its primary token
253 // except for their spellings.
254 Diag(MacroNameTok, getLangOpts().MicrosoftExt
255 ? diag::ext_pp_operator_used_as_macro_name
256 : diag::err_pp_operator_used_as_macro_name)
257 << II << MacroNameTok.getKind();
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000258 // Allow #defining |and| and friends for Microsoft compatibility or
259 // recovery when legacy C headers are included in C++.
Alp Tokerb05e0b52014-05-21 06:13:51 +0000260 }
261
Serge Pavlovd024f522014-10-24 17:31:32 +0000262 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000263 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
264 return Diag(MacroNameTok, diag::err_defined_macro_name);
265 }
266
Richard Smith20e883e2015-04-29 23:20:19 +0000267 if (isDefineUndef == MU_Undef) {
268 auto *MI = getMacroInfo(II);
269 if (MI && MI->isBuiltinMacro()) {
270 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
271 // and C++ [cpp.predefined]p4], but allow it as an extension.
272 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
273 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000274 }
275
Serge Pavlov07c0f042014-12-18 11:14:21 +0000276 // If defining/undefining reserved identifier or a keyword, we need to issue
277 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000278 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000279 if (ShadowFlag)
280 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000281 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
Mehdi Amini99d1b292016-10-01 16:38:28 +0000282 (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000283 MacroDiag D = MD_NoWarn;
284 if (isDefineUndef == MU_Define) {
285 D = shouldWarnOnMacroDef(*this, II);
286 }
287 else if (isDefineUndef == MU_Undef)
288 D = shouldWarnOnMacroUndef(*this, II);
289 if (D == MD_KeywordDef) {
290 // We do not want to warn on some patterns widely used in configuration
291 // scripts. This requires analyzing next tokens, so do not issue warnings
292 // now, only inform caller.
293 if (ShadowFlag)
294 *ShadowFlag = true;
295 }
296 if (D == MD_ReservedMacro)
297 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000298 }
299
Alp Tokerb05e0b52014-05-21 06:13:51 +0000300 // Okay, we got a good identifier.
301 return false;
302}
303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000304/// Lex and validate a macro name, which occurs after a
James Dennettf6333ac2012-06-22 05:46:07 +0000305/// \#define or \#undef.
306///
Serge Pavlovd024f522014-10-24 17:31:32 +0000307/// This sets the token kind to eod and discards the rest of the macro line if
308/// the macro name is invalid.
309///
310/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000311/// \param isDefineUndef Context in which macro is used.
312/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
313void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
314 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000315 // Read the token, don't allow macro expansion on it.
316 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000317
Douglas Gregor12785102010-08-24 20:21:13 +0000318 if (MacroNameTok.is(tok::code_completion)) {
319 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000320 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000321 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000322 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000323 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000324
Serge Pavlov07c0f042014-12-18 11:14:21 +0000325 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000326 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000327
328 // Invalid macro name, read and discard the rest of the line and set the
329 // token kind to tok::eod if necessary.
330 if (MacroNameTok.isNot(tok::eod)) {
331 MacroNameTok.setKind(tok::eod);
332 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000333 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000334}
335
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000336/// Ensure that the next token is a tok::eod token.
James Dennettf6333ac2012-06-22 05:46:07 +0000337///
338/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000339/// true, then we consider macros that expand to zero tokens as being ok.
Richard Smith8af8b862019-04-11 21:18:23 +0000340///
341/// Returns the location of the end of the directive.
342SourceLocation Preprocessor::CheckEndOfDirective(const char *DirType,
343 bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000344 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000345 // Lex unexpanded tokens for most directives: macros might expand to zero
346 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
347 // #line) allow empty macros.
348 if (EnableMacros)
349 Lex(Tmp);
350 else
351 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000352
Chris Lattnerf64b3522008-03-09 01:54:53 +0000353 // There should be no tokens after the directive, but we allow them as an
354 // extension.
355 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
356 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000357
Richard Smith8af8b862019-04-11 21:18:23 +0000358 if (Tmp.is(tok::eod))
359 return Tmp.getLocation();
360
361 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
362 // or if this is a macro-style preprocessing directive, because it is more
363 // trouble than it is worth to insert /**/ and check that there is no /**/
364 // in the range also.
365 FixItHint Hint;
366 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
367 !CurTokenLexer)
368 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
369 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
370 return DiscardUntilEndOfDirective().getEnd();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000371}
372
Alex Lorenzca6e6092019-09-11 20:40:31 +0000373Optional<unsigned> Preprocessor::getSkippedRangeForExcludedConditionalBlock(
374 SourceLocation HashLoc) {
375 if (!ExcludedConditionalDirectiveSkipMappings)
376 return None;
377 if (!HashLoc.isFileID())
378 return None;
379
380 std::pair<FileID, unsigned> HashFileOffset =
381 SourceMgr.getDecomposedLoc(HashLoc);
382 const llvm::MemoryBuffer *Buf = SourceMgr.getBuffer(HashFileOffset.first);
383 auto It = ExcludedConditionalDirectiveSkipMappings->find(Buf);
384 if (It == ExcludedConditionalDirectiveSkipMappings->end())
385 return None;
386
387 const PreprocessorSkippedRangeMapping &SkippedRanges = *It->getSecond();
388 // Check if the offset of '#' is mapped in the skipped ranges.
389 auto MappingIt = SkippedRanges.find(HashFileOffset.second);
390 if (MappingIt == SkippedRanges.end())
391 return None;
392
393 unsigned BytesToSkip = MappingIt->getSecond();
394 unsigned CurLexerBufferOffset = CurLexer->getCurrentBufferOffset();
395 assert(CurLexerBufferOffset >= HashFileOffset.second &&
396 "lexer is before the hash?");
397 // Take into account the fact that the lexer has already advanced, so the
398 // number of bytes to skip must be adjusted.
399 unsigned LengthDiff = CurLexerBufferOffset - HashFileOffset.second;
400 assert(BytesToSkip >= LengthDiff && "lexer is after the skipped range?");
401 return BytesToSkip - LengthDiff;
402}
403
James Dennettf6333ac2012-06-22 05:46:07 +0000404/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
405/// decided that the subsequent tokens are in the \#if'd out portion of the
406/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000407/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000408/// this \#if directive, so \#else/\#elif blocks should never be entered.
409/// If ElseOk is true, then \#else directives are ok, if not, then we have
410/// already seen one so a \#else directive is a duplicate. When this returns,
411/// the caller can lex the first valid token.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000412void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
Vedant Kumar3919a502017-09-11 20:47:42 +0000413 SourceLocation IfTokenLoc,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000414 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000415 bool FoundElse,
416 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000417 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000418 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000419
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000420 if (PreambleConditionalStack.reachedEOFWhileSkipping())
421 PreambleConditionalStack.clearSkipInfo();
422 else
423 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
424 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000425
Chris Lattnerf64b3522008-03-09 01:54:53 +0000426 // Enter raw mode to disable identifier lookup (and thus macro expansion),
427 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000428 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000429 Token Tok;
Alex Lorenzca6e6092019-09-11 20:40:31 +0000430 if (auto SkipLength =
431 getSkippedRangeForExcludedConditionalBlock(HashTokenLoc)) {
432 // Skip to the next '#endif' / '#else' / '#elif'.
433 CurLexer->skipOver(*SkipLength);
434 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000435 while (true) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000436 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000437
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000438 if (Tok.is(tok::code_completion)) {
439 if (CodeComplete)
440 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000441 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000442 continue;
443 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000444
Chris Lattnerf64b3522008-03-09 01:54:53 +0000445 // If this is the end of the buffer, we have an error.
446 if (Tok.is(tok::eof)) {
Ilya Biryukov8f738ac2017-09-12 08:35:57 +0000447 // We don't emit errors for unterminated conditionals here,
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000448 // Lexer::LexEndOfFile can do that properly.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000449 // Just return and let the caller lex after this #include.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000450 if (PreambleConditionalStack.isRecording())
451 PreambleConditionalStack.SkipInfo.emplace(
452 HashTokenLoc, IfTokenLoc, FoundNonSkipPortion, FoundElse, ElseLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000453 break;
454 }
Mike Stump11289f42009-09-09 15:08:12 +0000455
Chris Lattnerf64b3522008-03-09 01:54:53 +0000456 // If this token is not a preprocessor directive, just skip it.
457 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
458 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000459
Chris Lattnerf64b3522008-03-09 01:54:53 +0000460 // We just parsed a # character at the start of a line, so we're in
461 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000462 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000463 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000464 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000465
Mike Stump11289f42009-09-09 15:08:12 +0000466
Chris Lattnerf64b3522008-03-09 01:54:53 +0000467 // Read the next token, the directive flavor.
468 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000469
Chris Lattnerf64b3522008-03-09 01:54:53 +0000470 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
471 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000472 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000473 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000474 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000475 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000476 continue;
477 }
478
479 // If the first letter isn't i or e, it isn't intesting to us. We know that
480 // this is safe in the face of spelling differences, because there is no way
481 // to spell an i/e in a strange way that is another letter. Skipping this
482 // allows us to avoid looking up the identifier info for #define/#undef and
483 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000484 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000485
Alp Toker2d57cea2014-05-17 04:53:25 +0000486 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000487 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000488 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000489 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000490 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000491 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000492 continue;
493 }
Mike Stump11289f42009-09-09 15:08:12 +0000494
Chris Lattnerf64b3522008-03-09 01:54:53 +0000495 // Get the identifier name without trigraphs or embedded newlines. Note
496 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
497 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000498 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000499 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000500 if (!Tok.needsCleaning() && RI.size() < 20) {
501 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000502 } else {
503 std::string DirectiveStr = getSpelling(Tok);
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000504 size_t IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000505 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000506 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000507 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000508 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000509 continue;
510 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000511 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000512 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000513 }
Mike Stump11289f42009-09-09 15:08:12 +0000514
Benjamin Kramer144884642009-12-31 13:32:38 +0000515 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000516 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000517 if (Sub.empty() || // "if"
518 Sub == "def" || // "ifdef"
519 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000520 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
521 // bother parsing the condition.
522 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000523 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000524 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000525 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000526 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000527 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000528 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000529 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000530 PPConditionalInfo CondInfo;
531 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000532 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000533 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000534 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000535
Chris Lattnerf64b3522008-03-09 01:54:53 +0000536 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000537 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000538 // Restore the value of LexingRawMode so that trailing comments
539 // are handled correctly, if we've reached the outermost block.
540 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000541 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000542 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000543 if (Callbacks)
544 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000545 break;
Richard Smithd0124572012-06-21 00:35:03 +0000546 } else {
547 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000548 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000549 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000550 // #else directive in a skipping conditional. If not in some other
551 // skipping conditional, and if #else hasn't already been seen, enter it
552 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000553 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattnerf64b3522008-03-09 01:54:53 +0000555 // If this is a #else with a #else before it, report the error.
556 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000557
Chris Lattnerf64b3522008-03-09 01:54:53 +0000558 // Note that we've seen a #else in this conditional.
559 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000560
Chris Lattnerf64b3522008-03-09 01:54:53 +0000561 // If the conditional is at the top level, and the #if block wasn't
562 // entered, enter the #else block now.
563 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
564 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000565 // Restore the value of LexingRawMode so that trailing comments
566 // are handled correctly.
567 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000568 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000569 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000570 if (Callbacks)
571 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000572 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000573 } else {
574 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000575 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000576 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000577 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000578
John Thompson17c35732013-12-04 20:19:30 +0000579 // If this is a #elif with a #else before it, report the error.
580 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
581
Chris Lattnerf64b3522008-03-09 01:54:53 +0000582 // If this is in a skipping block or if we're already handled this #if
583 // block, don't bother parsing the condition.
Chandler Carruthd92d70b2019-01-19 06:36:00 +0000584 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
585 DiscardUntilEndOfDirective();
586 } else {
587 // Restore the value of LexingRawMode so that identifiers are
588 // looked up, etc, inside the #elif expression.
589 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
590 CurPPLexer->LexingRawMode = false;
591 IdentifierInfo *IfNDefMacro = nullptr;
592 DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
593 const bool CondValue = DER.Conditional;
594 CurPPLexer->LexingRawMode = true;
595 if (Callbacks) {
596 Callbacks->Elif(
597 Tok.getLocation(), DER.ExprRange,
598 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
599 CondInfo.IfLoc);
600 }
601 // If this condition is true, enter it!
602 if (CondValue) {
John Thompson17c35732013-12-04 20:19:30 +0000603 CondInfo.FoundNonSkip = true;
604 break;
605 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000606 }
607 }
608 }
Mike Stump11289f42009-09-09 15:08:12 +0000609
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000610 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000611 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000612 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000613 }
614
615 // Finally, if we are out of the conditional (saw an #endif or ran off the end
616 // of the file, just stop skipping and return to lexing whatever came after
617 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000618 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000619
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000620 // The last skipped range isn't actually skipped yet if it's truncated
621 // by the end of the preamble; we'll resume parsing after the preamble.
622 if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
Vedant Kumar3919a502017-09-11 20:47:42 +0000623 Callbacks->SourceRangeSkipped(
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000624 SourceRange(HashTokenLoc, CurPPLexer->getSourceLocation()),
Vedant Kumar3919a502017-09-11 20:47:42 +0000625 Tok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000626}
627
Richard Smith2a553082015-04-23 22:58:06 +0000628Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000629 if (!SourceMgr.isInMainFile(Loc)) {
630 // Try to determine the module of the include directive.
631 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
632 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
633 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
634 // The include comes from an included file.
635 return HeaderInfo.getModuleMap()
636 .findModuleForHeader(EntryOfIncl)
637 .getModule();
638 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000639 }
Richard Smith7e82e012016-02-19 22:25:36 +0000640
641 // This is either in the main file or not in a file at all. It belongs
642 // to the current module, if there is one.
643 return getLangOpts().CurrentModule.empty()
644 ? nullptr
645 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000646}
647
Richard Smith4eb83932016-04-27 21:57:05 +0000648const FileEntry *
Richard Smith0a088ea2020-04-28 18:22:34 -0700649Preprocessor::getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
650 SourceLocation Loc) {
Richard Smith4eb83932016-04-27 21:57:05 +0000651 Module *IncM = getModuleForLocation(IncLoc);
652
653 // Walk up through the include stack, looking through textual headers of M
654 // until we hit a non-textual header that we can #include. (We assume textual
655 // headers of a module with non-textual headers aren't meant to be used to
656 // import entities from the module.)
657 auto &SM = getSourceManager();
658 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
659 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
660 auto *FE = SM.getFileEntryForID(ID);
Richard Smith040e1262017-06-02 01:55:39 +0000661 if (!FE)
662 break;
Richard Smith4eb83932016-04-27 21:57:05 +0000663
Richard Smith0a088ea2020-04-28 18:22:34 -0700664 // We want to find all possible modules that might contain this header, so
665 // search all enclosing directories for module maps and load them.
666 HeaderInfo.hasModuleMap(FE->getName(), /*Root*/ nullptr,
667 SourceMgr.isInSystemHeader(Loc));
Richard Smithe867e982019-04-18 00:56:58 +0000668
Richard Smith0a088ea2020-04-28 18:22:34 -0700669 bool InPrivateHeader = false;
670 for (auto Header : HeaderInfo.findAllModulesForHeader(FE)) {
671 if (!Header.isAccessibleFrom(IncM)) {
Richard Smith4eb83932016-04-27 21:57:05 +0000672 // It's in a private header; we can't #include it.
673 // FIXME: If there's a public header in some module that re-exports it,
674 // then we could suggest including that, but it's not clear that's the
675 // expected way to make this entity visible.
Richard Smith0a088ea2020-04-28 18:22:34 -0700676 InPrivateHeader = true;
Richard Smith4eb83932016-04-27 21:57:05 +0000677 continue;
678 }
679
Richard Smith0a088ea2020-04-28 18:22:34 -0700680 // We'll suggest including textual headers below if they're
681 // include-guarded.
682 if (Header.getRole() & ModuleMap::TextualHeader)
683 continue;
684
685 // If we have a module import syntax, we shouldn't include a header to
686 // make a particular module visible. Let the caller know they should
687 // suggest an import instead.
688 if (getLangOpts().ObjC || getLangOpts().CPlusPlusModules ||
689 getLangOpts().ModulesTS)
690 return nullptr;
691
692 // If this is an accessible, non-textual header of M's top-level module
693 // that transitively includes the given location and makes the
694 // corresponding module visible, this is the thing to #include.
695 return FE;
Richard Smith4eb83932016-04-27 21:57:05 +0000696 }
697
Richard Smith0a088ea2020-04-28 18:22:34 -0700698 // FIXME: If we're bailing out due to a private header, we shouldn't suggest
699 // an import either.
700 if (InPrivateHeader)
701 return nullptr;
702
703 // If the header is includable and has an include guard, assume the
704 // intended way to expose its contents is by #include, not by importing a
705 // module that transitively includes it.
706 if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE))
707 return FE;
Richard Smith4eb83932016-04-27 21:57:05 +0000708
709 Loc = SM.getIncludeLoc(ID);
710 }
711
712 return nullptr;
713}
714
Alex Lorenz4dc55732019-08-22 18:15:50 +0000715Optional<FileEntryRef> Preprocessor::LookupFile(
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000716 SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
717 const DirectoryLookup *FromDir, const FileEntry *FromFile,
718 const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000719 SmallVectorImpl<char> *RelativePath,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000720 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
721 bool *IsFrameworkFound, bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000722 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000723 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000724
Will Wilson0fafd342013-12-27 19:46:16 +0000725 // If the header lookup mechanism may be relative to the current inclusion
726 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000727 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
728 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000729 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000730 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000731 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000732 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000733
Chris Lattner022923a2009-02-04 19:45:07 +0000734 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000735 // predefines buffer or the module includes buffer. Any other file is not
736 // lexed with a normal lexer, so it won't be scanned for preprocessor
737 // directives.
738 //
739 // If we have the predefines buffer, resolve #include references (which come
740 // from the -include command line argument) from the current working
741 // directory instead of relative to the main file.
742 //
743 // If we have the module includes buffer, resolve #include references (which
744 // come from header declarations in the module map) relative to the module
745 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000746 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000747 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000748 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000749 BuildSystemModule = getCurrentModule()->IsSystem;
750 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000751 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Harlan Haskins8d323d12019-08-01 21:31:56 +0000752 Includers.push_back(std::make_pair(FileEnt, *FileMgr.getDirectory(".")));
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000753 } else {
754 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
755 }
Will Wilson0fafd342013-12-27 19:46:16 +0000756
757 // MSVC searches the current include stack from top to bottom for
758 // headers included by quoted include directives.
759 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000760 if (LangOpts.MSVCCompat && !isAngled) {
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000761 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000762 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000763 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000764 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000765 }
Chris Lattner022923a2009-02-04 19:45:07 +0000766 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000767 }
Mike Stump11289f42009-09-09 15:08:12 +0000768
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000769 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000770
771 if (FromFile) {
772 // We're supposed to start looking from after a particular file. Search
773 // the include path until we find that file or run out of files.
774 const DirectoryLookup *TmpCurDir = CurDir;
775 const DirectoryLookup *TmpFromDir = nullptr;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000776 while (Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +0000777 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000778 Includers, SearchPath, RelativePath, RequestingModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000779 SuggestedModule, /*IsMapped=*/nullptr,
780 /*IsFrameworkFound=*/nullptr, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000781 // Keep looking as if this file did a #include_next.
782 TmpFromDir = TmpCurDir;
783 ++TmpFromDir;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000784 if (&FE->getFileEntry() == FromFile) {
Richard Smith25d50752014-10-20 00:15:49 +0000785 // Found it.
786 FromDir = TmpFromDir;
787 CurDir = TmpCurDir;
788 break;
789 }
790 }
791 }
792
793 // Do a standard file entry lookup.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000794 Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000795 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000796 RelativePath, RequestingModule, SuggestedModule, IsMapped,
797 IsFrameworkFound, SkipCache, BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000798 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000799 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000800 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000801 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
Alex Lorenz4dc55732019-08-22 18:15:50 +0000802 Filename, &FE->getFileEntry());
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000803 return FE;
804 }
Mike Stump11289f42009-09-09 15:08:12 +0000805
Will Wilson0fafd342013-12-27 19:46:16 +0000806 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000807 // Otherwise, see if this is a subframework header. If so, this is relative
808 // to one of the headers on the #include stack. Walk the list of the current
809 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000810 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000811 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000812 if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
813 Filename, CurFileEnt, SearchPath, RelativePath, RequestingModule,
814 SuggestedModule)) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000815 if (SuggestedModule && !LangOpts.AsmPreprocessor)
816 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000817 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
Alex Lorenz4dc55732019-08-22 18:15:50 +0000818 Filename, &FE->getFileEntry());
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000819 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000820 }
821 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000822 }
Mike Stump11289f42009-09-09 15:08:12 +0000823
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000824 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000825 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000826 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000827 if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000828 Filename, CurFileEnt, SearchPath, RelativePath,
Alex Lorenz4dc55732019-08-22 18:15:50 +0000829 RequestingModule, SuggestedModule)) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000830 if (SuggestedModule && !LangOpts.AsmPreprocessor)
831 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000832 RequestingModule, RequestingModuleIsModuleInterface,
Alex Lorenz4dc55732019-08-22 18:15:50 +0000833 FilenameLoc, Filename, &FE->getFileEntry());
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000834 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000835 }
836 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000837 }
838 }
Mike Stump11289f42009-09-09 15:08:12 +0000839
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000840 // Otherwise, we really couldn't find the file.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000841 return None;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000842}
843
Chris Lattnerf64b3522008-03-09 01:54:53 +0000844//===----------------------------------------------------------------------===//
845// Preprocessor Directive Handling.
846//===----------------------------------------------------------------------===//
847
David Blaikied5321242012-06-06 18:52:13 +0000848class Preprocessor::ResetMacroExpansionHelper {
849public:
850 ResetMacroExpansionHelper(Preprocessor *pp)
851 : PP(pp), save(pp->DisableMacroExpansion) {
852 if (pp->MacroExpansionInDirectivesOverride)
853 pp->DisableMacroExpansion = false;
854 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000855
David Blaikied5321242012-06-06 18:52:13 +0000856 ~ResetMacroExpansionHelper() {
857 PP->DisableMacroExpansion = save;
858 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000859
David Blaikied5321242012-06-06 18:52:13 +0000860private:
861 Preprocessor *PP;
862 bool save;
863};
864
Mike Rice58df1af2018-09-11 17:10:44 +0000865/// Process a directive while looking for the through header or a #pragma
866/// hdrstop. The following directives are handled:
867/// #include (to check if it is the through header)
868/// #define (to warn about macros that don't match the PCH)
869/// #pragma (to check for pragma hdrstop).
870/// All other directives are completely discarded.
871void Preprocessor::HandleSkippedDirectiveWhileUsingPCH(Token &Result,
Erich Keane76675de2018-07-05 17:22:13 +0000872 SourceLocation HashLoc) {
873 if (const IdentifierInfo *II = Result.getIdentifierInfo()) {
Mike Rice58df1af2018-09-11 17:10:44 +0000874 if (II->getPPKeywordID() == tok::pp_define) {
Erich Keane76675de2018-07-05 17:22:13 +0000875 return HandleDefineDirective(Result,
876 /*ImmediatelyAfterHeaderGuard=*/false);
Mike Rice58df1af2018-09-11 17:10:44 +0000877 }
878 if (SkippingUntilPCHThroughHeader &&
879 II->getPPKeywordID() == tok::pp_include) {
880 return HandleIncludeDirective(HashLoc, Result);
881 }
882 if (SkippingUntilPragmaHdrStop && II->getPPKeywordID() == tok::pp_pragma) {
Richard Smith75f96812019-04-11 21:18:22 +0000883 Lex(Result);
884 auto *II = Result.getIdentifierInfo();
Mike Rice58df1af2018-09-11 17:10:44 +0000885 if (II && II->getName() == "hdrstop")
Richard Smith75f96812019-04-11 21:18:22 +0000886 return HandlePragmaHdrstop(Result);
Mike Rice58df1af2018-09-11 17:10:44 +0000887 }
Erich Keane76675de2018-07-05 17:22:13 +0000888 }
889 DiscardUntilEndOfDirective();
890}
891
Chris Lattnerf64b3522008-03-09 01:54:53 +0000892/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000893/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000894/// lexer/preprocessor state, and advances the lexer(s) so that the next token
895/// read is the correct one.
896void Preprocessor::HandleDirective(Token &Result) {
897 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000898
Chris Lattnerf64b3522008-03-09 01:54:53 +0000899 // We just parsed a # character at the start of a line, so we're in directive
900 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000901 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000902 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000903 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000904
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000905 bool ImmediatelyAfterTopLevelIfndef =
906 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
907 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
908
Chris Lattnerf64b3522008-03-09 01:54:53 +0000909 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000910
Chris Lattnerf64b3522008-03-09 01:54:53 +0000911 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000912 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000913 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000914 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000915
Chris Lattner2d17ab72009-03-18 21:00:25 +0000916 // Save the '#' token in case we need to return it later.
917 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000918
Chris Lattnerf64b3522008-03-09 01:54:53 +0000919 // Read the next token, the directive flavor. This isn't expanded due to
920 // C99 6.10.3p8.
921 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000922
Chris Lattnerf64b3522008-03-09 01:54:53 +0000923 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
924 // #define A(x) #x
925 // A(abc
926 // #warning blah
927 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000928 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
929 // not support this for #include-like directives, since that can result in
930 // terrible diagnostics, and does not work in GCC.
931 if (InMacroArgs) {
932 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
933 switch (II->getPPKeywordID()) {
934 case tok::pp_include:
935 case tok::pp_import:
936 case tok::pp_include_next:
937 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000938 case tok::pp_pragma:
939 Diag(Result, diag::err_embedded_directive) << II->getName();
Nico Weber023dd1e2019-02-14 04:13:17 +0000940 Diag(*ArgMacro, diag::note_macro_expansion_here)
941 << ArgMacro->getIdentifierInfo();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000942 DiscardUntilEndOfDirective();
943 return;
944 default:
945 break;
946 }
947 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000948 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000949 }
Mike Stump11289f42009-09-09 15:08:12 +0000950
David Blaikied5321242012-06-06 18:52:13 +0000951 // Temporarily enable macro expansion if set so
952 // and reset to previous state when returning from this function.
953 ResetMacroExpansionHelper helper(this);
954
Mike Rice58df1af2018-09-11 17:10:44 +0000955 if (SkippingUntilPCHThroughHeader || SkippingUntilPragmaHdrStop)
956 return HandleSkippedDirectiveWhileUsingPCH(Result, SavedHash.getLocation());
Erich Keane76675de2018-07-05 17:22:13 +0000957
Chris Lattnerf64b3522008-03-09 01:54:53 +0000958 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000959 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000960 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000961 case tok::code_completion:
962 if (CodeComplete)
963 CodeComplete->CodeCompleteDirective(
964 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000965 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000966 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000967 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000968 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000969 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000970 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000971 default:
972 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000973 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattnerf64b3522008-03-09 01:54:53 +0000975 // Ask what the preprocessor keyword ID is.
976 switch (II->getPPKeywordID()) {
977 default: break;
978 // C99 6.10.1 - Conditional Inclusion.
979 case tok::pp_if:
Vedant Kumar3919a502017-09-11 20:47:42 +0000980 return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000981 case tok::pp_ifdef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000982 return HandleIfdefDirective(Result, SavedHash, false,
983 true /*not valid for miopt*/);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000984 case tok::pp_ifndef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000985 return HandleIfdefDirective(Result, SavedHash, true,
986 ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000987 case tok::pp_elif:
Vedant Kumar3919a502017-09-11 20:47:42 +0000988 return HandleElifDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000989 case tok::pp_else:
Vedant Kumar3919a502017-09-11 20:47:42 +0000990 return HandleElseDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000991 case tok::pp_endif:
992 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000993
Chris Lattnerf64b3522008-03-09 01:54:53 +0000994 // C99 6.10.2 - Source File Inclusion.
995 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000996 // Handle #include.
997 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000998 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000999 // Handle -imacros.
Taewook Oh755e4d22016-06-13 21:55:33 +00001000 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00001001
Chris Lattnerf64b3522008-03-09 01:54:53 +00001002 // C99 6.10.3 - Macro Replacement.
1003 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001004 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001005 case tok::pp_undef:
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001006 return HandleUndefDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001007
1008 // C99 6.10.4 - Line Control.
1009 case tok::pp_line:
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001010 return HandleLineDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattnerf64b3522008-03-09 01:54:53 +00001012 // C99 6.10.5 - Error Directive.
1013 case tok::pp_error:
1014 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +00001015
Chris Lattnerf64b3522008-03-09 01:54:53 +00001016 // C99 6.10.6 - Pragma Directive.
1017 case tok::pp_pragma:
Joel E. Dennyddde0ec2019-05-21 23:51:38 +00001018 return HandlePragmaDirective({PIK_HashPragma, SavedHash.getLocation()});
Mike Stump11289f42009-09-09 15:08:12 +00001019
Chris Lattnerf64b3522008-03-09 01:54:53 +00001020 // GNU Extensions.
1021 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001022 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001023 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001024 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00001025
Chris Lattnerf64b3522008-03-09 01:54:53 +00001026 case tok::pp_warning:
1027 Diag(Result, diag::ext_pp_warning_directive);
1028 return HandleUserDiagnosticDirective(Result, true);
1029 case tok::pp_ident:
1030 return HandleIdentSCCSDirective(Result);
1031 case tok::pp_sccs:
1032 return HandleIdentSCCSDirective(Result);
1033 case tok::pp_assert:
1034 //isExtension = true; // FIXME: implement #assert
1035 break;
1036 case tok::pp_unassert:
1037 //isExtension = true; // FIXME: implement #unassert
1038 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001039
Douglas Gregor663b48f2012-01-03 19:48:16 +00001040 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001041 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001042 return HandleMacroPublicDirective(Result);
1043 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001044
Douglas Gregor663b48f2012-01-03 19:48:16 +00001045 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001046 if (getLangOpts().Modules)
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001047 return HandleMacroPrivateDirective();
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001048 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001049 }
1050 break;
1051 }
Mike Stump11289f42009-09-09 15:08:12 +00001052
Chris Lattner2d17ab72009-03-18 21:00:25 +00001053 // If this is a .S file, treat unknown # directives as non-preprocessor
1054 // directives. This is important because # may be a comment or introduce
1055 // various pseudo-ops. Just return the # token and push back the following
1056 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001057 if (getLangOpts().AsmPreprocessor) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001058 auto Toks = std::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001059 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001060 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001061 Toks[1] = Result;
Taewook Oh755e4d22016-06-13 21:55:33 +00001062
Chris Lattner56f64c12011-01-06 05:01:51 +00001063 // If the second token is a hashhash token, then we need to translate it to
1064 // unknown so the token lexer doesn't try to perform token pasting.
1065 if (Result.is(tok::hashhash))
1066 Toks[1].setKind(tok::unknown);
Taewook Oh755e4d22016-06-13 21:55:33 +00001067
Chris Lattner2d17ab72009-03-18 21:00:25 +00001068 // Enter this token stream so that we re-lex the tokens. Make sure to
1069 // enable macro expansion, in case the token after the # is an identifier
1070 // that is expanded.
Ilya Biryukov929af672019-05-17 09:32:05 +00001071 EnterTokenStream(std::move(Toks), 2, false, /*IsReinject*/false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001072 return;
1073 }
Mike Stump11289f42009-09-09 15:08:12 +00001074
Chris Lattnerf64b3522008-03-09 01:54:53 +00001075 // If we reached here, the preprocessing token is not valid!
1076 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001077
Chris Lattnerf64b3522008-03-09 01:54:53 +00001078 // Read the rest of the PP line.
1079 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattnerf64b3522008-03-09 01:54:53 +00001081 // Okay, we're done parsing the directive.
1082}
1083
Chris Lattner76e68962009-01-26 06:19:46 +00001084/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1085/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1086static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001087 unsigned DiagID, Preprocessor &PP,
1088 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001089 if (DigitTok.isNot(tok::numeric_constant)) {
1090 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001091
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001092 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001093 PP.DiscardUntilEndOfDirective();
1094 return true;
1095 }
Mike Stump11289f42009-09-09 15:08:12 +00001096
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001097 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001098 IntegerBuffer.resize(DigitTok.getLength());
1099 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001100 bool Invalid = false;
1101 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1102 if (Invalid)
1103 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001104
Chris Lattnerd66f1722009-04-18 18:35:15 +00001105 // Verify that we have a simple digit-sequence, and compute the value. This
1106 // is always a simple digit string computed in decimal, so we do this manually
1107 // here.
1108 Val = 0;
1109 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001110 // C++1y [lex.fcon]p1:
1111 // Optional separating single quotes in a digit-sequence are ignored
1112 if (DigitTokBegin[i] == '\'')
1113 continue;
1114
Jordan Rosea7d03842013-02-08 22:30:41 +00001115 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001116 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001117 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001118 PP.DiscardUntilEndOfDirective();
1119 return true;
1120 }
Mike Stump11289f42009-09-09 15:08:12 +00001121
Chris Lattnerd66f1722009-04-18 18:35:15 +00001122 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1123 if (NextVal < Val) { // overflow.
1124 PP.Diag(DigitTok, DiagID);
1125 PP.DiscardUntilEndOfDirective();
1126 return true;
1127 }
1128 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001129 }
Mike Stump11289f42009-09-09 15:08:12 +00001130
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001131 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001132 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1133 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001134
Chris Lattner76e68962009-01-26 06:19:46 +00001135 return false;
1136}
1137
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001138/// Handle a \#line directive: C99 6.10.4.
James Dennettf6333ac2012-06-22 05:46:07 +00001139///
1140/// The two acceptable forms are:
1141/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001142/// # line digit-sequence
1143/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001144/// \endverbatim
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001145void Preprocessor::HandleLineDirective() {
Chris Lattner100c65e2009-01-26 05:29:08 +00001146 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1147 // expanded.
1148 Token DigitTok;
1149 Lex(DigitTok);
1150
Chris Lattner100c65e2009-01-26 05:29:08 +00001151 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001152 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001153 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001154 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001155
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001156 if (LineNo == 0)
1157 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001158
Chris Lattner76e68962009-01-26 06:19:46 +00001159 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1160 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001161 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001162 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001163 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001164 if (LineNo >= LineLimit)
1165 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001166 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001167 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001169 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001170 Token StrTok;
1171 Lex(StrTok);
1172
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001173 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1174 // string followed by eod.
1175 if (StrTok.is(tok::eod))
Chandler Carruthd92d70b2019-01-19 06:36:00 +00001176 ; // ok
1177 else if (StrTok.isNot(tok::string_literal)) {
1178 Diag(StrTok, diag::err_pp_line_invalid_filename);
1179 DiscardUntilEndOfDirective();
1180 return;
1181 } else if (StrTok.hasUDSuffix()) {
1182 Diag(StrTok, diag::err_invalid_string_udl);
1183 DiscardUntilEndOfDirective();
1184 return;
1185 } else {
1186 // Parse and validate the string, converting it into a unique ID.
1187 StringLiteralParser Literal(StrTok, *this);
1188 assert(Literal.isAscii() && "Didn't allow wide strings in");
1189 if (Literal.hadError) {
1190 DiscardUntilEndOfDirective();
1191 return;
1192 }
1193 if (Literal.Pascal) {
1194 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1195 DiscardUntilEndOfDirective();
1196 return;
1197 }
1198 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1199
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001200 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001201 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1202 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001203 }
Mike Stump11289f42009-09-09 15:08:12 +00001204
Reid Klecknereb00ee02017-05-22 21:42:58 +00001205 // Take the file kind of the file containing the #line directive. #line
1206 // directives are often used for generated sources from the same codebase, so
1207 // the new file should generally be classified the same way as the current
1208 // file. This is visible in GCC's pre-processed output, which rewrites #line
1209 // to GNU line markers.
1210 SrcMgr::CharacteristicKind FileKind =
1211 SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1212
1213 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1214 false, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001215
Chris Lattner839150e2009-03-27 17:13:49 +00001216 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001217 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Reid Klecknereb00ee02017-05-22 21:42:58 +00001218 PPCallbacks::RenameFile, FileKind);
Chris Lattner100c65e2009-01-26 05:29:08 +00001219}
1220
Chris Lattner76e68962009-01-26 06:19:46 +00001221/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1222/// marker directive.
1223static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
Reid Klecknereb00ee02017-05-22 21:42:58 +00001224 SrcMgr::CharacteristicKind &FileKind,
Chris Lattner76e68962009-01-26 06:19:46 +00001225 Preprocessor &PP) {
1226 unsigned FlagVal;
1227 Token FlagTok;
1228 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001229 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001230 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1231 return true;
1232
1233 if (FlagVal == 1) {
1234 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001235
Chris Lattner76e68962009-01-26 06:19:46 +00001236 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001237 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001238 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1239 return true;
1240 } else if (FlagVal == 2) {
1241 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001242
Chris Lattner1c967782009-02-04 06:25:26 +00001243 SourceManager &SM = PP.getSourceManager();
1244 // If we are leaving the current presumed file, check to make sure the
1245 // presumed include stack isn't empty!
1246 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001247 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001248 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001249 if (PLoc.isInvalid())
1250 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001251
Chris Lattner1c967782009-02-04 06:25:26 +00001252 // If there is no include loc (main file) or if the include loc is in a
1253 // different physical file, then we aren't in a "1" line marker flag region.
1254 SourceLocation IncLoc = PLoc.getIncludeLoc();
1255 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001256 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001257 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1258 PP.DiscardUntilEndOfDirective();
1259 return true;
1260 }
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattner76e68962009-01-26 06:19:46 +00001262 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001263 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001264 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1265 return true;
1266 }
1267
1268 // We must have 3 if there are still flags.
1269 if (FlagVal != 3) {
1270 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001271 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001272 return true;
1273 }
Mike Stump11289f42009-09-09 15:08:12 +00001274
Reid Klecknereb00ee02017-05-22 21:42:58 +00001275 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001276
Chris Lattner76e68962009-01-26 06:19:46 +00001277 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001278 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001279 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001280 return true;
1281
1282 // We must have 4 if there is yet another flag.
1283 if (FlagVal != 4) {
1284 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001285 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001286 return true;
1287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288
Reid Klecknereb00ee02017-05-22 21:42:58 +00001289 FileKind = SrcMgr::C_ExternCSystem;
Mike Stump11289f42009-09-09 15:08:12 +00001290
Chris Lattner76e68962009-01-26 06:19:46 +00001291 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001292 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001293
1294 // There are no more valid flags here.
1295 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001296 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001297 return true;
1298}
1299
1300/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1301/// one of the following forms:
1302///
1303/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001304/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001305/// # 42 "file" ('1' | '2')? '3' '4'?
1306///
1307void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1308 // Validate the number and convert it to an unsigned. GNU does not have a
1309 // line # limit other than it fit in 32-bits.
1310 unsigned LineNo;
1311 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001312 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001313 return;
Mike Stump11289f42009-09-09 15:08:12 +00001314
Chris Lattner76e68962009-01-26 06:19:46 +00001315 Token StrTok;
1316 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001317
Chris Lattner76e68962009-01-26 06:19:46 +00001318 bool IsFileEntry = false, IsFileExit = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001319 int FilenameID = -1;
Reid Klecknereb00ee02017-05-22 21:42:58 +00001320 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001321
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001322 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1323 // string followed by eod.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001324 if (StrTok.is(tok::eod)) {
1325 // Treat this like "#line NN", which doesn't change file characteristics.
Chandler Carruthd92d70b2019-01-19 06:36:00 +00001326 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1327 } else if (StrTok.isNot(tok::string_literal)) {
1328 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1329 DiscardUntilEndOfDirective();
1330 return;
1331 } else if (StrTok.hasUDSuffix()) {
1332 Diag(StrTok, diag::err_invalid_string_udl);
1333 DiscardUntilEndOfDirective();
1334 return;
1335 } else {
1336 // Parse and validate the string, converting it into a unique ID.
1337 StringLiteralParser Literal(StrTok, *this);
1338 assert(Literal.isAscii() && "Didn't allow wide strings in");
1339 if (Literal.hadError) {
1340 DiscardUntilEndOfDirective();
1341 return;
1342 }
1343 if (Literal.Pascal) {
1344 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1345 DiscardUntilEndOfDirective();
1346 return;
1347 }
1348 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1349
Chris Lattner76e68962009-01-26 06:19:46 +00001350 // If a filename was present, read any flags that are present.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001351 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001352 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001353 }
Mike Stump11289f42009-09-09 15:08:12 +00001354
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001355 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001356 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1357 IsFileExit, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001358
Chris Lattner839150e2009-03-27 17:13:49 +00001359 // If the preprocessor has callbacks installed, notify them of the #line
1360 // change. This is used so that the line marker comes out in -E mode for
1361 // example.
1362 if (Callbacks) {
1363 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1364 if (IsFileEntry)
1365 Reason = PPCallbacks::EnterFile;
1366 else if (IsFileExit)
1367 Reason = PPCallbacks::ExitFile;
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattnerc745cec2010-04-14 04:28:50 +00001369 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001370 }
Chris Lattner76e68962009-01-26 06:19:46 +00001371}
1372
Chris Lattner38d7fd22009-01-26 05:30:54 +00001373/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1374///
Mike Stump11289f42009-09-09 15:08:12 +00001375void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001376 bool isWarning) {
1377 // Read the rest of the line raw. We do this because we don't want macros
1378 // to be expanded and we don't require that the tokens be valid preprocessing
1379 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001380 // collapse multiple consecutive white space between tokens, but this isn't
Chris Lattnerf64b3522008-03-09 01:54:53 +00001381 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001382 SmallString<128> Message;
1383 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001384
1385 // Find the first non-whitespace character, so that we can make the
1386 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001387 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001388
Chris Lattner100c65e2009-01-26 05:29:08 +00001389 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001390 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001391 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001392 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001393}
1394
1395/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1396///
1397void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1398 // Yes, this directive is an extension.
1399 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001400
Chris Lattnerf64b3522008-03-09 01:54:53 +00001401 // Read the string argument.
1402 Token StrTok;
1403 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001404
Chris Lattnerf64b3522008-03-09 01:54:53 +00001405 // If the token kind isn't a string, it's a malformed directive.
1406 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001407 StrTok.isNot(tok::wide_string_literal)) {
1408 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001409 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001410 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001411 return;
1412 }
Chandler Carruthd92d70b2019-01-19 06:36:00 +00001413
1414 if (StrTok.hasUDSuffix()) {
1415 Diag(StrTok, diag::err_invalid_string_udl);
1416 DiscardUntilEndOfDirective();
1417 return;
1418 }
1419
1420 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001421 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001422
Douglas Gregordc970f02010-03-16 22:30:13 +00001423 if (Callbacks) {
1424 bool Invalid = false;
1425 std::string Str = getSpelling(StrTok, &Invalid);
1426 if (!Invalid)
1427 Callbacks->Ident(Tok.getLocation(), Str);
1428 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001429}
1430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001431/// Handle a #public directive.
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001432void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001433 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001434 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001435
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001436 // Error reading macro name? If so, diagnostic already issued.
1437 if (MacroNameTok.is(tok::eod))
1438 return;
1439
Douglas Gregor663b48f2012-01-03 19:48:16 +00001440 // Check to see if this is the last token on the #__public_macro line.
1441 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001442
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001443 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001444 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001445 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001446
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001447 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001448 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001449 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001450 return;
1451 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001452
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001453 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001454 appendMacroDirective(II, AllocateVisibilityMacroDirective(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001455 MacroNameTok.getLocation(), /*isPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001456}
1457
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001458/// Handle a #private directive.
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001459void Preprocessor::HandleMacroPrivateDirective() {
Douglas Gregorebf00492011-10-17 15:32:29 +00001460 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001461 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001462
Douglas Gregorebf00492011-10-17 15:32:29 +00001463 // Error reading macro name? If so, diagnostic already issued.
1464 if (MacroNameTok.is(tok::eod))
1465 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001466
Douglas Gregor663b48f2012-01-03 19:48:16 +00001467 // Check to see if this is the last token on the #__private_macro line.
1468 CheckEndOfDirective("__private_macro");
Taewook Oh755e4d22016-06-13 21:55:33 +00001469
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001470 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001471 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001472 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001473
Douglas Gregorebf00492011-10-17 15:32:29 +00001474 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001475 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001476 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001477 return;
1478 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001479
Douglas Gregorebf00492011-10-17 15:32:29 +00001480 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001481 appendMacroDirective(II, AllocateVisibilityMacroDirective(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001482 MacroNameTok.getLocation(), /*isPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001483}
1484
Chris Lattnerf64b3522008-03-09 01:54:53 +00001485//===----------------------------------------------------------------------===//
1486// Preprocessor Include Directive Handling.
1487//===----------------------------------------------------------------------===//
1488
1489/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001490/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001491/// true if the input filename was in <>'s or false if it were in ""'s. The
1492/// caller is expected to provide a buffer that is large enough to hold the
1493/// spelling of the filename, but is also expected to handle the case when
1494/// this method decides to use a different buffer.
1495bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001496 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001497 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001498 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001499
Richard Smith91e150d2019-03-19 22:09:55 +00001500 // FIXME: Consider warning on some of the cases described in C11 6.4.7/3 and
1501 // C++20 [lex.header]/2:
1502 //
1503 // If `"`, `'`, `\`, `/*`, or `//` appears in a header-name, then
1504 // in C: behavior is undefined
1505 // in C++: program is conditionally-supported with implementation-defined
1506 // semantics
1507
Chris Lattnerf64b3522008-03-09 01:54:53 +00001508 // Make sure the filename is <x> or "x".
1509 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001510 if (Buffer[0] == '<') {
1511 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001512 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001513 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001514 return true;
1515 }
1516 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001517 } else if (Buffer[0] == '"') {
1518 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001519 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001520 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001521 return true;
1522 }
1523 isAngled = false;
1524 } else {
1525 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001526 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001527 return true;
1528 }
Mike Stump11289f42009-09-09 15:08:12 +00001529
Chris Lattnerf64b3522008-03-09 01:54:53 +00001530 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001531 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001532 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001533 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001534 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001535 }
Mike Stump11289f42009-09-09 15:08:12 +00001536
Chris Lattnerf64b3522008-03-09 01:54:53 +00001537 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001538 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001539 return isAngled;
1540}
1541
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001542/// Push a token onto the token stream containing an annotation.
Richard Smithc51c38b2017-04-29 00:34:47 +00001543void Preprocessor::EnterAnnotationToken(SourceRange Range,
1544 tok::TokenKind Kind,
1545 void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001546 // FIXME: Produce this as the current token directly, rather than
1547 // allocating a new token for it.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001548 auto Tok = std::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001549 Tok[0].startToken();
1550 Tok[0].setKind(Kind);
Richard Smithc51c38b2017-04-29 00:34:47 +00001551 Tok[0].setLocation(Range.getBegin());
1552 Tok[0].setAnnotationEndLoc(Range.getEnd());
Richard Smith34f30512013-11-23 04:06:09 +00001553 Tok[0].setAnnotationValue(AnnotationVal);
Ilya Biryukov929af672019-05-17 09:32:05 +00001554 EnterTokenStream(std::move(Tok), 1, true, /*IsReinject*/ false);
Richard Smith34f30512013-11-23 04:06:09 +00001555}
1556
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001557/// Produce a diagnostic informing the user that a #include or similar
Richard Smith63b6fce2015-05-18 04:45:41 +00001558/// was implicitly treated as a module import.
1559static void diagnoseAutoModuleImport(
1560 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1561 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1562 SourceLocation PathEnd) {
Richard Smith8af8b862019-04-11 21:18:23 +00001563 StringRef ImportKeyword;
1564 if (PP.getLangOpts().ObjC)
1565 ImportKeyword = "@import";
1566 else if (PP.getLangOpts().ModulesTS || PP.getLangOpts().CPlusPlusModules)
1567 ImportKeyword = "import";
1568 else
1569 return; // no import syntax available
Richard Smith63b6fce2015-05-18 04:45:41 +00001570
1571 SmallString<128> PathString;
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001572 for (size_t I = 0, N = Path.size(); I != N; ++I) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001573 if (I)
1574 PathString += '.';
1575 PathString += Path[I].first->getName();
1576 }
1577 int IncludeKind = 0;
Taewook Oh755e4d22016-06-13 21:55:33 +00001578
Richard Smith63b6fce2015-05-18 04:45:41 +00001579 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1580 case tok::pp_include:
1581 IncludeKind = 0;
1582 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001583
Richard Smith63b6fce2015-05-18 04:45:41 +00001584 case tok::pp_import:
1585 IncludeKind = 1;
Taewook Oh755e4d22016-06-13 21:55:33 +00001586 break;
1587
Richard Smith63b6fce2015-05-18 04:45:41 +00001588 case tok::pp_include_next:
1589 IncludeKind = 2;
1590 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001591
Richard Smith63b6fce2015-05-18 04:45:41 +00001592 case tok::pp___include_macros:
1593 IncludeKind = 3;
1594 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001595
Richard Smith63b6fce2015-05-18 04:45:41 +00001596 default:
1597 llvm_unreachable("unknown include directive kind");
1598 }
1599
1600 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1601 /*IsTokenRange=*/false);
1602 PP.Diag(HashLoc, diag::warn_auto_module_import)
1603 << IncludeKind << PathString
Richard Smith8af8b862019-04-11 21:18:23 +00001604 << FixItHint::CreateReplacement(
1605 ReplaceRange, (ImportKeyword + " " + PathString + ";").str());
Richard Smith63b6fce2015-05-18 04:45:41 +00001606}
1607
Taewook Ohf42103c2016-06-13 20:40:21 +00001608// Given a vector of path components and a string containing the real
1609// path to the file, build a properly-cased replacement in the vector,
1610// and return true if the replacement should be suggested.
1611static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1612 StringRef RealPathName) {
1613 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1614 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1615 int Cnt = 0;
1616 bool SuggestReplacement = false;
1617 // Below is a best-effort to handle ".." in paths. It is admittedly
1618 // not 100% correct in the presence of symlinks.
1619 for (auto &Component : llvm::reverse(Components)) {
1620 if ("." == Component) {
1621 } else if (".." == Component) {
1622 ++Cnt;
1623 } else if (Cnt) {
1624 --Cnt;
1625 } else if (RealPathComponentIter != RealPathComponentEnd) {
1626 if (Component != *RealPathComponentIter) {
1627 // If these path components differ by more than just case, then we
1628 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1629 // noisy false positives.
1630 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1631 if (!SuggestReplacement)
1632 break;
1633 Component = *RealPathComponentIter;
1634 }
1635 ++RealPathComponentIter;
1636 }
1637 }
1638 return SuggestReplacement;
1639}
1640
Richard Smith27e5aa02017-06-05 18:57:56 +00001641bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
1642 const TargetInfo &TargetInfo,
1643 DiagnosticsEngine &Diags, Module *M) {
1644 Module::Requirement Requirement;
1645 Module::UnresolvedHeaderDirective MissingHeader;
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00001646 Module *ShadowingModule = nullptr;
1647 if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
1648 ShadowingModule))
Richard Smith27e5aa02017-06-05 18:57:56 +00001649 return false;
1650
1651 if (MissingHeader.FileNameLoc.isValid()) {
1652 Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1653 << MissingHeader.IsUmbrella << MissingHeader.FileName;
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00001654 } else if (ShadowingModule) {
1655 Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name;
1656 Diags.Report(ShadowingModule->DefinitionLoc,
1657 diag::note_previous_definition);
Richard Smith27e5aa02017-06-05 18:57:56 +00001658 } else {
1659 // FIXME: Track the location at which the requirement was specified, and
1660 // use it here.
1661 Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
1662 << M->getFullModuleName() << Requirement.second << Requirement.first;
1663 }
1664 return true;
1665}
1666
James Dennettf6333ac2012-06-22 05:46:07 +00001667/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1668/// the file to be included from the lexer, then include it! This is a common
1669/// routine with functionality shared between \#include, \#include_next and
1670/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001671/// specifies the file to start searching from.
Taewook Oh755e4d22016-06-13 21:55:33 +00001672void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001673 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001674 const DirectoryLookup *LookupFrom,
Richard Smith8af8b862019-04-11 21:18:23 +00001675 const FileEntry *LookupFromFile) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001676 Token FilenameTok;
Richard Smithb9b05102019-03-19 01:51:19 +00001677 if (LexHeaderName(FilenameTok))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001678 return;
Mike Stump11289f42009-09-09 15:08:12 +00001679
Richard Smith91e150d2019-03-19 22:09:55 +00001680 if (FilenameTok.isNot(tok::header_name)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001681 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
Richard Smithb9b05102019-03-19 01:51:19 +00001682 if (FilenameTok.isNot(tok::eod))
1683 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001684 return;
1685 }
Mike Stump11289f42009-09-09 15:08:12 +00001686
Richard Smith8af8b862019-04-11 21:18:23 +00001687 // Verify that there is nothing after the filename, other than EOD. Note
1688 // that we allow macros that expand to nothing after the filename, because
1689 // this falls into the category of "#include pp-tokens new-line" specified
1690 // in C99 6.10.2p4.
1691 SourceLocation EndLoc =
1692 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
1693
1694 auto Action = HandleHeaderIncludeOrImport(HashLoc, IncludeTok, FilenameTok,
1695 EndLoc, LookupFrom, LookupFromFile);
1696 switch (Action.Kind) {
1697 case ImportAction::None:
Richard Smithd652bdd2019-04-14 08:06:59 +00001698 case ImportAction::SkippedModuleImport:
Richard Smith8af8b862019-04-11 21:18:23 +00001699 break;
1700 case ImportAction::ModuleBegin:
1701 EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
1702 tok::annot_module_begin, Action.ModuleForHeader);
1703 break;
1704 case ImportAction::ModuleImport:
1705 EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
1706 tok::annot_module_include, Action.ModuleForHeader);
1707 break;
Diogo Sampaiobce360b2020-01-24 23:56:12 +00001708 case ImportAction::Failure:
1709 assert(TheModuleLoader.HadFatalFailure &&
1710 "This should be an early exit only to a fatal error");
1711 TheModuleLoader.HadFatalFailure = true;
1712 IncludeTok.setKind(tok::eof);
1713 CurLexer->cutOffLexing();
1714 return;
Richard Smith8af8b862019-04-11 21:18:23 +00001715 }
1716}
1717
Alex Lorenz4dc55732019-08-22 18:15:50 +00001718Optional<FileEntryRef> Preprocessor::LookupHeaderIncludeOrImport(
1719 const DirectoryLookup *&CurDir, StringRef Filename,
1720 SourceLocation FilenameLoc, CharSourceRange FilenameRange,
1721 const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
1722 bool &IsMapped, const DirectoryLookup *LookupFrom,
Reid Kleckner9aeae9f2019-09-25 22:50:50 +00001723 const FileEntry *LookupFromFile, StringRef LookupFilename,
Alex Lorenz4dc55732019-08-22 18:15:50 +00001724 SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
1725 ModuleMap::KnownHeader &SuggestedModule, bool isAngled) {
1726 Optional<FileEntryRef> File = LookupFile(
Reid Kleckner9aeae9f2019-09-25 22:50:50 +00001727 FilenameLoc, LookupFilename,
Alex Lorenz4dc55732019-08-22 18:15:50 +00001728 isAngled, LookupFrom, LookupFromFile, CurDir,
1729 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1730 &SuggestedModule, &IsMapped, &IsFrameworkFound);
1731 if (File)
1732 return File;
1733
1734 if (Callbacks) {
1735 // Give the clients a chance to recover.
1736 SmallString<128> RecoveryPath;
1737 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
Alex Lorenz0377ca62019-08-31 01:26:04 +00001738 if (auto DE = FileMgr.getOptionalDirectoryRef(RecoveryPath)) {
Alex Lorenz4dc55732019-08-22 18:15:50 +00001739 // Add the recovery path to the list of search paths.
1740 DirectoryLookup DL(*DE, SrcMgr::C_User, false);
1741 HeaderInfo.AddSearchPath(DL, isAngled);
1742
1743 // Try the lookup again, skipping the cache.
1744 Optional<FileEntryRef> File = LookupFile(
1745 FilenameLoc,
Reid Kleckner9aeae9f2019-09-25 22:50:50 +00001746 LookupFilename, isAngled,
Alex Lorenz4dc55732019-08-22 18:15:50 +00001747 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
1748 &SuggestedModule, &IsMapped, /*IsFrameworkFound=*/nullptr,
1749 /*SkipCache*/ true);
1750 if (File)
1751 return File;
1752 }
1753 }
1754 }
1755
1756 if (SuppressIncludeNotFoundError)
1757 return None;
1758
1759 // If the file could not be located and it was included via angle
1760 // brackets, we can attempt a lookup as though it were a quoted path to
1761 // provide the user with a possible fixit.
1762 if (isAngled) {
1763 Optional<FileEntryRef> File = LookupFile(
Reid Kleckner9aeae9f2019-09-25 22:50:50 +00001764 FilenameLoc, LookupFilename,
Alex Lorenz4dc55732019-08-22 18:15:50 +00001765 false, LookupFrom, LookupFromFile, CurDir,
1766 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1767 &SuggestedModule, &IsMapped,
1768 /*IsFrameworkFound=*/nullptr);
1769 if (File) {
1770 Diag(FilenameTok, diag::err_pp_file_not_found_angled_include_not_fatal)
1771 << Filename << IsImportDecl
1772 << FixItHint::CreateReplacement(FilenameRange,
1773 "\"" + Filename.str() + "\"");
1774 return File;
1775 }
1776 }
1777
1778 // Check for likely typos due to leading or trailing non-isAlphanumeric
1779 // characters
1780 StringRef OriginalFilename = Filename;
1781 if (LangOpts.SpellChecking) {
1782 // A heuristic to correct a typo file name by removing leading and
1783 // trailing non-isAlphanumeric characters.
1784 auto CorrectTypoFilename = [](llvm::StringRef Filename) {
1785 Filename = Filename.drop_until(isAlphanumeric);
1786 while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
1787 Filename = Filename.drop_back();
1788 }
1789 return Filename;
1790 };
1791 StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
Reid Kleckneradc18302019-09-26 17:19:22 +00001792
Alex Lorenz4dc55732019-08-22 18:15:50 +00001793#ifndef _WIN32
Reid Kleckneradc18302019-09-26 17:19:22 +00001794 // Normalize slashes when compiling with -fms-extensions on non-Windows.
1795 // This is unnecessary on Windows since the filesystem there handles
1796 // backslashes.
1797 SmallString<128> NormalizedTypoCorrectionPath;
1798 if (LangOpts.MicrosoftExt) {
1799 NormalizedTypoCorrectionPath = TypoCorrectionName;
Alex Lorenz4dc55732019-08-22 18:15:50 +00001800 llvm::sys::path::native(NormalizedTypoCorrectionPath);
Reid Kleckneradc18302019-09-26 17:19:22 +00001801 TypoCorrectionName = NormalizedTypoCorrectionPath;
Alex Lorenz4dc55732019-08-22 18:15:50 +00001802 }
Reid Kleckneradc18302019-09-26 17:19:22 +00001803#endif
1804
Alex Lorenz4dc55732019-08-22 18:15:50 +00001805 Optional<FileEntryRef> File = LookupFile(
Reid Kleckneradc18302019-09-26 17:19:22 +00001806 FilenameLoc, TypoCorrectionName, isAngled, LookupFrom, LookupFromFile,
1807 CurDir, Callbacks ? &SearchPath : nullptr,
1808 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
Alex Lorenz4dc55732019-08-22 18:15:50 +00001809 /*IsFrameworkFound=*/nullptr);
1810 if (File) {
1811 auto Hint =
1812 isAngled ? FixItHint::CreateReplacement(
1813 FilenameRange, "<" + TypoCorrectionName.str() + ">")
1814 : FixItHint::CreateReplacement(
1815 FilenameRange, "\"" + TypoCorrectionName.str() + "\"");
1816 Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
1817 << OriginalFilename << TypoCorrectionName << Hint;
1818 // We found the file, so set the Filename to the name after typo
1819 // correction.
1820 Filename = TypoCorrectionName;
1821 return File;
1822 }
1823 }
1824
1825 // If the file is still not found, just go with the vanilla diagnostic
1826 assert(!File.hasValue() && "expected missing file");
1827 Diag(FilenameTok, diag::err_pp_file_not_found)
1828 << OriginalFilename << FilenameRange;
1829 if (IsFrameworkFound) {
1830 size_t SlashPos = OriginalFilename.find('/');
1831 assert(SlashPos != StringRef::npos &&
1832 "Include with framework name should have '/' in the filename");
1833 StringRef FrameworkName = OriginalFilename.substr(0, SlashPos);
1834 FrameworkCacheEntry &CacheEntry =
1835 HeaderInfo.LookupFrameworkCache(FrameworkName);
1836 assert(CacheEntry.Directory && "Found framework should be in cache");
1837 Diag(FilenameTok, diag::note_pp_framework_without_header)
1838 << OriginalFilename.substr(SlashPos + 1) << FrameworkName
1839 << CacheEntry.Directory->getName();
1840 }
1841
1842 return None;
1843}
1844
Richard Smith8af8b862019-04-11 21:18:23 +00001845/// Handle either a #include-like directive or an import declaration that names
1846/// a header file.
1847///
1848/// \param HashLoc The location of the '#' token for an include, or
1849/// SourceLocation() for an import declaration.
1850/// \param IncludeTok The include / include_next / import token.
1851/// \param FilenameTok The header-name token.
1852/// \param EndLoc The location at which any imported macros become visible.
1853/// \param LookupFrom For #include_next, the starting directory for the
1854/// directory lookup.
1855/// \param LookupFromFile For #include_next, the starting file for the directory
1856/// lookup.
1857Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
1858 SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok,
1859 SourceLocation EndLoc, const DirectoryLookup *LookupFrom,
1860 const FileEntry *LookupFromFile) {
Richard Smithb9b05102019-03-19 01:51:19 +00001861 SmallString<128> FilenameBuffer;
1862 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer);
1863 SourceLocation CharEnd = FilenameTok.getEndLoc();
1864
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001865 CharSourceRange FilenameRange
1866 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001867 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001868 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001869 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Richard Smith8af8b862019-04-11 21:18:23 +00001870
Chris Lattnerf64b3522008-03-09 01:54:53 +00001871 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1872 // error.
Richard Smith8af8b862019-04-11 21:18:23 +00001873 if (Filename.empty())
1874 return {ImportAction::None};
Mike Stump11289f42009-09-09 15:08:12 +00001875
Richard Smith8af8b862019-04-11 21:18:23 +00001876 bool IsImportDecl = HashLoc.isInvalid();
1877 SourceLocation StartLoc = IsImportDecl ? IncludeTok.getLocation() : HashLoc;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001878
John McCall32f5fe12011-09-30 05:12:12 +00001879 // Complain about attempts to #include files in an audit pragma.
Erich Keane6a24e802019-09-13 17:39:31 +00001880 if (PragmaARCCFCodeAuditedInfo.second.isValid()) {
Richard Smith8af8b862019-04-11 21:18:23 +00001881 Diag(StartLoc, diag::err_pp_include_in_arc_cf_code_audited) << IsImportDecl;
Erich Keane6a24e802019-09-13 17:39:31 +00001882 Diag(PragmaARCCFCodeAuditedInfo.second, diag::note_pragma_entered_here);
John McCall32f5fe12011-09-30 05:12:12 +00001883
1884 // Immediately leave the pragma.
Erich Keane6a24e802019-09-13 17:39:31 +00001885 PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};
John McCall32f5fe12011-09-30 05:12:12 +00001886 }
1887
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001888 // Complain about attempts to #include files in an assume-nonnull pragma.
1889 if (PragmaAssumeNonNullLoc.isValid()) {
Richard Smith8af8b862019-04-11 21:18:23 +00001890 Diag(StartLoc, diag::err_pp_include_in_assume_nonnull) << IsImportDecl;
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001891 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1892
1893 // Immediately leave the pragma.
1894 PragmaAssumeNonNullLoc = SourceLocation();
1895 }
1896
Aaron Ballman611306e2012-03-02 22:51:54 +00001897 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001898 // Map the filename with the brackets still attached. If the name doesn't
1899 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001900 // spelling for.
1901 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1902 if (!NewName.empty())
1903 Filename = NewName;
1904 }
1905
Chris Lattnerf64b3522008-03-09 01:54:53 +00001906 // Search include directories.
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001907 bool IsMapped = false;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001908 bool IsFrameworkFound = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001909 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001910 SmallString<1024> SearchPath;
1911 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001912 // We get the raw path only if we have 'Callbacks' to which we later pass
1913 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001914 ModuleMap::KnownHeader SuggestedModule;
1915 SourceLocation FilenameLoc = FilenameTok.getLocation();
Reid Kleckneradc18302019-09-26 17:19:22 +00001916 StringRef LookupFilename = Filename;
1917
Nico Weberb9d50bd2020-04-30 20:39:19 -04001918#ifdef _WIN32
1919 llvm::sys::path::Style BackslashStyle = llvm::sys::path::Style::windows;
1920#else
Reid Kleckneradc18302019-09-26 17:19:22 +00001921 // Normalize slashes when compiling with -fms-extensions on non-Windows. This
1922 // is unnecessary on Windows since the filesystem there handles backslashes.
1923 SmallString<128> NormalizedPath;
Nico Weberb9d50bd2020-04-30 20:39:19 -04001924 llvm::sys::path::Style BackslashStyle = llvm::sys::path::Style::posix;
Reid Kleckneradc18302019-09-26 17:19:22 +00001925 if (LangOpts.MicrosoftExt) {
1926 NormalizedPath = Filename.str();
Rafael Espindolaf6002232014-08-08 21:31:04 +00001927 llvm::sys::path::native(NormalizedPath);
Reid Kleckneradc18302019-09-26 17:19:22 +00001928 LookupFilename = NormalizedPath;
Nico Weberb9d50bd2020-04-30 20:39:19 -04001929 BackslashStyle = llvm::sys::path::Style::windows;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001930 }
Reid Kleckneradc18302019-09-26 17:19:22 +00001931#endif
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001932
Alex Lorenz4dc55732019-08-22 18:15:50 +00001933 Optional<FileEntryRef> File = LookupHeaderIncludeOrImport(
1934 CurDir, Filename, FilenameLoc, FilenameRange, FilenameTok,
1935 IsFrameworkFound, IsImportDecl, IsMapped, LookupFrom, LookupFromFile,
Reid Kleckner9aeae9f2019-09-25 22:50:50 +00001936 LookupFilename, RelativePath, SearchPath, SuggestedModule, isAngled);
Douglas Gregor11729f02011-11-30 18:12:06 +00001937
Erich Keane76675de2018-07-05 17:22:13 +00001938 if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
Alex Lorenz4dc55732019-08-22 18:15:50 +00001939 if (File && isPCHThroughHeader(&File->getFileEntry()))
Erich Keane76675de2018-07-05 17:22:13 +00001940 SkippingUntilPCHThroughHeader = false;
Richard Smith8af8b862019-04-11 21:18:23 +00001941 return {ImportAction::None};
Erich Keane76675de2018-07-05 17:22:13 +00001942 }
1943
Richard Smith86559dc2019-03-21 19:44:17 +00001944 // Should we enter the source file? Set to Skip if either the source file is
Richard Smith63b6fce2015-05-18 04:45:41 +00001945 // known to have no effect beyond its effect on module visibility -- that is,
Richard Smith86559dc2019-03-21 19:44:17 +00001946 // if it's got an include guard that is already defined, set to Import if it
1947 // is a modular header we've already built and should import.
1948 enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter;
Richard Smithdbbc5232015-05-14 02:25:44 +00001949
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001950 if (PPOpts->SingleFileParseMode)
Richard Smith86559dc2019-03-21 19:44:17 +00001951 Action = IncludeLimitReached;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001952
Volodymyr Sapsai978be4c12018-12-07 20:29:54 +00001953 // If we've reached the max allowed include depth, it is usually due to an
1954 // include cycle. Don't enter already processed files again as it can lead to
1955 // reaching the max allowed include depth again.
Richard Smith86559dc2019-03-21 19:44:17 +00001956 if (Action == Enter && HasReachedMaxIncludeDepth && File &&
Alex Lorenz4dc55732019-08-22 18:15:50 +00001957 HeaderInfo.getFileInfo(&File->getFileEntry()).NumIncludes)
Richard Smith86559dc2019-03-21 19:44:17 +00001958 Action = IncludeLimitReached;
Volodymyr Sapsai482070b2018-07-25 19:16:26 +00001959
Richard Smith63b6fce2015-05-18 04:45:41 +00001960 // Determine whether we should try to import the module for this #include, if
1961 // there is one. Don't do so if precompiled module support is disabled or we
1962 // are processing this module textually (because we're building the module).
Richard Smith86559dc2019-03-21 19:44:17 +00001963 if (Action == Enter && File && SuggestedModule && getLangOpts().Modules &&
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +00001964 !isForModuleBuilding(SuggestedModule.getModule(),
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00001965 getLangOpts().CurrentModule,
1966 getLangOpts().ModuleName)) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001967 // If this include corresponds to a module but that module is
1968 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001969 // FIXME: Remove this; loadModule does the same check (but produces
1970 // slightly worse diagnostics).
Richard Smith27e5aa02017-06-05 18:57:56 +00001971 if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
1972 SuggestedModule.getModule())) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001973 Diag(FilenameTok.getLocation(),
1974 diag::note_implicit_top_level_module_import_here)
Richard Smith27e5aa02017-06-05 18:57:56 +00001975 << SuggestedModule.getModule()->getTopLevelModuleName();
Richard Smith8af8b862019-04-11 21:18:23 +00001976 return {ImportAction::None};
Sean Silva8b7c0392015-08-17 16:39:30 +00001977 }
1978
Douglas Gregor71944202011-11-30 00:36:36 +00001979 // Compute the module access path corresponding to this module.
1980 // FIXME: Should we have a second loadModule() overload to avoid this
1981 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001982 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001983 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001984 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1985 FilenameTok.getLocation()));
1986 std::reverse(Path.begin(), Path.end());
1987
Douglas Gregor41e115a2011-11-30 18:02:36 +00001988 // Warn that we're replacing the include/import with a module import.
Richard Smith8af8b862019-04-11 21:18:23 +00001989 if (!IsImportDecl)
1990 diagnoseAutoModuleImport(*this, StartLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001991
Richard Smith10434f32015-05-02 02:08:26 +00001992 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001993 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001994 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1995 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001996 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1997 IncludeTok.getLocation(), Path, Module::Hidden,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001998 /*IsInclusionDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001999 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00002000 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002001
Richard Smith86559dc2019-03-21 19:44:17 +00002002 if (Imported) {
2003 Action = Import;
2004 } else if (Imported.isMissingExpected()) {
Richard Smith63b6fce2015-05-18 04:45:41 +00002005 // We failed to find a submodule that we assumed would exist (because it
2006 // was in the directory of an umbrella header, for instance), but no
Richard Smitha114c462016-12-06 00:40:17 +00002007 // actual module containing it exists (because the umbrella header is
Richard Smith63b6fce2015-05-18 04:45:41 +00002008 // incomplete). Treat this as a textual inclusion.
2009 SuggestedModule = ModuleMap::KnownHeader();
Richard Smitha114c462016-12-06 00:40:17 +00002010 } else if (Imported.isConfigMismatch()) {
2011 // On a configuration mismatch, enter the header textually. We still know
2012 // that it's part of the corresponding module.
Richard Smith63b6fce2015-05-18 04:45:41 +00002013 } else {
2014 // We hit an error processing the import. Bail out.
2015 if (hadModuleLoaderFatalFailure()) {
2016 // With a fatal failure in the module loader, we abort parsing.
2017 Token &Result = IncludeTok;
Erich Keane0a6b5b62018-12-04 14:34:09 +00002018 assert(CurLexer && "#include but no current lexer set!");
2019 Result.startToken();
2020 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
2021 CurLexer->cutOffLexing();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002022 }
Richard Smith8af8b862019-04-11 21:18:23 +00002023 return {ImportAction::None};
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002024 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00002025 }
2026
Richard Smithc5247e62017-05-30 02:03:19 +00002027 // The #included file will be considered to be a system header if either it is
2028 // in a system include directory, or if the #includer is a system include
2029 // header.
2030 SrcMgr::CharacteristicKind FileCharacter =
2031 SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
2032 if (File)
Alex Lorenz4dc55732019-08-22 18:15:50 +00002033 FileCharacter = std::max(HeaderInfo.getFileDirFlavor(&File->getFileEntry()),
2034 FileCharacter);
Richard Smithc5247e62017-05-30 02:03:19 +00002035
Richard Smith8af8b862019-04-11 21:18:23 +00002036 // If this is a '#import' or an import-declaration, don't re-enter the file.
2037 //
2038 // FIXME: If we have a suggested module for a '#include', and we've already
2039 // visited this file, don't bother entering it again. We know it has no
2040 // further effect.
2041 bool EnterOnce =
2042 IsImportDecl ||
2043 IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import;
2044
Richard Smithc5247e62017-05-30 02:03:19 +00002045 // Ask HeaderInfo if we should enter this #include file. If not, #including
2046 // this file will have no effect.
Richard Smith86559dc2019-03-21 19:44:17 +00002047 if (Action == Enter && File &&
Alex Lorenz4dc55732019-08-22 18:15:50 +00002048 !HeaderInfo.ShouldEnterIncludeFile(*this, &File->getFileEntry(),
2049 EnterOnce, getLangOpts().Modules,
Richard Smithc5247e62017-05-30 02:03:19 +00002050 SuggestedModule.getModule())) {
Richard Smith86559dc2019-03-21 19:44:17 +00002051 // Even if we've already preprocessed this header once and know that we
2052 // don't need to see its contents again, we still need to import it if it's
2053 // modular because we might not have imported it from this submodule before.
2054 //
2055 // FIXME: We don't do this when compiling a PCH because the AST
2056 // serialization layer can't cope with it. This means we get local
2057 // submodule visibility semantics wrong in that case.
2058 Action = (SuggestedModule && !getLangOpts().CompilingPCH) ? Import : Skip;
Richard Smithc5247e62017-05-30 02:03:19 +00002059 }
2060
Sam McCallee12edc2020-04-17 16:07:21 +02002061 // Check for circular inclusion of the main file.
2062 // We can't generate a consistent preamble with regard to the conditional
2063 // stack if the main file is included again as due to the preamble bounds
2064 // some directives (e.g. #endif of a header guard) will never be seen.
2065 // Since this will lead to confusing errors, avoid the inclusion.
2066 if (Action == Enter && File && PreambleConditionalStack.isRecording() &&
2067 SourceMgr.translateFile(&File->getFileEntry()) ==
2068 SourceMgr.getMainFileID()) {
2069 Diag(FilenameTok.getLocation(),
2070 diag::err_pp_including_mainfile_in_preamble);
2071 return {ImportAction::None};
2072 }
2073
Richard Smith8af8b862019-04-11 21:18:23 +00002074 if (Callbacks && !IsImportDecl) {
Richard Smith63b6fce2015-05-18 04:45:41 +00002075 // Notify the callback object that we've seen an inclusion directive.
Richard Smith8af8b862019-04-11 21:18:23 +00002076 // FIXME: Use a different callback for a pp-import?
Nico Weberd0383832020-05-06 20:19:14 -04002077 // FIXME: Passes wrong filename if LookupHeaderIncludeOrImport() did
2078 // typo correction.
Richard Smith63b6fce2015-05-18 04:45:41 +00002079 Callbacks->InclusionDirective(
Reid Kleckner9aeae9f2019-09-25 22:50:50 +00002080 HashLoc, IncludeTok, LookupFilename, isAngled, FilenameRange,
2081 File ? &File->getFileEntry() : nullptr, SearchPath, RelativePath,
2082 Action == Import ? SuggestedModule.getModule() : nullptr,
Richard Smith86559dc2019-03-21 19:44:17 +00002083 FileCharacter);
Alex Lorenz4dc55732019-08-22 18:15:50 +00002084 if (Action == Skip && File)
Alex Lorenz67d25fe2019-08-27 01:03:25 +00002085 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Douglas Gregor97eec242011-09-15 22:00:41 +00002086 }
Richard Smith63b6fce2015-05-18 04:45:41 +00002087
2088 if (!File)
Richard Smith8af8b862019-04-11 21:18:23 +00002089 return {ImportAction::None};
Taewook Oh755e4d22016-06-13 21:55:33 +00002090
Richard Smith8af8b862019-04-11 21:18:23 +00002091 // If this is a C++20 pp-import declaration, diagnose if we didn't find any
2092 // module corresponding to the named header.
2093 if (IsImportDecl && !SuggestedModule) {
2094 Diag(FilenameTok, diag::err_header_import_not_header_unit)
2095 << OriginalFilename << File->getName();
2096 return {ImportAction::None};
2097 }
Richard Smith54ef4c32015-05-19 19:58:11 +00002098
Taewook Ohf42103c2016-06-13 20:40:21 +00002099 // Issue a diagnostic if the name of the file on disk has a different case
2100 // than the one we're about to open.
2101 const bool CheckIncludePathPortability =
Alex Lorenz4dc55732019-08-22 18:15:50 +00002102 !IsMapped && !File->getFileEntry().tryGetRealPathName().empty();
Taewook Ohf42103c2016-06-13 20:40:21 +00002103
2104 if (CheckIncludePathPortability) {
Nico Weberd0383832020-05-06 20:19:14 -04002105 // FIXME: Looks at the wrong filename if we did typo correction.
Reid Kleckner9aeae9f2019-09-25 22:50:50 +00002106 StringRef Name = LookupFilename;
Nico Weberd0383832020-05-06 20:19:14 -04002107 StringRef NameWithoriginalSlashes = Filename;
2108#if defined(_WIN32)
2109 // Skip UNC prefix if present. (tryGetRealPathName() always
2110 // returns a path with the prefix skipped.)
2111 bool NameWasUNC = Name.consume_front("\\\\?\\");
2112 NameWithoriginalSlashes.consume_front("\\\\?\\");
2113#endif
Alex Lorenz4dc55732019-08-22 18:15:50 +00002114 StringRef RealPathName = File->getFileEntry().tryGetRealPathName();
Taewook Ohf42103c2016-06-13 20:40:21 +00002115 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
2116 llvm::sys::path::end(Name));
Nico Weberd0383832020-05-06 20:19:14 -04002117#if defined(_WIN32)
2118 // -Wnonportable-include-path is designed to diagnose includes using
2119 // case even on systems with a case-insensitive file system.
2120 // On Windows, RealPathName always starts with an upper-case drive
2121 // letter for absolute paths, but Name might start with either
2122 // case depending on if `cd c:\foo` or `cd C:\foo` was used in the shell.
2123 // ("foo" will always have on-disk case, no matter which case was
2124 // used in the cd command). To not emit this warning solely for
2125 // the drive letter, whose case is dependent on if `cd` is used
2126 // with upper- or lower-case drive letters, always consider the
2127 // given drive letter case as correct for the purpose of this warning.
2128 SmallString<128> FixedDriveRealPath;
2129 if (llvm::sys::path::is_absolute(Name) &&
2130 llvm::sys::path::is_absolute(RealPathName) &&
2131 toLowercase(Name[0]) == toLowercase(RealPathName[0]) &&
2132 isLowercase(Name[0]) != isLowercase(RealPathName[0])) {
2133 assert(Components.size() >= 3 && "should have drive, backslash, name");
2134 assert(Components[0].size() == 2 && "should start with drive");
2135 assert(Components[0][1] == ':' && "should have colon");
2136 FixedDriveRealPath = (Name.substr(0, 1) + RealPathName.substr(1)).str();
2137 RealPathName = FixedDriveRealPath;
2138 }
2139#endif
Taewook Ohf42103c2016-06-13 20:40:21 +00002140
2141 if (trySimplifyPath(Components, RealPathName)) {
2142 SmallString<128> Path;
2143 Path.reserve(Name.size()+2);
2144 Path.push_back(isAngled ? '<' : '"');
Nico Weberb9d50bd2020-04-30 20:39:19 -04002145
2146 const auto IsSep = [BackslashStyle](char c) {
2147 return llvm::sys::path::is_separator(c, BackslashStyle);
2148 };
2149
Taewook Ohf42103c2016-06-13 20:40:21 +00002150 for (auto Component : Components) {
Nico Weberb9d50bd2020-04-30 20:39:19 -04002151 // On POSIX, Components will contain a single '/' as first element
2152 // exactly if Name is an absolute path.
2153 // On Windows, it will contain "C:" followed by '\' for absolute paths.
2154 // The drive letter is optional for absolute paths on Windows, but
2155 // clang currently cannot process absolute paths in #include lines that
2156 // don't have a drive.
2157 // If the first entry in Components is a directory separator,
2158 // then the code at the bottom of this loop that keeps the original
2159 // directory separator style copies it. If the second entry is
2160 // a directory separator (the C:\ case), then that separator already
2161 // got copied when the C: was processed and we want to skip that entry.
2162 if (!(Component.size() == 1 && IsSep(Component[0])))
Taewook Ohcc89bac2017-02-21 22:30:55 +00002163 Path.append(Component);
Nico Weberb9d50bd2020-04-30 20:39:19 -04002164 else if (!Path.empty())
2165 continue;
2166
2167 // Append the separator(s) the user used, or the close quote
Nico Weberd0383832020-05-06 20:19:14 -04002168 if (Path.size() > NameWithoriginalSlashes.size()) {
Nico Weberb9d50bd2020-04-30 20:39:19 -04002169 Path.push_back(isAngled ? '>' : '"');
2170 continue;
2171 }
Nico Weberd0383832020-05-06 20:19:14 -04002172 assert(IsSep(NameWithoriginalSlashes[Path.size()-1]));
Nico Weberb9d50bd2020-04-30 20:39:19 -04002173 do
Nico Weberd0383832020-05-06 20:19:14 -04002174 Path.push_back(NameWithoriginalSlashes[Path.size()-1]);
2175 while (Path.size() <= NameWithoriginalSlashes.size() &&
2176 IsSep(NameWithoriginalSlashes[Path.size()-1]));
Taewook Ohf42103c2016-06-13 20:40:21 +00002177 }
Nico Weberd0383832020-05-06 20:19:14 -04002178
2179#if defined(_WIN32)
2180 // Restore UNC prefix if it was there.
2181 if (NameWasUNC)
2182 Path = (Path.substr(0, 1) + "\\\\?\\" + Path.substr(1)).str();
2183#endif
2184
Nico Weberb9d50bd2020-04-30 20:39:19 -04002185 // For user files and known standard headers, issue a diagnostic.
2186 // For other system headers, don't. They can be controlled separately.
2187 auto DiagId =
2188 (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name))
2189 ? diag::pp_nonportable_path
2190 : diag::pp_nonportable_system_path;
Reid Kleckner273895b2017-02-14 18:38:40 +00002191 Diag(FilenameTok, DiagId) << Path <<
Richard Smithb9b05102019-03-19 01:51:19 +00002192 FixItHint::CreateReplacement(FilenameRange, Path);
Taewook Ohf42103c2016-06-13 20:40:21 +00002193 }
2194 }
2195
Richard Smith86559dc2019-03-21 19:44:17 +00002196 switch (Action) {
2197 case Skip:
2198 // If we don't need to enter the file, stop now.
Richard Smithd652bdd2019-04-14 08:06:59 +00002199 if (Module *M = SuggestedModule.getModule())
2200 return {ImportAction::SkippedModuleImport, M};
Richard Smith8af8b862019-04-11 21:18:23 +00002201 return {ImportAction::None};
Richard Smith86559dc2019-03-21 19:44:17 +00002202
2203 case IncludeLimitReached:
2204 // If we reached our include limit and don't want to enter any more files,
2205 // don't go any further.
Richard Smith8af8b862019-04-11 21:18:23 +00002206 return {ImportAction::None};
Richard Smith86559dc2019-03-21 19:44:17 +00002207
2208 case Import: {
2209 // If this is a module import, make it visible if needed.
2210 Module *M = SuggestedModule.getModule();
2211 assert(M && "no module to import");
2212
Richard Smith8af8b862019-04-11 21:18:23 +00002213 makeModuleVisible(M, EndLoc);
Richard Smith86559dc2019-03-21 19:44:17 +00002214
Richard Smith8af8b862019-04-11 21:18:23 +00002215 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() ==
Richard Smith86559dc2019-03-21 19:44:17 +00002216 tok::pp___include_macros)
Richard Smith8af8b862019-04-11 21:18:23 +00002217 return {ImportAction::None};
2218
2219 return {ImportAction::ModuleImport, M};
Richard Smith86559dc2019-03-21 19:44:17 +00002220 }
2221
2222 case Enter:
2223 break;
Chris Lattner72286d62010-04-19 20:44:31 +00002224 }
2225
Richard Smith5a8ea4c2019-03-19 01:51:17 +00002226 // Check that we don't have infinite #include recursion.
2227 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
2228 Diag(FilenameTok, diag::err_pp_include_too_deep);
2229 HasReachedMaxIncludeDepth = true;
Richard Smith8af8b862019-04-11 21:18:23 +00002230 return {ImportAction::None};
Richard Smith5a8ea4c2019-03-19 01:51:17 +00002231 }
2232
Chris Lattnerf64b3522008-03-09 01:54:53 +00002233 // Look up the file, create a File ID for it.
Richard Smithb9b05102019-03-19 01:51:19 +00002234 SourceLocation IncludePos = FilenameTok.getLocation();
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002235 // If the filename string was the result of macro expansions, set the include
2236 // position on the file where it will be included and after the expansions.
2237 if (IncludePos.isMacroID())
Richard Smithb5f81712018-04-30 05:25:48 +00002238 IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
Alex Lorenz4dc55732019-08-22 18:15:50 +00002239 FileID FID = SourceMgr.createFileID(*File, IncludePos, FileCharacter);
Diogo Sampaiobce360b2020-01-24 23:56:12 +00002240 if (!FID.isValid()) {
2241 TheModuleLoader.HadFatalFailure = true;
2242 return ImportAction::Failure;
2243 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002244
Richard Smith34f30512013-11-23 04:06:09 +00002245 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002246 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
Richard Smith8af8b862019-04-11 21:18:23 +00002247 return {ImportAction::None};
Richard Smith34f30512013-11-23 04:06:09 +00002248
Richard Smitha0aafa32015-05-18 03:52:30 +00002249 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002250 if (auto *M = SuggestedModule.getModule()) {
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00002251 if (M->getTopLevelModule()->ShadowingModule) {
2252 // We are building a submodule that belongs to a shadowed module. This
2253 // means we find header files in the shadowed module.
2254 Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule)
2255 << M->getFullModuleName();
2256 Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc,
2257 diag::note_previous_definition);
Richard Smith8af8b862019-04-11 21:18:23 +00002258 return {ImportAction::None};
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00002259 }
Manman Renffd3e9d2017-01-09 19:20:18 +00002260 // When building a pch, -fmodule-name tells the compiler to textually
2261 // include headers in the specified module. We are not building the
2262 // specified module.
Richard Smith86559dc2019-03-21 19:44:17 +00002263 //
2264 // FIXME: This is the wrong way to handle this. We should produce a PCH
2265 // that behaves the same as the header would behave in a compilation using
2266 // that PCH, which means we should enter the submodule. We need to teach
2267 // the AST serialization layer to deal with the resulting AST.
Manman Renffd3e9d2017-01-09 19:20:18 +00002268 if (getLangOpts().CompilingPCH &&
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00002269 isForModuleBuilding(M, getLangOpts().CurrentModule,
2270 getLangOpts().ModuleName))
Richard Smith8af8b862019-04-11 21:18:23 +00002271 return {ImportAction::None};
Manman Renffd3e9d2017-01-09 19:20:18 +00002272
Richard Smithd1386302017-05-04 00:29:54 +00002273 assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2274 CurLexerSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002275
Richard Smitha0aafa32015-05-18 03:52:30 +00002276 // Let the macro handling code know that any future macros are within
2277 // the new submodule.
Richard Smith8af8b862019-04-11 21:18:23 +00002278 EnterSubmodule(M, EndLoc, /*ForPragma*/false);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002279
Richard Smitha0aafa32015-05-18 03:52:30 +00002280 // Let the parser know that any future declarations are within the new
2281 // submodule.
2282 // FIXME: There's no point doing this if we're handling a #__include_macros
2283 // directive.
Richard Smith8af8b862019-04-11 21:18:23 +00002284 return {ImportAction::ModuleBegin, M};
Richard Smith67294e22014-01-31 20:47:44 +00002285 }
Richard Smith8af8b862019-04-11 21:18:23 +00002286
Richard Smithd652bdd2019-04-14 08:06:59 +00002287 assert(!IsImportDecl && "failed to diagnose missing module for import decl");
Richard Smith8af8b862019-04-11 21:18:23 +00002288 return {ImportAction::None};
Chris Lattnerf64b3522008-03-09 01:54:53 +00002289}
2290
James Dennettf6333ac2012-06-22 05:46:07 +00002291/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002292///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002293void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2294 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002295 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002296
Chris Lattnerf64b3522008-03-09 01:54:53 +00002297 // #include_next is like #include, except that we start searching after
2298 // the current found directory. If we can't do this, issue a
2299 // diagnostic.
2300 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002301 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00002302 if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2303 // If the main file is a header, then it's either for PCH/AST generation,
2304 // or libclang opened it. Either way, handle it as a normal include below
2305 // and do not complain about include_next.
2306 } else if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002307 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002308 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smithd1386302017-05-04 00:29:54 +00002309 } else if (CurLexerSubmodule) {
Richard Smith25d50752014-10-20 00:15:49 +00002310 // Start looking up in the directory *after* the one in which the current
2311 // file would be found, if any.
2312 assert(CurPPLexer && "#include_next directive in macro?");
2313 LookupFromFile = CurPPLexer->getFileEntry();
2314 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002315 } else if (!Lookup) {
Richard Smith6d69fec2019-03-21 20:42:13 +00002316 // The current file was not found by walking the include path. Either it
2317 // is the primary file (handled above), or it was found by absolute path,
2318 // or it was found relative to such a file.
2319 // FIXME: Track enough information so we know which case we're in.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002320 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2321 } else {
2322 // Start looking up in the next directory.
2323 ++Lookup;
2324 }
Mike Stump11289f42009-09-09 15:08:12 +00002325
Richard Smith25d50752014-10-20 00:15:49 +00002326 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2327 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002328}
2329
James Dennettf6333ac2012-06-22 05:46:07 +00002330/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002331void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2332 // The Microsoft #import directive takes a type library and generates header
2333 // files from it, and includes those. This is beyond the scope of what clang
2334 // does, so we ignore it and error out. However, #import can optionally have
2335 // trailing attributes that span multiple lines. We're going to eat those
2336 // so we can continue processing from there.
2337 Diag(Tok, diag::err_pp_import_directive_ms );
2338
Taewook Oh755e4d22016-06-13 21:55:33 +00002339 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002340 // directive can be split over multiple lines using the backslash character.
2341 DiscardUntilEndOfDirective();
2342}
2343
James Dennettf6333ac2012-06-22 05:46:07 +00002344/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002345///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002346void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2347 Token &ImportTok) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002348 if (!LangOpts.ObjC) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002349 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002350 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002351 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002352 }
Richard Smith8af8b862019-04-11 21:18:23 +00002353 return HandleIncludeDirective(HashLoc, ImportTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002354}
2355
Chris Lattner58a1eb02009-04-08 18:46:40 +00002356/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2357/// pseudo directive in the predefines buffer. This handles it by sucking all
2358/// tokens through the preprocessor and discarding them (only keeping the side
2359/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002360void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2361 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002362 // This directive should only occur in the predefines buffer. If not, emit an
2363 // error and reject it.
2364 SourceLocation Loc = IncludeMacrosTok.getLocation();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002365 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002366 Diag(IncludeMacrosTok.getLocation(),
2367 diag::pp_include_macros_out_of_predefines);
2368 DiscardUntilEndOfDirective();
2369 return;
2370 }
Mike Stump11289f42009-09-09 15:08:12 +00002371
Chris Lattnere01d82b2009-04-08 20:53:24 +00002372 // Treat this as a normal #include for checking purposes. If this is
2373 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002374 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002375
Chris Lattnere01d82b2009-04-08 20:53:24 +00002376 Token TmpTok;
2377 do {
2378 Lex(TmpTok);
2379 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2380 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002381}
2382
Chris Lattnerf64b3522008-03-09 01:54:53 +00002383//===----------------------------------------------------------------------===//
2384// Preprocessor Macro Directive Handling.
2385//===----------------------------------------------------------------------===//
2386
Faisal Valie8f430a2017-09-29 02:43:22 +00002387/// ReadMacroParameterList - The ( starting a parameter list of a macro
2388/// definition has just been read. Lex the rest of the parameters and the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002389/// closing ), updating MI with what we learn. Return true if an error occurs
Faisal Valie8f430a2017-09-29 02:43:22 +00002390/// parsing the param list.
Faisal Valiac506d72017-07-17 17:18:43 +00002391bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
Faisal Vali33df3912017-09-29 02:17:31 +00002392 SmallVector<IdentifierInfo*, 32> Parameters;
Mike Stump11289f42009-09-09 15:08:12 +00002393
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002394 while (true) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002395 LexUnexpandedToken(Tok);
2396 switch (Tok.getKind()) {
2397 case tok::r_paren:
Faisal Valie8f430a2017-09-29 02:43:22 +00002398 // Found the end of the parameter list.
Faisal Vali33df3912017-09-29 02:17:31 +00002399 if (Parameters.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002400 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002401 // Otherwise we have #define FOO(A,)
2402 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2403 return true;
2404 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002405 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002406 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002407 diag::warn_cxx98_compat_variadic_macro :
2408 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002409
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002410 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2411 if (LangOpts.OpenCL) {
Anastasia Stulova545652b2019-03-26 11:22:37 +00002412 Diag(Tok, diag::ext_pp_opencl_variadic_macros);
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002413 }
2414
Chris Lattnerf64b3522008-03-09 01:54:53 +00002415 // Lex the token after the identifier.
2416 LexUnexpandedToken(Tok);
2417 if (Tok.isNot(tok::r_paren)) {
2418 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2419 return true;
2420 }
Faisal Valie8f430a2017-09-29 02:43:22 +00002421 // Add the __VA_ARGS__ identifier as a parameter.
Faisal Vali33df3912017-09-29 02:17:31 +00002422 Parameters.push_back(Ident__VA_ARGS__);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002423 MI->setIsC99Varargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002424 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002425 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002426 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002427 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2428 return true;
2429 default:
2430 // Handle keywords and identifiers here to accept things like
2431 // #define Foo(for) for.
2432 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002433 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002434 // #define X(1
2435 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2436 return true;
2437 }
2438
Faisal Valie8f430a2017-09-29 02:43:22 +00002439 // If this is already used as a parameter, it is used multiple times (e.g.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002440 // #define X(A,A.
Fangrui Song75e74e02019-03-31 08:48:19 +00002441 if (llvm::find(Parameters, II) != Parameters.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002442 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002443 return true;
2444 }
Mike Stump11289f42009-09-09 15:08:12 +00002445
Faisal Valie8f430a2017-09-29 02:43:22 +00002446 // Add the parameter to the macro info.
Faisal Vali33df3912017-09-29 02:17:31 +00002447 Parameters.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002448
Chris Lattnerf64b3522008-03-09 01:54:53 +00002449 // Lex the token after the identifier.
2450 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002451
Chris Lattnerf64b3522008-03-09 01:54:53 +00002452 switch (Tok.getKind()) {
2453 default: // #define X(A B
2454 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2455 return true;
2456 case tok::r_paren: // #define X(A)
Faisal Vali33df3912017-09-29 02:17:31 +00002457 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002458 return false;
2459 case tok::comma: // #define X(A,
2460 break;
2461 case tok::ellipsis: // #define X(A... -> GCC extension
2462 // Diagnose extension.
2463 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002464
Chris Lattnerf64b3522008-03-09 01:54:53 +00002465 // Lex the token after the identifier.
2466 LexUnexpandedToken(Tok);
2467 if (Tok.isNot(tok::r_paren)) {
2468 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2469 return true;
2470 }
Mike Stump11289f42009-09-09 15:08:12 +00002471
Chris Lattnerf64b3522008-03-09 01:54:53 +00002472 MI->setIsGNUVarargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002473 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002474 return false;
2475 }
2476 }
2477 }
2478}
2479
Serge Pavlov07c0f042014-12-18 11:14:21 +00002480static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2481 const LangOptions &LOptions) {
2482 if (MI->getNumTokens() == 1) {
2483 const Token &Value = MI->getReplacementToken(0);
2484
2485 // Macro that is identity, like '#define inline inline' is a valid pattern.
2486 if (MacroName.getKind() == Value.getKind())
2487 return true;
2488
2489 // Macro that maps a keyword to the same keyword decorated with leading/
2490 // trailing underscores is a valid pattern:
2491 // #define inline __inline
2492 // #define inline __inline__
2493 // #define inline _inline (in MS compatibility mode)
2494 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2495 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2496 if (!II->isKeyword(LOptions))
2497 return false;
2498 StringRef ValueText = II->getName();
2499 StringRef TrimmedValue = ValueText;
2500 if (!ValueText.startswith("__")) {
2501 if (ValueText.startswith("_"))
2502 TrimmedValue = TrimmedValue.drop_front(1);
2503 else
2504 return false;
2505 } else {
2506 TrimmedValue = TrimmedValue.drop_front(2);
2507 if (TrimmedValue.endswith("__"))
2508 TrimmedValue = TrimmedValue.drop_back(2);
2509 }
2510 return TrimmedValue.equals(MacroText);
2511 } else {
2512 return false;
2513 }
2514 }
2515
2516 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002517 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2518 tok::kw_const) &&
2519 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002520}
2521
Faisal Valiac506d72017-07-17 17:18:43 +00002522// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2523// entire line) of the macro's tokens and adds them to MacroInfo, and while
2524// doing so performs certain validity checks including (but not limited to):
2525// - # (stringization) is followed by a macro parameter
2526//
2527// Returns a nullptr if an invalid sequence of tokens is encountered or returns
2528// a pointer to a MacroInfo object.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002529
Faisal Valiac506d72017-07-17 17:18:43 +00002530MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2531 const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002532
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002533 Token LastTok = MacroNameTok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002534 // Create the new macro.
Faisal Valiac506d72017-07-17 17:18:43 +00002535 MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002536
Chris Lattnerf64b3522008-03-09 01:54:53 +00002537 Token Tok;
2538 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002539
Ilya Biryukovb455fc42019-08-01 09:10:37 +00002540 // Ensure we consume the rest of the macro body if errors occur.
2541 auto _ = llvm::make_scope_exit([&]() {
2542 // The flag indicates if we are still waiting for 'eod'.
2543 if (CurLexer->ParsingPreprocessorDirective)
2544 DiscardUntilEndOfDirective();
2545 });
2546
Faisal Vali6bf67912017-07-25 03:15:36 +00002547 // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2548 // within their appropriate context.
2549 VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2550
Chris Lattnerf64b3522008-03-09 01:54:53 +00002551 // If this is a function-like macro definition, parse the argument list,
2552 // marking each of the identifiers as being used as macro arguments. Also,
2553 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002554 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002555 if (ImmediatelyAfterHeaderGuard) {
2556 // Save this macro information since it may part of a header guard.
2557 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2558 MacroNameTok.getLocation());
2559 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002560 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002561 } else if (Tok.hasLeadingSpace()) {
2562 // This is a normal token with leading space. Clear the leading space
2563 // marker on the first token to get proper expansion.
2564 Tok.clearFlag(Token::LeadingSpace);
2565 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002566 // This is a function-like macro definition. Read the argument list.
2567 MI->setIsFunctionLike();
Ilya Biryukovb455fc42019-08-01 09:10:37 +00002568 if (ReadMacroParameterList(MI, LastTok))
Faisal Valiac506d72017-07-17 17:18:43 +00002569 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002570
Faisal Vali6bf67912017-07-25 03:15:36 +00002571 // If this is a definition of an ISO C/C++ variadic function-like macro (not
2572 // using the GNU named varargs extension) inform our variadic scope guard
2573 // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2574 // allowed only within the definition of a variadic macro.
Mike Stump11289f42009-09-09 15:08:12 +00002575
Faisal Vali6bf67912017-07-25 03:15:36 +00002576 if (MI->isC99Varargs()) {
2577 VariadicMacroScopeGuard.enterScope();
2578 }
Mike Stump11289f42009-09-09 15:08:12 +00002579
Chris Lattnerf64b3522008-03-09 01:54:53 +00002580 // Read the first token after the arg list for down below.
2581 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002582 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002583 // C99 requires whitespace between the macro definition and the body. Emit
2584 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002585 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002586 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002587 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2588 // first character of a replacement list is not a character required by
2589 // subclause 5.2.1, then there shall be white-space separation between the
2590 // identifier and the replacement list.". 5.2.1 lists this set:
2591 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2592 // is irrelevant here.
2593 bool isInvalid = false;
2594 if (Tok.is(tok::at)) // @ is not in the list above.
2595 isInvalid = true;
2596 else if (Tok.is(tok::unknown)) {
2597 // If we have an unknown token, it is something strange like "`". Since
2598 // all of valid characters would have lexed into a single character
2599 // token of some sort, we know this is not a valid case.
2600 isInvalid = true;
2601 }
2602 if (isInvalid)
2603 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2604 else
2605 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002606 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002607
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002608 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002609 LastTok = Tok;
2610
Chris Lattnerf64b3522008-03-09 01:54:53 +00002611 // Read the rest of the macro body.
2612 if (MI->isObjectLike()) {
2613 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002614 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002615 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002616 MI->AddTokenToBody(Tok);
2617 // Get the next token of the macro.
2618 LexUnexpandedToken(Tok);
2619 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002620 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002621 // Otherwise, read the body of a function-like macro. While we are at it,
2622 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2623 // parameters in function-like macro expansions.
Faisal Vali18268422017-10-15 01:26:26 +00002624
2625 VAOptDefinitionContext VAOCtx(*this);
2626
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002627 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002628 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002629
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002630 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002631 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002632
Faisal Vali18268422017-10-15 01:26:26 +00002633 if (VAOCtx.isVAOptToken(Tok)) {
2634 // If we're already within a VAOPT, emit an error.
2635 if (VAOCtx.isInVAOpt()) {
2636 Diag(Tok, diag::err_pp_vaopt_nested_use);
2637 return nullptr;
2638 }
2639 // Ensure VAOPT is followed by a '(' .
2640 LexUnexpandedToken(Tok);
2641 if (Tok.isNot(tok::l_paren)) {
2642 Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
2643 return nullptr;
2644 }
2645 MI->AddTokenToBody(Tok);
2646 VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
2647 LexUnexpandedToken(Tok);
2648 if (Tok.is(tok::hashhash)) {
2649 Diag(Tok, diag::err_vaopt_paste_at_start);
2650 return nullptr;
2651 }
2652 continue;
2653 } else if (VAOCtx.isInVAOpt()) {
2654 if (Tok.is(tok::r_paren)) {
2655 if (VAOCtx.sawClosingParen()) {
2656 const unsigned NumTokens = MI->getNumTokens();
2657 assert(NumTokens >= 3 && "Must have seen at least __VA_OPT__( "
2658 "and a subsequent tok::r_paren");
2659 if (MI->getReplacementToken(NumTokens - 2).is(tok::hashhash)) {
2660 Diag(Tok, diag::err_vaopt_paste_at_end);
2661 return nullptr;
2662 }
2663 }
2664 } else if (Tok.is(tok::l_paren)) {
2665 VAOCtx.sawOpeningParen(Tok.getLocation());
2666 }
2667 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002668 // Get the next token of the macro.
2669 LexUnexpandedToken(Tok);
2670 continue;
2671 }
Mike Stump11289f42009-09-09 15:08:12 +00002672
Richard Smith701a3522013-07-09 01:00:29 +00002673 // If we're in -traditional mode, then we should ignore stringification
2674 // and token pasting. Mark the tokens as unknown so as not to confuse
2675 // things.
2676 if (getLangOpts().TraditionalCPP) {
2677 Tok.setKind(tok::unknown);
2678 MI->AddTokenToBody(Tok);
2679
2680 // Get the next token of the macro.
2681 LexUnexpandedToken(Tok);
2682 continue;
2683 }
2684
Eli Friedman14d3c792012-11-14 02:18:46 +00002685 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002686 // If we see token pasting, check if it looks like the gcc comma
2687 // pasting extension. We'll use this information to suppress
2688 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002689
Eli Friedman14d3c792012-11-14 02:18:46 +00002690 // Get the next token of the macro.
2691 LexUnexpandedToken(Tok);
2692
2693 if (Tok.is(tok::eod)) {
2694 MI->AddTokenToBody(LastTok);
2695 break;
2696 }
2697
2698 unsigned NumTokens = MI->getNumTokens();
2699 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2700 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2701 MI->setHasCommaPasting();
2702
David Majnemer76faf1f2013-11-05 09:30:17 +00002703 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002704 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002705 continue;
2706 }
2707
Faisal Vali18268422017-10-15 01:26:26 +00002708 // Our Token is a stringization operator.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002709 // Get the next token of the macro.
2710 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002711
Faisal Vali18268422017-10-15 01:26:26 +00002712 // Check for a valid macro arg identifier or __VA_OPT__.
2713 if (!VAOCtx.isVAOptToken(Tok) &&
2714 (Tok.getIdentifierInfo() == nullptr ||
2715 MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002716
2717 // If this is assembler-with-cpp mode, we accept random gibberish after
2718 // the '#' because '#' is often a comment character. However, change
2719 // the kind of the token to tok::unknown so that the preprocessor isn't
2720 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002721 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002722 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002723 MI->AddTokenToBody(LastTok);
2724 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002725 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002726 Diag(Tok, diag::err_pp_stringize_not_parameter)
2727 << LastTok.is(tok::hashat);
Faisal Valiac506d72017-07-17 17:18:43 +00002728 return nullptr;
Chris Lattner83bd8282009-05-25 17:16:10 +00002729 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002730 }
Mike Stump11289f42009-09-09 15:08:12 +00002731
Chris Lattner83bd8282009-05-25 17:16:10 +00002732 // Things look ok, add the '#' and param name tokens to the macro.
2733 MI->AddTokenToBody(LastTok);
Mike Stump11289f42009-09-09 15:08:12 +00002734
Faisal Vali18268422017-10-15 01:26:26 +00002735 // If the token following '#' is VAOPT, let the next iteration handle it
2736 // and check it for correctness, otherwise add the token and prime the
2737 // loop with the next one.
2738 if (!VAOCtx.isVAOptToken(Tok)) {
2739 MI->AddTokenToBody(Tok);
2740 LastTok = Tok;
2741
2742 // Get the next token of the macro.
2743 LexUnexpandedToken(Tok);
2744 }
2745 }
2746 if (VAOCtx.isInVAOpt()) {
2747 assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
2748 Diag(Tok, diag::err_pp_expected_after)
2749 << LastTok.getKind() << tok::r_paren;
2750 Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
2751 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002752 }
2753 }
Faisal Valiac506d72017-07-17 17:18:43 +00002754 MI->setDefinitionEndLoc(LastTok.getLocation());
Faisal Valiac506d72017-07-17 17:18:43 +00002755 return MI;
2756}
2757/// HandleDefineDirective - Implements \#define. This consumes the entire macro
2758/// line then lets the caller lex the next real token.
2759void Preprocessor::HandleDefineDirective(
2760 Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2761 ++NumDefined;
2762
2763 Token MacroNameTok;
2764 bool MacroShadowsKeyword;
2765 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2766
2767 // Error reading macro name? If so, diagnostic already issued.
2768 if (MacroNameTok.is(tok::eod))
2769 return;
2770
2771 // If we are supposed to keep comments in #defines, reenable comment saving
2772 // mode.
2773 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2774
2775 MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2776 MacroNameTok, ImmediatelyAfterHeaderGuard);
Fangrui Song6907ce22018-07-30 19:24:48 +00002777
Faisal Valiac506d72017-07-17 17:18:43 +00002778 if (!MI) return;
Mike Stump11289f42009-09-09 15:08:12 +00002779
Serge Pavlov07c0f042014-12-18 11:14:21 +00002780 if (MacroShadowsKeyword &&
2781 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2782 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
Fangrui Song6907ce22018-07-30 19:24:48 +00002783 }
Chris Lattner57540c52011-04-15 05:22:18 +00002784 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002785 // replacement list.
2786 unsigned NumTokens = MI->getNumTokens();
2787 if (NumTokens != 0) {
2788 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2789 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002790 return;
2791 }
2792 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2793 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002794 return;
2795 }
2796 }
Mike Stump11289f42009-09-09 15:08:12 +00002797
Erich Keane76675de2018-07-05 17:22:13 +00002798 // When skipping just warn about macros that do not match.
2799 if (SkippingUntilPCHThroughHeader) {
2800 const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
2801 if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
2802 /*Syntactic=*/LangOpts.MicrosoftExt))
2803 Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
2804 << MacroNameTok.getIdentifierInfo();
Zachary Henkel0f9cf422020-01-14 14:58:14 -08002805 // Issue the diagnostic but allow the change if msvc extensions are enabled
2806 if (!LangOpts.MicrosoftExt)
2807 return;
Erich Keane76675de2018-07-05 17:22:13 +00002808 }
Mike Stump11289f42009-09-09 15:08:12 +00002809
Chris Lattnerf64b3522008-03-09 01:54:53 +00002810 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002811 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002812 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002813 // In Objective-C, ignore attempts to directly redefine the builtin
2814 // definitions of the ownership qualifiers. It's still possible to
2815 // #undef them.
2816 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2817 return II->isStr("__strong") ||
2818 II->isStr("__weak") ||
2819 II->isStr("__unsafe_unretained") ||
2820 II->isStr("__autoreleasing");
2821 };
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002822 if (getLangOpts().ObjC &&
John McCall83760372015-12-10 23:31:01 +00002823 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2824 == getPredefinesFileID() &&
2825 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2826 // Warn if it changes the tokens.
2827 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2828 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2829 !MI->isIdenticalTo(*OtherMI, *this,
2830 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2831 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2832 }
2833 assert(!OtherMI->isWarnIfUnused());
2834 return;
2835 }
2836
Chris Lattner5244f342009-01-16 19:50:11 +00002837 // It is very common for system headers to have tons of macro redefinitions
2838 // and for warnings to be disabled in system headers. If this is the case,
2839 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002840 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002841 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002842 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002843 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002844
Taewook Oh755e4d22016-06-13 21:55:33 +00002845 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002846 // C++ [cpp.predefined]p4, but allow it as an extension.
2847 if (OtherMI->isBuiltinMacro())
2848 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002849 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002850 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002851 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002852 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002853 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2854 << MacroNameTok.getIdentifierInfo();
2855 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2856 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002857 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002858 if (OtherMI->isWarnIfUnused())
2859 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002860 }
Mike Stump11289f42009-09-09 15:08:12 +00002861
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002862 DefMacroDirective *MD =
2863 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002864
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002865 assert(!MI->isUsed());
2866 // If we need warning for not using the macro, add its location in the
2867 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002868 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Lubos Lunaka507a5e2019-09-16 19:18:37 +00002869 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc()) &&
Luboš Luňák5c8c9902020-02-02 12:15:40 +01002870 !MacroExpansionInDirectivesOverride &&
2871 getSourceManager().getFileID(MI->getDefinitionLoc()) !=
2872 getPredefinesFileID()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002873 MI->setIsWarnIfUnused(true);
2874 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2875 }
2876
Chris Lattner928e9092009-04-12 01:39:54 +00002877 // If the callbacks want to know, tell them about the macro definition.
2878 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002879 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002880}
2881
James Dennettf6333ac2012-06-22 05:46:07 +00002882/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002883///
Erik Verbruggen4bddef92016-10-26 08:52:41 +00002884void Preprocessor::HandleUndefDirective() {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002885 ++NumUndefined;
2886
2887 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002888 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002889
Chris Lattnerf64b3522008-03-09 01:54:53 +00002890 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002891 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002892 return;
Mike Stump11289f42009-09-09 15:08:12 +00002893
Chris Lattnerf64b3522008-03-09 01:54:53 +00002894 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002895 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002896
Richard Smith20e883e2015-04-29 23:20:19 +00002897 // Okay, we have a valid identifier to undef.
2898 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002899 auto MD = getMacroDefinition(II);
Vedant Kumar349a6242017-04-26 21:05:44 +00002900 UndefMacroDirective *Undef = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00002901
Vedant Kumar349a6242017-04-26 21:05:44 +00002902 // If the macro is not defined, this is a noop undef.
2903 if (const MacroInfo *MI = MD.getMacroInfo()) {
2904 if (!MI->isUsed() && MI->isWarnIfUnused())
2905 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2906
2907 if (MI->isWarnIfUnused())
2908 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2909
2910 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
2911 }
Mike Stump11289f42009-09-09 15:08:12 +00002912
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002913 // If the callbacks want to know, tell them about the macro #undef.
2914 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002915 if (Callbacks)
Vedant Kumar349a6242017-04-26 21:05:44 +00002916 Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002917
Vedant Kumar349a6242017-04-26 21:05:44 +00002918 if (Undef)
2919 appendMacroDirective(II, Undef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002920}
2921
Chris Lattnerf64b3522008-03-09 01:54:53 +00002922//===----------------------------------------------------------------------===//
2923// Preprocessor Conditional Directive Handling.
2924//===----------------------------------------------------------------------===//
2925
James Dennettf6333ac2012-06-22 05:46:07 +00002926/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2927/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2928/// true if any tokens have been returned or pp-directives activated before this
2929/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002930///
Vedant Kumar3919a502017-09-11 20:47:42 +00002931void Preprocessor::HandleIfdefDirective(Token &Result,
2932 const Token &HashToken,
2933 bool isIfndef,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002934 bool ReadAnyTokensBeforeDirective) {
2935 ++NumIf;
2936 Token DirectiveTok = Result;
2937
2938 Token MacroNameTok;
2939 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002940
Chris Lattnerf64b3522008-03-09 01:54:53 +00002941 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002942 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002943 // Skip code until we get to #endif. This helps with recovery by not
2944 // emitting an error when the #endif is reached.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002945 SkipExcludedConditionalBlock(HashToken.getLocation(),
2946 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002947 /*Foundnonskip*/ false, /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002948 return;
2949 }
Mike Stump11289f42009-09-09 15:08:12 +00002950
Chris Lattnerf64b3522008-03-09 01:54:53 +00002951 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002952 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002953
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002954 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002955 auto MD = getMacroDefinition(MII);
2956 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002957
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002958 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002959 // If the start of a top-level #ifdef and if the macro is not defined,
2960 // inform MIOpt that this might be the start of a proper include guard.
2961 // Otherwise it is some other form of unknown conditional which we can't
2962 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002963 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002964 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002965 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002966 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002967 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002968 }
2969
Chris Lattnerf64b3522008-03-09 01:54:53 +00002970 // If there is a macro, process it.
2971 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002972 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002973
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002974 if (Callbacks) {
2975 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002976 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002977 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002978 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002979 }
2980
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00002981 bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
2982 getSourceManager().isInMainFile(DirectiveTok.getLocation());
2983
Chris Lattnerf64b3522008-03-09 01:54:53 +00002984 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002985 if (PPOpts->SingleFileParseMode && !MI) {
2986 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2987 // the directive blocks.
2988 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002989 /*wasskip*/false, /*foundnonskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002990 /*foundelse*/false);
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00002991 } else if (!MI == isIfndef || RetainExcludedCB) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002992 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002993 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2994 /*wasskip*/false, /*foundnonskip*/true,
2995 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002996 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002997 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002998 SkipExcludedConditionalBlock(HashToken.getLocation(),
2999 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00003000 /*Foundnonskip*/ false,
3001 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00003002 }
3003}
3004
James Dennettf6333ac2012-06-22 05:46:07 +00003005/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00003006///
3007void Preprocessor::HandleIfDirective(Token &IfToken,
Vedant Kumar3919a502017-09-11 20:47:42 +00003008 const Token &HashToken,
Chris Lattnerf64b3522008-03-09 01:54:53 +00003009 bool ReadAnyTokensBeforeDirective) {
3010 ++NumIf;
Chandler Carruthd92d70b2019-01-19 06:36:00 +00003011
3012 // Parse and evaluate the conditional expression.
3013 IdentifierInfo *IfNDefMacro = nullptr;
3014 const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
3015 const bool ConditionalTrue = DER.Conditional;
3016
3017 // If this condition is equivalent to #ifndef X, and if this is the first
3018 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00003019 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00003020 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00003021 // FIXME: Pass in the location of the macro name, not the 'if' token.
3022 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00003023 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00003024 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chandler Carruthd92d70b2019-01-19 06:36:00 +00003025 }
3026
3027 if (Callbacks)
3028 Callbacks->If(
3029 IfToken.getLocation(), DER.ExprRange,
3030 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
3031
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003032 bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3033 getSourceManager().isInMainFile(IfToken.getLocation());
3034
Chandler Carruthd92d70b2019-01-19 06:36:00 +00003035 // Should we include the stuff contained by this directive?
3036 if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00003037 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3038 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00003039 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00003040 /*foundnonskip*/false, /*foundelse*/false);
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003041 } else if (ConditionalTrue || RetainExcludedCB) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00003042 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00003043 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00003044 /*foundnonskip*/true, /*foundelse*/false);
3045 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00003046 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003047 SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00003048 /*Foundnonskip*/ false,
3049 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00003050 }
3051}
3052
James Dennettf6333ac2012-06-22 05:46:07 +00003053/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00003054///
3055void Preprocessor::HandleEndifDirective(Token &EndifToken) {
3056 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00003057
Chris Lattnerf64b3522008-03-09 01:54:53 +00003058 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00003059 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00003060
Chris Lattnerf64b3522008-03-09 01:54:53 +00003061 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00003062 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00003063 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00003064 Diag(EndifToken, diag::err_pp_endif_without_if);
3065 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00003066 }
Mike Stump11289f42009-09-09 15:08:12 +00003067
Chris Lattnerf64b3522008-03-09 01:54:53 +00003068 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00003069 if (CurPPLexer->getConditionalStackDepth() == 0)
3070 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00003071
Ted Kremenek30cd88c2008-11-18 00:34:22 +00003072 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00003073 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00003074
3075 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00003076 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00003077}
3078
James Dennettf6333ac2012-06-22 05:46:07 +00003079/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00003080///
Vedant Kumar3919a502017-09-11 20:47:42 +00003081void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00003082 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00003083
Chris Lattnerf64b3522008-03-09 01:54:53 +00003084 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00003085 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00003086
Chris Lattnerf64b3522008-03-09 01:54:53 +00003087 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00003088 if (CurPPLexer->popConditionalLevel(CI)) {
3089 Diag(Result, diag::pp_err_else_without_if);
3090 return;
3091 }
Mike Stump11289f42009-09-09 15:08:12 +00003092
Chris Lattnerf64b3522008-03-09 01:54:53 +00003093 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00003094 if (CurPPLexer->getConditionalStackDepth() == 0)
3095 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00003096
3097 // If this is a #else with a #else before it, report the error.
3098 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00003099
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00003100 if (Callbacks)
3101 Callbacks->Else(Result.getLocation(), CI.IfLoc);
3102
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003103 bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3104 getSourceManager().isInMainFile(Result.getLocation());
3105
3106 if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00003107 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3108 // the directive blocks.
3109 CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00003110 /*foundnonskip*/false, /*foundelse*/true);
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00003111 return;
3112 }
3113
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00003114 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003115 SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
3116 /*Foundnonskip*/ true,
Vedant Kumar3919a502017-09-11 20:47:42 +00003117 /*FoundElse*/ true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00003118}
3119
James Dennettf6333ac2012-06-22 05:46:07 +00003120/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00003121///
Vedant Kumar3919a502017-09-11 20:47:42 +00003122void Preprocessor::HandleElifDirective(Token &ElifToken,
3123 const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00003124 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00003125
Chandler Carruthd92d70b2019-01-19 06:36:00 +00003126 // #elif directive in a non-skipping conditional... start skipping.
3127 // We don't care what the condition is, because we will always skip it (since
3128 // the block immediately before it was included).
3129 SourceRange ConditionRange = DiscardUntilEndOfDirective();
3130
3131 PPConditionalInfo CI;
3132 if (CurPPLexer->popConditionalLevel(CI)) {
Chris Lattner907dfe92008-11-18 07:59:24 +00003133 Diag(ElifToken, diag::pp_err_elif_without_if);
3134 return;
3135 }
Mike Stump11289f42009-09-09 15:08:12 +00003136
Chris Lattnerf64b3522008-03-09 01:54:53 +00003137 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00003138 if (CurPPLexer->getConditionalStackDepth() == 0)
3139 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00003140
Chris Lattnerf64b3522008-03-09 01:54:53 +00003141 // If this is a #elif with a #else before it, report the error.
Chandler Carruthd92d70b2019-01-19 06:36:00 +00003142 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
3143
3144 if (Callbacks)
3145 Callbacks->Elif(ElifToken.getLocation(), ConditionRange,
3146 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
3147
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003148 bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3149 getSourceManager().isInMainFile(ElifToken.getLocation());
3150
3151 if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00003152 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3153 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00003154 CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00003155 /*foundnonskip*/false, /*foundelse*/false);
3156 return;
3157 }
3158
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00003159 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003160 SkipExcludedConditionalBlock(
3161 HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
3162 /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00003163}