blob: 525f95b96e030296ead44d003e3af8d47233cc09 [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
James Dennettf6333ac2012-06-22 05:46:07 +0000373/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
374/// decided that the subsequent tokens are in the \#if'd out portion of the
375/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000376/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000377/// this \#if directive, so \#else/\#elif blocks should never be entered.
378/// If ElseOk is true, then \#else directives are ok, if not, then we have
379/// already seen one so a \#else directive is a duplicate. When this returns,
380/// the caller can lex the first valid token.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000381void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
Vedant Kumar3919a502017-09-11 20:47:42 +0000382 SourceLocation IfTokenLoc,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000383 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000384 bool FoundElse,
385 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000387 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000388
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000389 if (PreambleConditionalStack.reachedEOFWhileSkipping())
390 PreambleConditionalStack.clearSkipInfo();
391 else
392 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
393 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattnerf64b3522008-03-09 01:54:53 +0000395 // Enter raw mode to disable identifier lookup (and thus macro expansion),
396 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000397 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000398 Token Tok;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000399 while (true) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000400 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000401
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000402 if (Tok.is(tok::code_completion)) {
403 if (CodeComplete)
404 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000405 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000406 continue;
407 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000408
Chris Lattnerf64b3522008-03-09 01:54:53 +0000409 // If this is the end of the buffer, we have an error.
410 if (Tok.is(tok::eof)) {
Ilya Biryukov8f738ac2017-09-12 08:35:57 +0000411 // We don't emit errors for unterminated conditionals here,
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000412 // Lexer::LexEndOfFile can do that properly.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000413 // Just return and let the caller lex after this #include.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000414 if (PreambleConditionalStack.isRecording())
415 PreambleConditionalStack.SkipInfo.emplace(
416 HashTokenLoc, IfTokenLoc, FoundNonSkipPortion, FoundElse, ElseLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000417 break;
418 }
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattnerf64b3522008-03-09 01:54:53 +0000420 // If this token is not a preprocessor directive, just skip it.
421 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
422 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattnerf64b3522008-03-09 01:54:53 +0000424 // We just parsed a # character at the start of a line, so we're in
425 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000426 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000427 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000428 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000429
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattnerf64b3522008-03-09 01:54:53 +0000431 // Read the next token, the directive flavor.
432 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000433
Chris Lattnerf64b3522008-03-09 01:54:53 +0000434 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
435 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000436 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000437 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000438 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000439 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000440 continue;
441 }
442
443 // If the first letter isn't i or e, it isn't intesting to us. We know that
444 // this is safe in the face of spelling differences, because there is no way
445 // to spell an i/e in a strange way that is another letter. Skipping this
446 // allows us to avoid looking up the identifier info for #define/#undef and
447 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000448 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000449
Alp Toker2d57cea2014-05-17 04:53:25 +0000450 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000451 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000452 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000453 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000454 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000455 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000456 continue;
457 }
Mike Stump11289f42009-09-09 15:08:12 +0000458
Chris Lattnerf64b3522008-03-09 01:54:53 +0000459 // Get the identifier name without trigraphs or embedded newlines. Note
460 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
461 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000462 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000463 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000464 if (!Tok.needsCleaning() && RI.size() < 20) {
465 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000466 } else {
467 std::string DirectiveStr = getSpelling(Tok);
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000468 size_t IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000469 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000470 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000471 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000472 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000473 continue;
474 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000475 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000476 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000477 }
Mike Stump11289f42009-09-09 15:08:12 +0000478
Benjamin Kramer144884642009-12-31 13:32:38 +0000479 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000480 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000481 if (Sub.empty() || // "if"
482 Sub == "def" || // "ifdef"
483 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000484 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
485 // bother parsing the condition.
486 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000487 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000488 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000489 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000490 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000491 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000493 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000494 PPConditionalInfo CondInfo;
495 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000496 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000497 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000498 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000499
Chris Lattnerf64b3522008-03-09 01:54:53 +0000500 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000501 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000502 // Restore the value of LexingRawMode so that trailing comments
503 // are handled correctly, if we've reached the outermost block.
504 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000505 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000506 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000507 if (Callbacks)
508 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000509 break;
Richard Smithd0124572012-06-21 00:35:03 +0000510 } else {
511 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000512 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000513 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000514 // #else directive in a skipping conditional. If not in some other
515 // skipping conditional, and if #else hasn't already been seen, enter it
516 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000517 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000518
Chris Lattnerf64b3522008-03-09 01:54:53 +0000519 // If this is a #else with a #else before it, report the error.
520 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000521
Chris Lattnerf64b3522008-03-09 01:54:53 +0000522 // Note that we've seen a #else in this conditional.
523 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000524
Chris Lattnerf64b3522008-03-09 01:54:53 +0000525 // If the conditional is at the top level, and the #if block wasn't
526 // entered, enter the #else block now.
527 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
528 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000529 // Restore the value of LexingRawMode so that trailing comments
530 // are handled correctly.
531 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000532 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000533 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000534 if (Callbacks)
535 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000536 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000537 } else {
538 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000539 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000540 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000541 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000542
John Thompson17c35732013-12-04 20:19:30 +0000543 // If this is a #elif with a #else before it, report the error.
544 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
545
Chris Lattnerf64b3522008-03-09 01:54:53 +0000546 // If this is in a skipping block or if we're already handled this #if
547 // block, don't bother parsing the condition.
Chandler Carruthd92d70b2019-01-19 06:36:00 +0000548 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
549 DiscardUntilEndOfDirective();
550 } else {
551 // Restore the value of LexingRawMode so that identifiers are
552 // looked up, etc, inside the #elif expression.
553 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
554 CurPPLexer->LexingRawMode = false;
555 IdentifierInfo *IfNDefMacro = nullptr;
556 DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
557 const bool CondValue = DER.Conditional;
558 CurPPLexer->LexingRawMode = true;
559 if (Callbacks) {
560 Callbacks->Elif(
561 Tok.getLocation(), DER.ExprRange,
562 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
563 CondInfo.IfLoc);
564 }
565 // If this condition is true, enter it!
566 if (CondValue) {
John Thompson17c35732013-12-04 20:19:30 +0000567 CondInfo.FoundNonSkip = true;
568 break;
569 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000570 }
571 }
572 }
Mike Stump11289f42009-09-09 15:08:12 +0000573
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000574 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000575 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000576 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000577 }
578
579 // Finally, if we are out of the conditional (saw an #endif or ran off the end
580 // of the file, just stop skipping and return to lexing whatever came after
581 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000582 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000583
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000584 // The last skipped range isn't actually skipped yet if it's truncated
585 // by the end of the preamble; we'll resume parsing after the preamble.
586 if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
Vedant Kumar3919a502017-09-11 20:47:42 +0000587 Callbacks->SourceRangeSkipped(
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000588 SourceRange(HashTokenLoc, CurPPLexer->getSourceLocation()),
Vedant Kumar3919a502017-09-11 20:47:42 +0000589 Tok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000590}
591
Richard Smith2a553082015-04-23 22:58:06 +0000592Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000593 if (!SourceMgr.isInMainFile(Loc)) {
594 // Try to determine the module of the include directive.
595 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
596 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
597 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
598 // The include comes from an included file.
599 return HeaderInfo.getModuleMap()
600 .findModuleForHeader(EntryOfIncl)
601 .getModule();
602 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000603 }
Richard Smith7e82e012016-02-19 22:25:36 +0000604
605 // This is either in the main file or not in a file at all. It belongs
606 // to the current module, if there is one.
607 return getLangOpts().CurrentModule.empty()
608 ? nullptr
609 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000610}
611
Richard Smith4eb83932016-04-27 21:57:05 +0000612const FileEntry *
613Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000614 Module *M,
Richard Smith4eb83932016-04-27 21:57:05 +0000615 SourceLocation Loc) {
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000616 assert(M && "no module to include");
617
Richard Smithe867e982019-04-18 00:56:58 +0000618 // If the context is the global module fragment of some module, we never
619 // want to return that file; instead, we want the innermost include-guarded
620 // header that it included.
621 bool InGlobalModuleFragment = M->Kind == Module::GlobalModuleFragment;
622
Richard Smith4eb83932016-04-27 21:57:05 +0000623 // If we have a module import syntax, we shouldn't include a header to
624 // make a particular module visible.
Richard Smithe867e982019-04-18 00:56:58 +0000625 if ((getLangOpts().ObjC || getLangOpts().CPlusPlusModules ||
626 getLangOpts().ModulesTS) &&
627 !InGlobalModuleFragment)
Richard Smith4eb83932016-04-27 21:57:05 +0000628 return nullptr;
629
Richard Smith4eb83932016-04-27 21:57:05 +0000630 Module *TopM = M->getTopLevelModule();
631 Module *IncM = getModuleForLocation(IncLoc);
632
633 // Walk up through the include stack, looking through textual headers of M
634 // until we hit a non-textual header that we can #include. (We assume textual
635 // headers of a module with non-textual headers aren't meant to be used to
636 // import entities from the module.)
637 auto &SM = getSourceManager();
638 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
639 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
640 auto *FE = SM.getFileEntryForID(ID);
Richard Smith040e1262017-06-02 01:55:39 +0000641 if (!FE)
642 break;
Richard Smith4eb83932016-04-27 21:57:05 +0000643
Richard Smithe867e982019-04-18 00:56:58 +0000644 if (InGlobalModuleFragment) {
645 if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE))
646 return FE;
647 Loc = SM.getIncludeLoc(ID);
648 continue;
649 }
650
Richard Smith4eb83932016-04-27 21:57:05 +0000651 bool InTextualHeader = false;
652 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
653 if (!Header.getModule()->isSubModuleOf(TopM))
654 continue;
655
656 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
657 // If this is an accessible, non-textual header of M's top-level module
658 // that transitively includes the given location and makes the
659 // corresponding module visible, this is the thing to #include.
660 if (Header.isAccessibleFrom(IncM))
661 return FE;
662
663 // It's in a private header; we can't #include it.
664 // FIXME: If there's a public header in some module that re-exports it,
665 // then we could suggest including that, but it's not clear that's the
666 // expected way to make this entity visible.
667 continue;
668 }
669
670 InTextualHeader = true;
671 }
672
673 if (!InTextualHeader)
674 break;
675
676 Loc = SM.getIncludeLoc(ID);
677 }
678
679 return nullptr;
680}
681
Alex Lorenz4dc55732019-08-22 18:15:50 +0000682Optional<FileEntryRef> Preprocessor::LookupFile(
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000683 SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
684 const DirectoryLookup *FromDir, const FileEntry *FromFile,
685 const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000686 SmallVectorImpl<char> *RelativePath,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000687 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
688 bool *IsFrameworkFound, bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000689 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000690 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000691
Will Wilson0fafd342013-12-27 19:46:16 +0000692 // If the header lookup mechanism may be relative to the current inclusion
693 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000694 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
695 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000696 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000697 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000698 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000699 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000700
Chris Lattner022923a2009-02-04 19:45:07 +0000701 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000702 // predefines buffer or the module includes buffer. Any other file is not
703 // lexed with a normal lexer, so it won't be scanned for preprocessor
704 // directives.
705 //
706 // If we have the predefines buffer, resolve #include references (which come
707 // from the -include command line argument) from the current working
708 // directory instead of relative to the main file.
709 //
710 // If we have the module includes buffer, resolve #include references (which
711 // come from header declarations in the module map) relative to the module
712 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000713 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000714 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000715 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000716 BuildSystemModule = getCurrentModule()->IsSystem;
717 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000718 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Harlan Haskins8d323d12019-08-01 21:31:56 +0000719 Includers.push_back(std::make_pair(FileEnt, *FileMgr.getDirectory(".")));
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000720 } else {
721 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
722 }
Will Wilson0fafd342013-12-27 19:46:16 +0000723
724 // MSVC searches the current include stack from top to bottom for
725 // headers included by quoted include directives.
726 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000727 if (LangOpts.MSVCCompat && !isAngled) {
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000728 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000729 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000730 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000731 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000732 }
Chris Lattner022923a2009-02-04 19:45:07 +0000733 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000734 }
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000736 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000737
738 if (FromFile) {
739 // We're supposed to start looking from after a particular file. Search
740 // the include path until we find that file or run out of files.
741 const DirectoryLookup *TmpCurDir = CurDir;
742 const DirectoryLookup *TmpFromDir = nullptr;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000743 while (Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +0000744 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000745 Includers, SearchPath, RelativePath, RequestingModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000746 SuggestedModule, /*IsMapped=*/nullptr,
747 /*IsFrameworkFound=*/nullptr, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000748 // Keep looking as if this file did a #include_next.
749 TmpFromDir = TmpCurDir;
750 ++TmpFromDir;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000751 if (&FE->getFileEntry() == FromFile) {
Richard Smith25d50752014-10-20 00:15:49 +0000752 // Found it.
753 FromDir = TmpFromDir;
754 CurDir = TmpCurDir;
755 break;
756 }
757 }
758 }
759
760 // Do a standard file entry lookup.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000761 Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000762 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000763 RelativePath, RequestingModule, SuggestedModule, IsMapped,
764 IsFrameworkFound, SkipCache, BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000765 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000766 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000767 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000768 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
Alex Lorenz4dc55732019-08-22 18:15:50 +0000769 Filename, &FE->getFileEntry());
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000770 return FE;
771 }
Mike Stump11289f42009-09-09 15:08:12 +0000772
Will Wilson0fafd342013-12-27 19:46:16 +0000773 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000774 // Otherwise, see if this is a subframework header. If so, this is relative
775 // to one of the headers on the #include stack. Walk the list of the current
776 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000777 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000778 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000779 if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
780 Filename, CurFileEnt, SearchPath, RelativePath, RequestingModule,
781 SuggestedModule)) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000782 if (SuggestedModule && !LangOpts.AsmPreprocessor)
783 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000784 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
Alex Lorenz4dc55732019-08-22 18:15:50 +0000785 Filename, &FE->getFileEntry());
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000786 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000787 }
788 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000789 }
Mike Stump11289f42009-09-09 15:08:12 +0000790
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000791 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000792 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000793 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000794 if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000795 Filename, CurFileEnt, SearchPath, RelativePath,
Alex Lorenz4dc55732019-08-22 18:15:50 +0000796 RequestingModule, SuggestedModule)) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000797 if (SuggestedModule && !LangOpts.AsmPreprocessor)
798 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000799 RequestingModule, RequestingModuleIsModuleInterface,
Alex Lorenz4dc55732019-08-22 18:15:50 +0000800 FilenameLoc, Filename, &FE->getFileEntry());
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000801 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000802 }
803 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000804 }
805 }
Mike Stump11289f42009-09-09 15:08:12 +0000806
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000807 // Otherwise, we really couldn't find the file.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000808 return None;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000809}
810
Chris Lattnerf64b3522008-03-09 01:54:53 +0000811//===----------------------------------------------------------------------===//
812// Preprocessor Directive Handling.
813//===----------------------------------------------------------------------===//
814
David Blaikied5321242012-06-06 18:52:13 +0000815class Preprocessor::ResetMacroExpansionHelper {
816public:
817 ResetMacroExpansionHelper(Preprocessor *pp)
818 : PP(pp), save(pp->DisableMacroExpansion) {
819 if (pp->MacroExpansionInDirectivesOverride)
820 pp->DisableMacroExpansion = false;
821 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000822
David Blaikied5321242012-06-06 18:52:13 +0000823 ~ResetMacroExpansionHelper() {
824 PP->DisableMacroExpansion = save;
825 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000826
David Blaikied5321242012-06-06 18:52:13 +0000827private:
828 Preprocessor *PP;
829 bool save;
830};
831
Mike Rice58df1af2018-09-11 17:10:44 +0000832/// Process a directive while looking for the through header or a #pragma
833/// hdrstop. The following directives are handled:
834/// #include (to check if it is the through header)
835/// #define (to warn about macros that don't match the PCH)
836/// #pragma (to check for pragma hdrstop).
837/// All other directives are completely discarded.
838void Preprocessor::HandleSkippedDirectiveWhileUsingPCH(Token &Result,
Erich Keane76675de2018-07-05 17:22:13 +0000839 SourceLocation HashLoc) {
840 if (const IdentifierInfo *II = Result.getIdentifierInfo()) {
Mike Rice58df1af2018-09-11 17:10:44 +0000841 if (II->getPPKeywordID() == tok::pp_define) {
Erich Keane76675de2018-07-05 17:22:13 +0000842 return HandleDefineDirective(Result,
843 /*ImmediatelyAfterHeaderGuard=*/false);
Mike Rice58df1af2018-09-11 17:10:44 +0000844 }
845 if (SkippingUntilPCHThroughHeader &&
846 II->getPPKeywordID() == tok::pp_include) {
847 return HandleIncludeDirective(HashLoc, Result);
848 }
849 if (SkippingUntilPragmaHdrStop && II->getPPKeywordID() == tok::pp_pragma) {
Richard Smith75f96812019-04-11 21:18:22 +0000850 Lex(Result);
851 auto *II = Result.getIdentifierInfo();
Mike Rice58df1af2018-09-11 17:10:44 +0000852 if (II && II->getName() == "hdrstop")
Richard Smith75f96812019-04-11 21:18:22 +0000853 return HandlePragmaHdrstop(Result);
Mike Rice58df1af2018-09-11 17:10:44 +0000854 }
Erich Keane76675de2018-07-05 17:22:13 +0000855 }
856 DiscardUntilEndOfDirective();
857}
858
Chris Lattnerf64b3522008-03-09 01:54:53 +0000859/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000860/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000861/// lexer/preprocessor state, and advances the lexer(s) so that the next token
862/// read is the correct one.
863void Preprocessor::HandleDirective(Token &Result) {
864 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000865
Chris Lattnerf64b3522008-03-09 01:54:53 +0000866 // We just parsed a # character at the start of a line, so we're in directive
867 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000868 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000869 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000870 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000871
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000872 bool ImmediatelyAfterTopLevelIfndef =
873 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
874 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
875
Chris Lattnerf64b3522008-03-09 01:54:53 +0000876 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000877
Chris Lattnerf64b3522008-03-09 01:54:53 +0000878 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000879 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000880 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000881 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000882
Chris Lattner2d17ab72009-03-18 21:00:25 +0000883 // Save the '#' token in case we need to return it later.
884 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000885
Chris Lattnerf64b3522008-03-09 01:54:53 +0000886 // Read the next token, the directive flavor. This isn't expanded due to
887 // C99 6.10.3p8.
888 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000889
Chris Lattnerf64b3522008-03-09 01:54:53 +0000890 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
891 // #define A(x) #x
892 // A(abc
893 // #warning blah
894 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000895 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
896 // not support this for #include-like directives, since that can result in
897 // terrible diagnostics, and does not work in GCC.
898 if (InMacroArgs) {
899 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
900 switch (II->getPPKeywordID()) {
901 case tok::pp_include:
902 case tok::pp_import:
903 case tok::pp_include_next:
904 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000905 case tok::pp_pragma:
906 Diag(Result, diag::err_embedded_directive) << II->getName();
Nico Weber023dd1e2019-02-14 04:13:17 +0000907 Diag(*ArgMacro, diag::note_macro_expansion_here)
908 << ArgMacro->getIdentifierInfo();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000909 DiscardUntilEndOfDirective();
910 return;
911 default:
912 break;
913 }
914 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000915 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000916 }
Mike Stump11289f42009-09-09 15:08:12 +0000917
David Blaikied5321242012-06-06 18:52:13 +0000918 // Temporarily enable macro expansion if set so
919 // and reset to previous state when returning from this function.
920 ResetMacroExpansionHelper helper(this);
921
Mike Rice58df1af2018-09-11 17:10:44 +0000922 if (SkippingUntilPCHThroughHeader || SkippingUntilPragmaHdrStop)
923 return HandleSkippedDirectiveWhileUsingPCH(Result, SavedHash.getLocation());
Erich Keane76675de2018-07-05 17:22:13 +0000924
Chris Lattnerf64b3522008-03-09 01:54:53 +0000925 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000926 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000927 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000928 case tok::code_completion:
929 if (CodeComplete)
930 CodeComplete->CodeCompleteDirective(
931 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000932 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000933 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000934 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000935 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000936 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000937 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000938 default:
939 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000940 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattnerf64b3522008-03-09 01:54:53 +0000942 // Ask what the preprocessor keyword ID is.
943 switch (II->getPPKeywordID()) {
944 default: break;
945 // C99 6.10.1 - Conditional Inclusion.
946 case tok::pp_if:
Vedant Kumar3919a502017-09-11 20:47:42 +0000947 return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000948 case tok::pp_ifdef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000949 return HandleIfdefDirective(Result, SavedHash, false,
950 true /*not valid for miopt*/);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000951 case tok::pp_ifndef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000952 return HandleIfdefDirective(Result, SavedHash, true,
953 ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000954 case tok::pp_elif:
Vedant Kumar3919a502017-09-11 20:47:42 +0000955 return HandleElifDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000956 case tok::pp_else:
Vedant Kumar3919a502017-09-11 20:47:42 +0000957 return HandleElseDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000958 case tok::pp_endif:
959 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chris Lattnerf64b3522008-03-09 01:54:53 +0000961 // C99 6.10.2 - Source File Inclusion.
962 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000963 // Handle #include.
964 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000965 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000966 // Handle -imacros.
Taewook Oh755e4d22016-06-13 21:55:33 +0000967 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattnerf64b3522008-03-09 01:54:53 +0000969 // C99 6.10.3 - Macro Replacement.
970 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000971 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000972 case tok::pp_undef:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000973 return HandleUndefDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000974
975 // C99 6.10.4 - Line Control.
976 case tok::pp_line:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000977 return HandleLineDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattnerf64b3522008-03-09 01:54:53 +0000979 // C99 6.10.5 - Error Directive.
980 case tok::pp_error:
981 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000982
Chris Lattnerf64b3522008-03-09 01:54:53 +0000983 // C99 6.10.6 - Pragma Directive.
984 case tok::pp_pragma:
Joel E. Dennyddde0ec2019-05-21 23:51:38 +0000985 return HandlePragmaDirective({PIK_HashPragma, SavedHash.getLocation()});
Mike Stump11289f42009-09-09 15:08:12 +0000986
Chris Lattnerf64b3522008-03-09 01:54:53 +0000987 // GNU Extensions.
988 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000989 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000990 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000991 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000992
Chris Lattnerf64b3522008-03-09 01:54:53 +0000993 case tok::pp_warning:
994 Diag(Result, diag::ext_pp_warning_directive);
995 return HandleUserDiagnosticDirective(Result, true);
996 case tok::pp_ident:
997 return HandleIdentSCCSDirective(Result);
998 case tok::pp_sccs:
999 return HandleIdentSCCSDirective(Result);
1000 case tok::pp_assert:
1001 //isExtension = true; // FIXME: implement #assert
1002 break;
1003 case tok::pp_unassert:
1004 //isExtension = true; // FIXME: implement #unassert
1005 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001006
Douglas Gregor663b48f2012-01-03 19:48:16 +00001007 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001008 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001009 return HandleMacroPublicDirective(Result);
1010 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001011
Douglas Gregor663b48f2012-01-03 19:48:16 +00001012 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001013 if (getLangOpts().Modules)
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001014 return HandleMacroPrivateDirective();
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001015 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001016 }
1017 break;
1018 }
Mike Stump11289f42009-09-09 15:08:12 +00001019
Chris Lattner2d17ab72009-03-18 21:00:25 +00001020 // If this is a .S file, treat unknown # directives as non-preprocessor
1021 // directives. This is important because # may be a comment or introduce
1022 // various pseudo-ops. Just return the # token and push back the following
1023 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001024 if (getLangOpts().AsmPreprocessor) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001025 auto Toks = std::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001026 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001027 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001028 Toks[1] = Result;
Taewook Oh755e4d22016-06-13 21:55:33 +00001029
Chris Lattner56f64c12011-01-06 05:01:51 +00001030 // If the second token is a hashhash token, then we need to translate it to
1031 // unknown so the token lexer doesn't try to perform token pasting.
1032 if (Result.is(tok::hashhash))
1033 Toks[1].setKind(tok::unknown);
Taewook Oh755e4d22016-06-13 21:55:33 +00001034
Chris Lattner2d17ab72009-03-18 21:00:25 +00001035 // Enter this token stream so that we re-lex the tokens. Make sure to
1036 // enable macro expansion, in case the token after the # is an identifier
1037 // that is expanded.
Ilya Biryukov929af672019-05-17 09:32:05 +00001038 EnterTokenStream(std::move(Toks), 2, false, /*IsReinject*/false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001039 return;
1040 }
Mike Stump11289f42009-09-09 15:08:12 +00001041
Chris Lattnerf64b3522008-03-09 01:54:53 +00001042 // If we reached here, the preprocessing token is not valid!
1043 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001044
Chris Lattnerf64b3522008-03-09 01:54:53 +00001045 // Read the rest of the PP line.
1046 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattnerf64b3522008-03-09 01:54:53 +00001048 // Okay, we're done parsing the directive.
1049}
1050
Chris Lattner76e68962009-01-26 06:19:46 +00001051/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1052/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1053static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001054 unsigned DiagID, Preprocessor &PP,
1055 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001056 if (DigitTok.isNot(tok::numeric_constant)) {
1057 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001058
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001059 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001060 PP.DiscardUntilEndOfDirective();
1061 return true;
1062 }
Mike Stump11289f42009-09-09 15:08:12 +00001063
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001064 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001065 IntegerBuffer.resize(DigitTok.getLength());
1066 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001067 bool Invalid = false;
1068 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1069 if (Invalid)
1070 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001071
Chris Lattnerd66f1722009-04-18 18:35:15 +00001072 // Verify that we have a simple digit-sequence, and compute the value. This
1073 // is always a simple digit string computed in decimal, so we do this manually
1074 // here.
1075 Val = 0;
1076 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001077 // C++1y [lex.fcon]p1:
1078 // Optional separating single quotes in a digit-sequence are ignored
1079 if (DigitTokBegin[i] == '\'')
1080 continue;
1081
Jordan Rosea7d03842013-02-08 22:30:41 +00001082 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001083 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001084 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001085 PP.DiscardUntilEndOfDirective();
1086 return true;
1087 }
Mike Stump11289f42009-09-09 15:08:12 +00001088
Chris Lattnerd66f1722009-04-18 18:35:15 +00001089 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1090 if (NextVal < Val) { // overflow.
1091 PP.Diag(DigitTok, DiagID);
1092 PP.DiscardUntilEndOfDirective();
1093 return true;
1094 }
1095 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001096 }
Mike Stump11289f42009-09-09 15:08:12 +00001097
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001098 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001099 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1100 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001101
Chris Lattner76e68962009-01-26 06:19:46 +00001102 return false;
1103}
1104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001105/// Handle a \#line directive: C99 6.10.4.
James Dennettf6333ac2012-06-22 05:46:07 +00001106///
1107/// The two acceptable forms are:
1108/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001109/// # line digit-sequence
1110/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001111/// \endverbatim
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001112void Preprocessor::HandleLineDirective() {
Chris Lattner100c65e2009-01-26 05:29:08 +00001113 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1114 // expanded.
1115 Token DigitTok;
1116 Lex(DigitTok);
1117
Chris Lattner100c65e2009-01-26 05:29:08 +00001118 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001119 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001120 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001121 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001122
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001123 if (LineNo == 0)
1124 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001125
Chris Lattner76e68962009-01-26 06:19:46 +00001126 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1127 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001128 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001129 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001130 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001131 if (LineNo >= LineLimit)
1132 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001133 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001134 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001135
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001136 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001137 Token StrTok;
1138 Lex(StrTok);
1139
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001140 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1141 // string followed by eod.
1142 if (StrTok.is(tok::eod))
Chandler Carruthd92d70b2019-01-19 06:36:00 +00001143 ; // ok
1144 else if (StrTok.isNot(tok::string_literal)) {
1145 Diag(StrTok, diag::err_pp_line_invalid_filename);
1146 DiscardUntilEndOfDirective();
1147 return;
1148 } else if (StrTok.hasUDSuffix()) {
1149 Diag(StrTok, diag::err_invalid_string_udl);
1150 DiscardUntilEndOfDirective();
1151 return;
1152 } else {
1153 // Parse and validate the string, converting it into a unique ID.
1154 StringLiteralParser Literal(StrTok, *this);
1155 assert(Literal.isAscii() && "Didn't allow wide strings in");
1156 if (Literal.hadError) {
1157 DiscardUntilEndOfDirective();
1158 return;
1159 }
1160 if (Literal.Pascal) {
1161 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1162 DiscardUntilEndOfDirective();
1163 return;
1164 }
1165 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1166
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001167 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001168 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1169 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001170 }
Mike Stump11289f42009-09-09 15:08:12 +00001171
Reid Klecknereb00ee02017-05-22 21:42:58 +00001172 // Take the file kind of the file containing the #line directive. #line
1173 // directives are often used for generated sources from the same codebase, so
1174 // the new file should generally be classified the same way as the current
1175 // file. This is visible in GCC's pre-processed output, which rewrites #line
1176 // to GNU line markers.
1177 SrcMgr::CharacteristicKind FileKind =
1178 SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1179
1180 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1181 false, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001182
Chris Lattner839150e2009-03-27 17:13:49 +00001183 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001184 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Reid Klecknereb00ee02017-05-22 21:42:58 +00001185 PPCallbacks::RenameFile, FileKind);
Chris Lattner100c65e2009-01-26 05:29:08 +00001186}
1187
Chris Lattner76e68962009-01-26 06:19:46 +00001188/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1189/// marker directive.
1190static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
Reid Klecknereb00ee02017-05-22 21:42:58 +00001191 SrcMgr::CharacteristicKind &FileKind,
Chris Lattner76e68962009-01-26 06:19:46 +00001192 Preprocessor &PP) {
1193 unsigned FlagVal;
1194 Token FlagTok;
1195 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001196 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001197 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1198 return true;
1199
1200 if (FlagVal == 1) {
1201 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001202
Chris Lattner76e68962009-01-26 06:19:46 +00001203 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001204 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001205 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1206 return true;
1207 } else if (FlagVal == 2) {
1208 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001209
Chris Lattner1c967782009-02-04 06:25:26 +00001210 SourceManager &SM = PP.getSourceManager();
1211 // If we are leaving the current presumed file, check to make sure the
1212 // presumed include stack isn't empty!
1213 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001214 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001215 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001216 if (PLoc.isInvalid())
1217 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001218
Chris Lattner1c967782009-02-04 06:25:26 +00001219 // If there is no include loc (main file) or if the include loc is in a
1220 // different physical file, then we aren't in a "1" line marker flag region.
1221 SourceLocation IncLoc = PLoc.getIncludeLoc();
1222 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001223 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001224 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1225 PP.DiscardUntilEndOfDirective();
1226 return true;
1227 }
Mike Stump11289f42009-09-09 15:08:12 +00001228
Chris Lattner76e68962009-01-26 06:19:46 +00001229 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001230 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001231 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1232 return true;
1233 }
1234
1235 // We must have 3 if there are still flags.
1236 if (FlagVal != 3) {
1237 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001238 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001239 return true;
1240 }
Mike Stump11289f42009-09-09 15:08:12 +00001241
Reid Klecknereb00ee02017-05-22 21:42:58 +00001242 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001243
Chris Lattner76e68962009-01-26 06:19:46 +00001244 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001245 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001246 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001247 return true;
1248
1249 // We must have 4 if there is yet another flag.
1250 if (FlagVal != 4) {
1251 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001252 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001253 return true;
1254 }
Mike Stump11289f42009-09-09 15:08:12 +00001255
Reid Klecknereb00ee02017-05-22 21:42:58 +00001256 FileKind = SrcMgr::C_ExternCSystem;
Mike Stump11289f42009-09-09 15:08:12 +00001257
Chris Lattner76e68962009-01-26 06:19:46 +00001258 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001259 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001260
1261 // There are no more valid flags here.
1262 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001263 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001264 return true;
1265}
1266
1267/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1268/// one of the following forms:
1269///
1270/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001271/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001272/// # 42 "file" ('1' | '2')? '3' '4'?
1273///
1274void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1275 // Validate the number and convert it to an unsigned. GNU does not have a
1276 // line # limit other than it fit in 32-bits.
1277 unsigned LineNo;
1278 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001279 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001280 return;
Mike Stump11289f42009-09-09 15:08:12 +00001281
Chris Lattner76e68962009-01-26 06:19:46 +00001282 Token StrTok;
1283 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001284
Chris Lattner76e68962009-01-26 06:19:46 +00001285 bool IsFileEntry = false, IsFileExit = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001286 int FilenameID = -1;
Reid Klecknereb00ee02017-05-22 21:42:58 +00001287 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001288
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001289 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1290 // string followed by eod.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001291 if (StrTok.is(tok::eod)) {
1292 // Treat this like "#line NN", which doesn't change file characteristics.
Chandler Carruthd92d70b2019-01-19 06:36:00 +00001293 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1294 } else if (StrTok.isNot(tok::string_literal)) {
1295 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1296 DiscardUntilEndOfDirective();
1297 return;
1298 } else if (StrTok.hasUDSuffix()) {
1299 Diag(StrTok, diag::err_invalid_string_udl);
1300 DiscardUntilEndOfDirective();
1301 return;
1302 } else {
1303 // Parse and validate the string, converting it into a unique ID.
1304 StringLiteralParser Literal(StrTok, *this);
1305 assert(Literal.isAscii() && "Didn't allow wide strings in");
1306 if (Literal.hadError) {
1307 DiscardUntilEndOfDirective();
1308 return;
1309 }
1310 if (Literal.Pascal) {
1311 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1312 DiscardUntilEndOfDirective();
1313 return;
1314 }
1315 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1316
Chris Lattner76e68962009-01-26 06:19:46 +00001317 // If a filename was present, read any flags that are present.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001318 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001319 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001320 }
Mike Stump11289f42009-09-09 15:08:12 +00001321
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001322 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001323 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1324 IsFileExit, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001325
Chris Lattner839150e2009-03-27 17:13:49 +00001326 // If the preprocessor has callbacks installed, notify them of the #line
1327 // change. This is used so that the line marker comes out in -E mode for
1328 // example.
1329 if (Callbacks) {
1330 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1331 if (IsFileEntry)
1332 Reason = PPCallbacks::EnterFile;
1333 else if (IsFileExit)
1334 Reason = PPCallbacks::ExitFile;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Chris Lattnerc745cec2010-04-14 04:28:50 +00001336 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001337 }
Chris Lattner76e68962009-01-26 06:19:46 +00001338}
1339
Chris Lattner38d7fd22009-01-26 05:30:54 +00001340/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1341///
Mike Stump11289f42009-09-09 15:08:12 +00001342void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001343 bool isWarning) {
1344 // Read the rest of the line raw. We do this because we don't want macros
1345 // to be expanded and we don't require that the tokens be valid preprocessing
1346 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001347 // collapse multiple consecutive white space between tokens, but this isn't
Chris Lattnerf64b3522008-03-09 01:54:53 +00001348 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001349 SmallString<128> Message;
1350 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001351
1352 // Find the first non-whitespace character, so that we can make the
1353 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001354 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001355
Chris Lattner100c65e2009-01-26 05:29:08 +00001356 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001357 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001358 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001359 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001360}
1361
1362/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1363///
1364void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1365 // Yes, this directive is an extension.
1366 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001367
Chris Lattnerf64b3522008-03-09 01:54:53 +00001368 // Read the string argument.
1369 Token StrTok;
1370 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001371
Chris Lattnerf64b3522008-03-09 01:54:53 +00001372 // If the token kind isn't a string, it's a malformed directive.
1373 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001374 StrTok.isNot(tok::wide_string_literal)) {
1375 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001376 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001377 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001378 return;
1379 }
Chandler Carruthd92d70b2019-01-19 06:36:00 +00001380
1381 if (StrTok.hasUDSuffix()) {
1382 Diag(StrTok, diag::err_invalid_string_udl);
1383 DiscardUntilEndOfDirective();
1384 return;
1385 }
1386
1387 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001388 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001389
Douglas Gregordc970f02010-03-16 22:30:13 +00001390 if (Callbacks) {
1391 bool Invalid = false;
1392 std::string Str = getSpelling(StrTok, &Invalid);
1393 if (!Invalid)
1394 Callbacks->Ident(Tok.getLocation(), Str);
1395 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001396}
1397
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001398/// Handle a #public directive.
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001399void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001400 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001401 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001402
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001403 // Error reading macro name? If so, diagnostic already issued.
1404 if (MacroNameTok.is(tok::eod))
1405 return;
1406
Douglas Gregor663b48f2012-01-03 19:48:16 +00001407 // Check to see if this is the last token on the #__public_macro line.
1408 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001409
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001410 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001411 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001412 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001413
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001414 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001415 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001416 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001417 return;
1418 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001419
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001420 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001421 appendMacroDirective(II, AllocateVisibilityMacroDirective(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001422 MacroNameTok.getLocation(), /*isPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001423}
1424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001425/// Handle a #private directive.
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001426void Preprocessor::HandleMacroPrivateDirective() {
Douglas Gregorebf00492011-10-17 15:32:29 +00001427 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001428 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001429
Douglas Gregorebf00492011-10-17 15:32:29 +00001430 // Error reading macro name? If so, diagnostic already issued.
1431 if (MacroNameTok.is(tok::eod))
1432 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001433
Douglas Gregor663b48f2012-01-03 19:48:16 +00001434 // Check to see if this is the last token on the #__private_macro line.
1435 CheckEndOfDirective("__private_macro");
Taewook Oh755e4d22016-06-13 21:55:33 +00001436
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001437 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001438 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001439 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001440
Douglas Gregorebf00492011-10-17 15:32:29 +00001441 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001442 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001443 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001444 return;
1445 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001446
Douglas Gregorebf00492011-10-17 15:32:29 +00001447 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001448 appendMacroDirective(II, AllocateVisibilityMacroDirective(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001449 MacroNameTok.getLocation(), /*isPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001450}
1451
Chris Lattnerf64b3522008-03-09 01:54:53 +00001452//===----------------------------------------------------------------------===//
1453// Preprocessor Include Directive Handling.
1454//===----------------------------------------------------------------------===//
1455
1456/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001457/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001458/// true if the input filename was in <>'s or false if it were in ""'s. The
1459/// caller is expected to provide a buffer that is large enough to hold the
1460/// spelling of the filename, but is also expected to handle the case when
1461/// this method decides to use a different buffer.
1462bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001463 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001464 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001465 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001466
Richard Smith91e150d2019-03-19 22:09:55 +00001467 // FIXME: Consider warning on some of the cases described in C11 6.4.7/3 and
1468 // C++20 [lex.header]/2:
1469 //
1470 // If `"`, `'`, `\`, `/*`, or `//` appears in a header-name, then
1471 // in C: behavior is undefined
1472 // in C++: program is conditionally-supported with implementation-defined
1473 // semantics
1474
Chris Lattnerf64b3522008-03-09 01:54:53 +00001475 // Make sure the filename is <x> or "x".
1476 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001477 if (Buffer[0] == '<') {
1478 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001479 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001480 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001481 return true;
1482 }
1483 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001484 } else if (Buffer[0] == '"') {
1485 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001486 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001487 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001488 return true;
1489 }
1490 isAngled = false;
1491 } else {
1492 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001493 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001494 return true;
1495 }
Mike Stump11289f42009-09-09 15:08:12 +00001496
Chris Lattnerf64b3522008-03-09 01:54:53 +00001497 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001498 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001499 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001500 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001501 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001502 }
Mike Stump11289f42009-09-09 15:08:12 +00001503
Chris Lattnerf64b3522008-03-09 01:54:53 +00001504 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001505 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001506 return isAngled;
1507}
1508
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001509/// Push a token onto the token stream containing an annotation.
Richard Smithc51c38b2017-04-29 00:34:47 +00001510void Preprocessor::EnterAnnotationToken(SourceRange Range,
1511 tok::TokenKind Kind,
1512 void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001513 // FIXME: Produce this as the current token directly, rather than
1514 // allocating a new token for it.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001515 auto Tok = std::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001516 Tok[0].startToken();
1517 Tok[0].setKind(Kind);
Richard Smithc51c38b2017-04-29 00:34:47 +00001518 Tok[0].setLocation(Range.getBegin());
1519 Tok[0].setAnnotationEndLoc(Range.getEnd());
Richard Smith34f30512013-11-23 04:06:09 +00001520 Tok[0].setAnnotationValue(AnnotationVal);
Ilya Biryukov929af672019-05-17 09:32:05 +00001521 EnterTokenStream(std::move(Tok), 1, true, /*IsReinject*/ false);
Richard Smith34f30512013-11-23 04:06:09 +00001522}
1523
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001524/// Produce a diagnostic informing the user that a #include or similar
Richard Smith63b6fce2015-05-18 04:45:41 +00001525/// was implicitly treated as a module import.
1526static void diagnoseAutoModuleImport(
1527 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1528 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1529 SourceLocation PathEnd) {
Richard Smith8af8b862019-04-11 21:18:23 +00001530 StringRef ImportKeyword;
1531 if (PP.getLangOpts().ObjC)
1532 ImportKeyword = "@import";
1533 else if (PP.getLangOpts().ModulesTS || PP.getLangOpts().CPlusPlusModules)
1534 ImportKeyword = "import";
1535 else
1536 return; // no import syntax available
Richard Smith63b6fce2015-05-18 04:45:41 +00001537
1538 SmallString<128> PathString;
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001539 for (size_t I = 0, N = Path.size(); I != N; ++I) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001540 if (I)
1541 PathString += '.';
1542 PathString += Path[I].first->getName();
1543 }
1544 int IncludeKind = 0;
Taewook Oh755e4d22016-06-13 21:55:33 +00001545
Richard Smith63b6fce2015-05-18 04:45:41 +00001546 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1547 case tok::pp_include:
1548 IncludeKind = 0;
1549 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001550
Richard Smith63b6fce2015-05-18 04:45:41 +00001551 case tok::pp_import:
1552 IncludeKind = 1;
Taewook Oh755e4d22016-06-13 21:55:33 +00001553 break;
1554
Richard Smith63b6fce2015-05-18 04:45:41 +00001555 case tok::pp_include_next:
1556 IncludeKind = 2;
1557 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001558
Richard Smith63b6fce2015-05-18 04:45:41 +00001559 case tok::pp___include_macros:
1560 IncludeKind = 3;
1561 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001562
Richard Smith63b6fce2015-05-18 04:45:41 +00001563 default:
1564 llvm_unreachable("unknown include directive kind");
1565 }
1566
1567 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1568 /*IsTokenRange=*/false);
1569 PP.Diag(HashLoc, diag::warn_auto_module_import)
1570 << IncludeKind << PathString
Richard Smith8af8b862019-04-11 21:18:23 +00001571 << FixItHint::CreateReplacement(
1572 ReplaceRange, (ImportKeyword + " " + PathString + ";").str());
Richard Smith63b6fce2015-05-18 04:45:41 +00001573}
1574
Taewook Ohf42103c2016-06-13 20:40:21 +00001575// Given a vector of path components and a string containing the real
1576// path to the file, build a properly-cased replacement in the vector,
1577// and return true if the replacement should be suggested.
1578static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1579 StringRef RealPathName) {
1580 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1581 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1582 int Cnt = 0;
1583 bool SuggestReplacement = false;
1584 // Below is a best-effort to handle ".." in paths. It is admittedly
1585 // not 100% correct in the presence of symlinks.
1586 for (auto &Component : llvm::reverse(Components)) {
1587 if ("." == Component) {
1588 } else if (".." == Component) {
1589 ++Cnt;
1590 } else if (Cnt) {
1591 --Cnt;
1592 } else if (RealPathComponentIter != RealPathComponentEnd) {
1593 if (Component != *RealPathComponentIter) {
1594 // If these path components differ by more than just case, then we
1595 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1596 // noisy false positives.
1597 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1598 if (!SuggestReplacement)
1599 break;
1600 Component = *RealPathComponentIter;
1601 }
1602 ++RealPathComponentIter;
1603 }
1604 }
1605 return SuggestReplacement;
1606}
1607
Richard Smith27e5aa02017-06-05 18:57:56 +00001608bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
1609 const TargetInfo &TargetInfo,
1610 DiagnosticsEngine &Diags, Module *M) {
1611 Module::Requirement Requirement;
1612 Module::UnresolvedHeaderDirective MissingHeader;
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00001613 Module *ShadowingModule = nullptr;
1614 if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
1615 ShadowingModule))
Richard Smith27e5aa02017-06-05 18:57:56 +00001616 return false;
1617
1618 if (MissingHeader.FileNameLoc.isValid()) {
1619 Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1620 << MissingHeader.IsUmbrella << MissingHeader.FileName;
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00001621 } else if (ShadowingModule) {
1622 Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name;
1623 Diags.Report(ShadowingModule->DefinitionLoc,
1624 diag::note_previous_definition);
Richard Smith27e5aa02017-06-05 18:57:56 +00001625 } else {
1626 // FIXME: Track the location at which the requirement was specified, and
1627 // use it here.
1628 Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
1629 << M->getFullModuleName() << Requirement.second << Requirement.first;
1630 }
1631 return true;
1632}
1633
James Dennettf6333ac2012-06-22 05:46:07 +00001634/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1635/// the file to be included from the lexer, then include it! This is a common
1636/// routine with functionality shared between \#include, \#include_next and
1637/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001638/// specifies the file to start searching from.
Taewook Oh755e4d22016-06-13 21:55:33 +00001639void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001640 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001641 const DirectoryLookup *LookupFrom,
Richard Smith8af8b862019-04-11 21:18:23 +00001642 const FileEntry *LookupFromFile) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001643 Token FilenameTok;
Richard Smithb9b05102019-03-19 01:51:19 +00001644 if (LexHeaderName(FilenameTok))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001645 return;
Mike Stump11289f42009-09-09 15:08:12 +00001646
Richard Smith91e150d2019-03-19 22:09:55 +00001647 if (FilenameTok.isNot(tok::header_name)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001648 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
Richard Smithb9b05102019-03-19 01:51:19 +00001649 if (FilenameTok.isNot(tok::eod))
1650 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001651 return;
1652 }
Mike Stump11289f42009-09-09 15:08:12 +00001653
Richard Smith8af8b862019-04-11 21:18:23 +00001654 // Verify that there is nothing after the filename, other than EOD. Note
1655 // that we allow macros that expand to nothing after the filename, because
1656 // this falls into the category of "#include pp-tokens new-line" specified
1657 // in C99 6.10.2p4.
1658 SourceLocation EndLoc =
1659 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
1660
1661 auto Action = HandleHeaderIncludeOrImport(HashLoc, IncludeTok, FilenameTok,
1662 EndLoc, LookupFrom, LookupFromFile);
1663 switch (Action.Kind) {
1664 case ImportAction::None:
Richard Smithd652bdd2019-04-14 08:06:59 +00001665 case ImportAction::SkippedModuleImport:
Richard Smith8af8b862019-04-11 21:18:23 +00001666 break;
1667 case ImportAction::ModuleBegin:
1668 EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
1669 tok::annot_module_begin, Action.ModuleForHeader);
1670 break;
1671 case ImportAction::ModuleImport:
1672 EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
1673 tok::annot_module_include, Action.ModuleForHeader);
1674 break;
1675 }
1676}
1677
Alex Lorenz4dc55732019-08-22 18:15:50 +00001678Optional<FileEntryRef> Preprocessor::LookupHeaderIncludeOrImport(
1679 const DirectoryLookup *&CurDir, StringRef Filename,
1680 SourceLocation FilenameLoc, CharSourceRange FilenameRange,
1681 const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
1682 bool &IsMapped, const DirectoryLookup *LookupFrom,
1683 const FileEntry *LookupFromFile, SmallString<128> &NormalizedPath,
1684 SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
1685 ModuleMap::KnownHeader &SuggestedModule, bool isAngled) {
1686 Optional<FileEntryRef> File = LookupFile(
1687 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
1688 isAngled, LookupFrom, LookupFromFile, CurDir,
1689 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1690 &SuggestedModule, &IsMapped, &IsFrameworkFound);
1691 if (File)
1692 return File;
1693
1694 if (Callbacks) {
1695 // Give the clients a chance to recover.
1696 SmallString<128> RecoveryPath;
1697 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1698 if (auto DE = FileMgr.getDirectory(RecoveryPath)) {
1699 // Add the recovery path to the list of search paths.
1700 DirectoryLookup DL(*DE, SrcMgr::C_User, false);
1701 HeaderInfo.AddSearchPath(DL, isAngled);
1702
1703 // Try the lookup again, skipping the cache.
1704 Optional<FileEntryRef> File = LookupFile(
1705 FilenameLoc,
1706 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1707 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
1708 &SuggestedModule, &IsMapped, /*IsFrameworkFound=*/nullptr,
1709 /*SkipCache*/ true);
1710 if (File)
1711 return File;
1712 }
1713 }
1714 }
1715
1716 if (SuppressIncludeNotFoundError)
1717 return None;
1718
1719 // If the file could not be located and it was included via angle
1720 // brackets, we can attempt a lookup as though it were a quoted path to
1721 // provide the user with a possible fixit.
1722 if (isAngled) {
1723 Optional<FileEntryRef> File = LookupFile(
1724 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
1725 false, LookupFrom, LookupFromFile, CurDir,
1726 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1727 &SuggestedModule, &IsMapped,
1728 /*IsFrameworkFound=*/nullptr);
1729 if (File) {
1730 Diag(FilenameTok, diag::err_pp_file_not_found_angled_include_not_fatal)
1731 << Filename << IsImportDecl
1732 << FixItHint::CreateReplacement(FilenameRange,
1733 "\"" + Filename.str() + "\"");
1734 return File;
1735 }
1736 }
1737
1738 // Check for likely typos due to leading or trailing non-isAlphanumeric
1739 // characters
1740 StringRef OriginalFilename = Filename;
1741 if (LangOpts.SpellChecking) {
1742 // A heuristic to correct a typo file name by removing leading and
1743 // trailing non-isAlphanumeric characters.
1744 auto CorrectTypoFilename = [](llvm::StringRef Filename) {
1745 Filename = Filename.drop_until(isAlphanumeric);
1746 while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
1747 Filename = Filename.drop_back();
1748 }
1749 return Filename;
1750 };
1751 StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
1752 SmallString<128> NormalizedTypoCorrectionPath;
1753 if (LangOpts.MSVCCompat) {
1754 NormalizedTypoCorrectionPath = TypoCorrectionName.str();
1755#ifndef _WIN32
1756 llvm::sys::path::native(NormalizedTypoCorrectionPath);
1757#endif
1758 }
1759 Optional<FileEntryRef> File = LookupFile(
1760 FilenameLoc,
1761 LangOpts.MSVCCompat ? NormalizedTypoCorrectionPath.c_str()
1762 : TypoCorrectionName,
1763 isAngled, LookupFrom, LookupFromFile, CurDir,
1764 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1765 &SuggestedModule, &IsMapped,
1766 /*IsFrameworkFound=*/nullptr);
1767 if (File) {
1768 auto Hint =
1769 isAngled ? FixItHint::CreateReplacement(
1770 FilenameRange, "<" + TypoCorrectionName.str() + ">")
1771 : FixItHint::CreateReplacement(
1772 FilenameRange, "\"" + TypoCorrectionName.str() + "\"");
1773 Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
1774 << OriginalFilename << TypoCorrectionName << Hint;
1775 // We found the file, so set the Filename to the name after typo
1776 // correction.
1777 Filename = TypoCorrectionName;
1778 return File;
1779 }
1780 }
1781
1782 // If the file is still not found, just go with the vanilla diagnostic
1783 assert(!File.hasValue() && "expected missing file");
1784 Diag(FilenameTok, diag::err_pp_file_not_found)
1785 << OriginalFilename << FilenameRange;
1786 if (IsFrameworkFound) {
1787 size_t SlashPos = OriginalFilename.find('/');
1788 assert(SlashPos != StringRef::npos &&
1789 "Include with framework name should have '/' in the filename");
1790 StringRef FrameworkName = OriginalFilename.substr(0, SlashPos);
1791 FrameworkCacheEntry &CacheEntry =
1792 HeaderInfo.LookupFrameworkCache(FrameworkName);
1793 assert(CacheEntry.Directory && "Found framework should be in cache");
1794 Diag(FilenameTok, diag::note_pp_framework_without_header)
1795 << OriginalFilename.substr(SlashPos + 1) << FrameworkName
1796 << CacheEntry.Directory->getName();
1797 }
1798
1799 return None;
1800}
1801
Richard Smith8af8b862019-04-11 21:18:23 +00001802/// Handle either a #include-like directive or an import declaration that names
1803/// a header file.
1804///
1805/// \param HashLoc The location of the '#' token for an include, or
1806/// SourceLocation() for an import declaration.
1807/// \param IncludeTok The include / include_next / import token.
1808/// \param FilenameTok The header-name token.
1809/// \param EndLoc The location at which any imported macros become visible.
1810/// \param LookupFrom For #include_next, the starting directory for the
1811/// directory lookup.
1812/// \param LookupFromFile For #include_next, the starting file for the directory
1813/// lookup.
1814Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
1815 SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok,
1816 SourceLocation EndLoc, const DirectoryLookup *LookupFrom,
1817 const FileEntry *LookupFromFile) {
Richard Smithb9b05102019-03-19 01:51:19 +00001818 SmallString<128> FilenameBuffer;
1819 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer);
1820 SourceLocation CharEnd = FilenameTok.getEndLoc();
1821
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001822 CharSourceRange FilenameRange
1823 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001824 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001825 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001826 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Richard Smith8af8b862019-04-11 21:18:23 +00001827
Chris Lattnerf64b3522008-03-09 01:54:53 +00001828 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1829 // error.
Richard Smith8af8b862019-04-11 21:18:23 +00001830 if (Filename.empty())
1831 return {ImportAction::None};
Mike Stump11289f42009-09-09 15:08:12 +00001832
Richard Smith8af8b862019-04-11 21:18:23 +00001833 bool IsImportDecl = HashLoc.isInvalid();
1834 SourceLocation StartLoc = IsImportDecl ? IncludeTok.getLocation() : HashLoc;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001835
John McCall32f5fe12011-09-30 05:12:12 +00001836 // Complain about attempts to #include files in an audit pragma.
1837 if (PragmaARCCFCodeAuditedLoc.isValid()) {
Richard Smith8af8b862019-04-11 21:18:23 +00001838 Diag(StartLoc, diag::err_pp_include_in_arc_cf_code_audited) << IsImportDecl;
John McCall32f5fe12011-09-30 05:12:12 +00001839 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1840
1841 // Immediately leave the pragma.
1842 PragmaARCCFCodeAuditedLoc = SourceLocation();
1843 }
1844
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001845 // Complain about attempts to #include files in an assume-nonnull pragma.
1846 if (PragmaAssumeNonNullLoc.isValid()) {
Richard Smith8af8b862019-04-11 21:18:23 +00001847 Diag(StartLoc, diag::err_pp_include_in_assume_nonnull) << IsImportDecl;
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001848 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1849
1850 // Immediately leave the pragma.
1851 PragmaAssumeNonNullLoc = SourceLocation();
1852 }
1853
Aaron Ballman611306e2012-03-02 22:51:54 +00001854 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001855 // Map the filename with the brackets still attached. If the name doesn't
1856 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001857 // spelling for.
1858 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1859 if (!NewName.empty())
1860 Filename = NewName;
1861 }
1862
Chris Lattnerf64b3522008-03-09 01:54:53 +00001863 // Search include directories.
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001864 bool IsMapped = false;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001865 bool IsFrameworkFound = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001866 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001867 SmallString<1024> SearchPath;
1868 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001869 // We get the raw path only if we have 'Callbacks' to which we later pass
1870 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001871 ModuleMap::KnownHeader SuggestedModule;
1872 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001873 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001874 if (LangOpts.MSVCCompat) {
1875 NormalizedPath = Filename.str();
Nico Weber1865df42018-04-27 19:11:14 +00001876#ifndef _WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001877 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001878#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001879 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001880
Alex Lorenz4dc55732019-08-22 18:15:50 +00001881 Optional<FileEntryRef> File = LookupHeaderIncludeOrImport(
1882 CurDir, Filename, FilenameLoc, FilenameRange, FilenameTok,
1883 IsFrameworkFound, IsImportDecl, IsMapped, LookupFrom, LookupFromFile,
1884 NormalizedPath, RelativePath, SearchPath, SuggestedModule, isAngled);
Douglas Gregor11729f02011-11-30 18:12:06 +00001885
Erich Keane76675de2018-07-05 17:22:13 +00001886 if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
Alex Lorenz4dc55732019-08-22 18:15:50 +00001887 if (File && isPCHThroughHeader(&File->getFileEntry()))
Erich Keane76675de2018-07-05 17:22:13 +00001888 SkippingUntilPCHThroughHeader = false;
Richard Smith8af8b862019-04-11 21:18:23 +00001889 return {ImportAction::None};
Erich Keane76675de2018-07-05 17:22:13 +00001890 }
1891
Nikolai Kosjar3c28a2d2019-05-10 10:25:35 +00001892 // Check for circular inclusion of the main file.
1893 // We can't generate a consistent preamble with regard to the conditional
1894 // stack if the main file is included again as due to the preamble bounds
1895 // some directives (e.g. #endif of a header guard) will never be seen.
1896 // Since this will lead to confusing errors, avoid the inclusion.
1897 if (File && PreambleConditionalStack.isRecording() &&
Alex Lorenz4dc55732019-08-22 18:15:50 +00001898 SourceMgr.translateFile(&File->getFileEntry()) ==
1899 SourceMgr.getMainFileID()) {
Nikolai Kosjar3c28a2d2019-05-10 10:25:35 +00001900 Diag(FilenameTok.getLocation(),
1901 diag::err_pp_including_mainfile_in_preamble);
1902 return {ImportAction::None};
1903 }
1904
Richard Smith86559dc2019-03-21 19:44:17 +00001905 // Should we enter the source file? Set to Skip if either the source file is
Richard Smith63b6fce2015-05-18 04:45:41 +00001906 // known to have no effect beyond its effect on module visibility -- that is,
Richard Smith86559dc2019-03-21 19:44:17 +00001907 // if it's got an include guard that is already defined, set to Import if it
1908 // is a modular header we've already built and should import.
1909 enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter;
Richard Smithdbbc5232015-05-14 02:25:44 +00001910
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001911 if (PPOpts->SingleFileParseMode)
Richard Smith86559dc2019-03-21 19:44:17 +00001912 Action = IncludeLimitReached;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001913
Volodymyr Sapsai978be4c12018-12-07 20:29:54 +00001914 // If we've reached the max allowed include depth, it is usually due to an
1915 // include cycle. Don't enter already processed files again as it can lead to
1916 // reaching the max allowed include depth again.
Richard Smith86559dc2019-03-21 19:44:17 +00001917 if (Action == Enter && HasReachedMaxIncludeDepth && File &&
Alex Lorenz4dc55732019-08-22 18:15:50 +00001918 HeaderInfo.getFileInfo(&File->getFileEntry()).NumIncludes)
Richard Smith86559dc2019-03-21 19:44:17 +00001919 Action = IncludeLimitReached;
Volodymyr Sapsai482070b2018-07-25 19:16:26 +00001920
Richard Smith63b6fce2015-05-18 04:45:41 +00001921 // Determine whether we should try to import the module for this #include, if
1922 // there is one. Don't do so if precompiled module support is disabled or we
1923 // are processing this module textually (because we're building the module).
Richard Smith86559dc2019-03-21 19:44:17 +00001924 if (Action == Enter && File && SuggestedModule && getLangOpts().Modules &&
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +00001925 !isForModuleBuilding(SuggestedModule.getModule(),
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00001926 getLangOpts().CurrentModule,
1927 getLangOpts().ModuleName)) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001928 // If this include corresponds to a module but that module is
1929 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001930 // FIXME: Remove this; loadModule does the same check (but produces
1931 // slightly worse diagnostics).
Richard Smith27e5aa02017-06-05 18:57:56 +00001932 if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
1933 SuggestedModule.getModule())) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001934 Diag(FilenameTok.getLocation(),
1935 diag::note_implicit_top_level_module_import_here)
Richard Smith27e5aa02017-06-05 18:57:56 +00001936 << SuggestedModule.getModule()->getTopLevelModuleName();
Richard Smith8af8b862019-04-11 21:18:23 +00001937 return {ImportAction::None};
Sean Silva8b7c0392015-08-17 16:39:30 +00001938 }
1939
Douglas Gregor71944202011-11-30 00:36:36 +00001940 // Compute the module access path corresponding to this module.
1941 // FIXME: Should we have a second loadModule() overload to avoid this
1942 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001943 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001944 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001945 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1946 FilenameTok.getLocation()));
1947 std::reverse(Path.begin(), Path.end());
1948
Douglas Gregor41e115a2011-11-30 18:02:36 +00001949 // Warn that we're replacing the include/import with a module import.
Richard Smith8af8b862019-04-11 21:18:23 +00001950 if (!IsImportDecl)
1951 diagnoseAutoModuleImport(*this, StartLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001952
Richard Smith10434f32015-05-02 02:08:26 +00001953 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001954 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001955 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1956 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001957 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1958 IncludeTok.getLocation(), Path, Module::Hidden,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001959 /*IsInclusionDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001960 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001961 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001962
Richard Smith86559dc2019-03-21 19:44:17 +00001963 if (Imported) {
1964 Action = Import;
1965 } else if (Imported.isMissingExpected()) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001966 // We failed to find a submodule that we assumed would exist (because it
1967 // was in the directory of an umbrella header, for instance), but no
Richard Smitha114c462016-12-06 00:40:17 +00001968 // actual module containing it exists (because the umbrella header is
Richard Smith63b6fce2015-05-18 04:45:41 +00001969 // incomplete). Treat this as a textual inclusion.
1970 SuggestedModule = ModuleMap::KnownHeader();
Richard Smitha114c462016-12-06 00:40:17 +00001971 } else if (Imported.isConfigMismatch()) {
1972 // On a configuration mismatch, enter the header textually. We still know
1973 // that it's part of the corresponding module.
Richard Smith63b6fce2015-05-18 04:45:41 +00001974 } else {
1975 // We hit an error processing the import. Bail out.
1976 if (hadModuleLoaderFatalFailure()) {
1977 // With a fatal failure in the module loader, we abort parsing.
1978 Token &Result = IncludeTok;
Erich Keane0a6b5b62018-12-04 14:34:09 +00001979 assert(CurLexer && "#include but no current lexer set!");
1980 Result.startToken();
1981 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1982 CurLexer->cutOffLexing();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001983 }
Richard Smith8af8b862019-04-11 21:18:23 +00001984 return {ImportAction::None};
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001985 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001986 }
1987
Richard Smithc5247e62017-05-30 02:03:19 +00001988 // The #included file will be considered to be a system header if either it is
1989 // in a system include directory, or if the #includer is a system include
1990 // header.
1991 SrcMgr::CharacteristicKind FileCharacter =
1992 SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
1993 if (File)
Alex Lorenz4dc55732019-08-22 18:15:50 +00001994 FileCharacter = std::max(HeaderInfo.getFileDirFlavor(&File->getFileEntry()),
1995 FileCharacter);
Richard Smithc5247e62017-05-30 02:03:19 +00001996
Richard Smith8af8b862019-04-11 21:18:23 +00001997 // If this is a '#import' or an import-declaration, don't re-enter the file.
1998 //
1999 // FIXME: If we have a suggested module for a '#include', and we've already
2000 // visited this file, don't bother entering it again. We know it has no
2001 // further effect.
2002 bool EnterOnce =
2003 IsImportDecl ||
2004 IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import;
2005
Richard Smithc5247e62017-05-30 02:03:19 +00002006 // Ask HeaderInfo if we should enter this #include file. If not, #including
2007 // this file will have no effect.
Richard Smith86559dc2019-03-21 19:44:17 +00002008 if (Action == Enter && File &&
Alex Lorenz4dc55732019-08-22 18:15:50 +00002009 !HeaderInfo.ShouldEnterIncludeFile(*this, &File->getFileEntry(),
2010 EnterOnce, getLangOpts().Modules,
Richard Smithc5247e62017-05-30 02:03:19 +00002011 SuggestedModule.getModule())) {
Richard Smith86559dc2019-03-21 19:44:17 +00002012 // Even if we've already preprocessed this header once and know that we
2013 // don't need to see its contents again, we still need to import it if it's
2014 // modular because we might not have imported it from this submodule before.
2015 //
2016 // FIXME: We don't do this when compiling a PCH because the AST
2017 // serialization layer can't cope with it. This means we get local
2018 // submodule visibility semantics wrong in that case.
2019 Action = (SuggestedModule && !getLangOpts().CompilingPCH) ? Import : Skip;
Richard Smithc5247e62017-05-30 02:03:19 +00002020 }
2021
Richard Smith8af8b862019-04-11 21:18:23 +00002022 if (Callbacks && !IsImportDecl) {
Richard Smith63b6fce2015-05-18 04:45:41 +00002023 // Notify the callback object that we've seen an inclusion directive.
Richard Smith8af8b862019-04-11 21:18:23 +00002024 // FIXME: Use a different callback for a pp-import?
Richard Smith63b6fce2015-05-18 04:45:41 +00002025 Callbacks->InclusionDirective(
2026 HashLoc, IncludeTok,
2027 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
Alex Lorenz4dc55732019-08-22 18:15:50 +00002028 FilenameRange, File ? &File->getFileEntry() : nullptr, SearchPath,
2029 RelativePath, Action == Import ? SuggestedModule.getModule() : nullptr,
Richard Smith86559dc2019-03-21 19:44:17 +00002030 FileCharacter);
Alex Lorenz4dc55732019-08-22 18:15:50 +00002031 if (Action == Skip && File)
Alex Lorenz67d25fe2019-08-27 01:03:25 +00002032 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Douglas Gregor97eec242011-09-15 22:00:41 +00002033 }
Richard Smith63b6fce2015-05-18 04:45:41 +00002034
2035 if (!File)
Richard Smith8af8b862019-04-11 21:18:23 +00002036 return {ImportAction::None};
Taewook Oh755e4d22016-06-13 21:55:33 +00002037
Richard Smith8af8b862019-04-11 21:18:23 +00002038 // If this is a C++20 pp-import declaration, diagnose if we didn't find any
2039 // module corresponding to the named header.
2040 if (IsImportDecl && !SuggestedModule) {
2041 Diag(FilenameTok, diag::err_header_import_not_header_unit)
2042 << OriginalFilename << File->getName();
2043 return {ImportAction::None};
2044 }
Richard Smith54ef4c32015-05-19 19:58:11 +00002045
Taewook Ohf42103c2016-06-13 20:40:21 +00002046 // Issue a diagnostic if the name of the file on disk has a different case
2047 // than the one we're about to open.
2048 const bool CheckIncludePathPortability =
Alex Lorenz4dc55732019-08-22 18:15:50 +00002049 !IsMapped && !File->getFileEntry().tryGetRealPathName().empty();
Taewook Ohf42103c2016-06-13 20:40:21 +00002050
2051 if (CheckIncludePathPortability) {
2052 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
Alex Lorenz4dc55732019-08-22 18:15:50 +00002053 StringRef RealPathName = File->getFileEntry().tryGetRealPathName();
Taewook Ohf42103c2016-06-13 20:40:21 +00002054 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
2055 llvm::sys::path::end(Name));
2056
2057 if (trySimplifyPath(Components, RealPathName)) {
2058 SmallString<128> Path;
2059 Path.reserve(Name.size()+2);
2060 Path.push_back(isAngled ? '<' : '"');
Taewook Ohcc89bac2017-02-21 22:30:55 +00002061 bool isLeadingSeparator = llvm::sys::path::is_absolute(Name);
Taewook Ohf42103c2016-06-13 20:40:21 +00002062 for (auto Component : Components) {
Taewook Ohcc89bac2017-02-21 22:30:55 +00002063 if (isLeadingSeparator)
2064 isLeadingSeparator = false;
2065 else
2066 Path.append(Component);
Taewook Ohf42103c2016-06-13 20:40:21 +00002067 // Append the separator the user used, or the close quote
2068 Path.push_back(
2069 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
2070 (isAngled ? '>' : '"'));
2071 }
Taewook Ohf42103c2016-06-13 20:40:21 +00002072 // For user files and known standard headers, by default we issue a diagnostic.
2073 // For other system headers, we don't. They can be controlled separately.
2074 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
2075 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
Reid Kleckner273895b2017-02-14 18:38:40 +00002076 Diag(FilenameTok, DiagId) << Path <<
Richard Smithb9b05102019-03-19 01:51:19 +00002077 FixItHint::CreateReplacement(FilenameRange, Path);
Taewook Ohf42103c2016-06-13 20:40:21 +00002078 }
2079 }
2080
Richard Smith86559dc2019-03-21 19:44:17 +00002081 switch (Action) {
2082 case Skip:
2083 // If we don't need to enter the file, stop now.
Richard Smithd652bdd2019-04-14 08:06:59 +00002084 if (Module *M = SuggestedModule.getModule())
2085 return {ImportAction::SkippedModuleImport, M};
Richard Smith8af8b862019-04-11 21:18:23 +00002086 return {ImportAction::None};
Richard Smith86559dc2019-03-21 19:44:17 +00002087
2088 case IncludeLimitReached:
2089 // If we reached our include limit and don't want to enter any more files,
2090 // don't go any further.
Richard Smith8af8b862019-04-11 21:18:23 +00002091 return {ImportAction::None};
Richard Smith86559dc2019-03-21 19:44:17 +00002092
2093 case Import: {
2094 // If this is a module import, make it visible if needed.
2095 Module *M = SuggestedModule.getModule();
2096 assert(M && "no module to import");
2097
Richard Smith8af8b862019-04-11 21:18:23 +00002098 makeModuleVisible(M, EndLoc);
Richard Smith86559dc2019-03-21 19:44:17 +00002099
Richard Smith8af8b862019-04-11 21:18:23 +00002100 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() ==
Richard Smith86559dc2019-03-21 19:44:17 +00002101 tok::pp___include_macros)
Richard Smith8af8b862019-04-11 21:18:23 +00002102 return {ImportAction::None};
2103
2104 return {ImportAction::ModuleImport, M};
Richard Smith86559dc2019-03-21 19:44:17 +00002105 }
2106
2107 case Enter:
2108 break;
Chris Lattner72286d62010-04-19 20:44:31 +00002109 }
2110
Richard Smith5a8ea4c2019-03-19 01:51:17 +00002111 // Check that we don't have infinite #include recursion.
2112 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
2113 Diag(FilenameTok, diag::err_pp_include_too_deep);
2114 HasReachedMaxIncludeDepth = true;
Richard Smith8af8b862019-04-11 21:18:23 +00002115 return {ImportAction::None};
Richard Smith5a8ea4c2019-03-19 01:51:17 +00002116 }
2117
Chris Lattnerf64b3522008-03-09 01:54:53 +00002118 // Look up the file, create a File ID for it.
Richard Smithb9b05102019-03-19 01:51:19 +00002119 SourceLocation IncludePos = FilenameTok.getLocation();
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002120 // If the filename string was the result of macro expansions, set the include
2121 // position on the file where it will be included and after the expansions.
2122 if (IncludePos.isMacroID())
Richard Smithb5f81712018-04-30 05:25:48 +00002123 IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
Alex Lorenz4dc55732019-08-22 18:15:50 +00002124 FileID FID = SourceMgr.createFileID(*File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002125 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002126
Richard Smith34f30512013-11-23 04:06:09 +00002127 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002128 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
Richard Smith8af8b862019-04-11 21:18:23 +00002129 return {ImportAction::None};
Richard Smith34f30512013-11-23 04:06:09 +00002130
Richard Smitha0aafa32015-05-18 03:52:30 +00002131 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002132 if (auto *M = SuggestedModule.getModule()) {
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00002133 if (M->getTopLevelModule()->ShadowingModule) {
2134 // We are building a submodule that belongs to a shadowed module. This
2135 // means we find header files in the shadowed module.
2136 Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule)
2137 << M->getFullModuleName();
2138 Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc,
2139 diag::note_previous_definition);
Richard Smith8af8b862019-04-11 21:18:23 +00002140 return {ImportAction::None};
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00002141 }
Manman Renffd3e9d2017-01-09 19:20:18 +00002142 // When building a pch, -fmodule-name tells the compiler to textually
2143 // include headers in the specified module. We are not building the
2144 // specified module.
Richard Smith86559dc2019-03-21 19:44:17 +00002145 //
2146 // FIXME: This is the wrong way to handle this. We should produce a PCH
2147 // that behaves the same as the header would behave in a compilation using
2148 // that PCH, which means we should enter the submodule. We need to teach
2149 // the AST serialization layer to deal with the resulting AST.
Manman Renffd3e9d2017-01-09 19:20:18 +00002150 if (getLangOpts().CompilingPCH &&
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00002151 isForModuleBuilding(M, getLangOpts().CurrentModule,
2152 getLangOpts().ModuleName))
Richard Smith8af8b862019-04-11 21:18:23 +00002153 return {ImportAction::None};
Manman Renffd3e9d2017-01-09 19:20:18 +00002154
Richard Smithd1386302017-05-04 00:29:54 +00002155 assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2156 CurLexerSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002157
Richard Smitha0aafa32015-05-18 03:52:30 +00002158 // Let the macro handling code know that any future macros are within
2159 // the new submodule.
Richard Smith8af8b862019-04-11 21:18:23 +00002160 EnterSubmodule(M, EndLoc, /*ForPragma*/false);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002161
Richard Smitha0aafa32015-05-18 03:52:30 +00002162 // Let the parser know that any future declarations are within the new
2163 // submodule.
2164 // FIXME: There's no point doing this if we're handling a #__include_macros
2165 // directive.
Richard Smith8af8b862019-04-11 21:18:23 +00002166 return {ImportAction::ModuleBegin, M};
Richard Smith67294e22014-01-31 20:47:44 +00002167 }
Richard Smith8af8b862019-04-11 21:18:23 +00002168
Richard Smithd652bdd2019-04-14 08:06:59 +00002169 assert(!IsImportDecl && "failed to diagnose missing module for import decl");
Richard Smith8af8b862019-04-11 21:18:23 +00002170 return {ImportAction::None};
Chris Lattnerf64b3522008-03-09 01:54:53 +00002171}
2172
James Dennettf6333ac2012-06-22 05:46:07 +00002173/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002174///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002175void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2176 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002177 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002178
Chris Lattnerf64b3522008-03-09 01:54:53 +00002179 // #include_next is like #include, except that we start searching after
2180 // the current found directory. If we can't do this, issue a
2181 // diagnostic.
2182 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002183 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00002184 if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2185 // If the main file is a header, then it's either for PCH/AST generation,
2186 // or libclang opened it. Either way, handle it as a normal include below
2187 // and do not complain about include_next.
2188 } else if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002189 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002190 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smithd1386302017-05-04 00:29:54 +00002191 } else if (CurLexerSubmodule) {
Richard Smith25d50752014-10-20 00:15:49 +00002192 // Start looking up in the directory *after* the one in which the current
2193 // file would be found, if any.
2194 assert(CurPPLexer && "#include_next directive in macro?");
2195 LookupFromFile = CurPPLexer->getFileEntry();
2196 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002197 } else if (!Lookup) {
Richard Smith6d69fec2019-03-21 20:42:13 +00002198 // The current file was not found by walking the include path. Either it
2199 // is the primary file (handled above), or it was found by absolute path,
2200 // or it was found relative to such a file.
2201 // FIXME: Track enough information so we know which case we're in.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002202 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2203 } else {
2204 // Start looking up in the next directory.
2205 ++Lookup;
2206 }
Mike Stump11289f42009-09-09 15:08:12 +00002207
Richard Smith25d50752014-10-20 00:15:49 +00002208 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2209 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002210}
2211
James Dennettf6333ac2012-06-22 05:46:07 +00002212/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002213void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2214 // The Microsoft #import directive takes a type library and generates header
2215 // files from it, and includes those. This is beyond the scope of what clang
2216 // does, so we ignore it and error out. However, #import can optionally have
2217 // trailing attributes that span multiple lines. We're going to eat those
2218 // so we can continue processing from there.
2219 Diag(Tok, diag::err_pp_import_directive_ms );
2220
Taewook Oh755e4d22016-06-13 21:55:33 +00002221 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002222 // directive can be split over multiple lines using the backslash character.
2223 DiscardUntilEndOfDirective();
2224}
2225
James Dennettf6333ac2012-06-22 05:46:07 +00002226/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002227///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002228void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2229 Token &ImportTok) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002230 if (!LangOpts.ObjC) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002231 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002232 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002233 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002234 }
Richard Smith8af8b862019-04-11 21:18:23 +00002235 return HandleIncludeDirective(HashLoc, ImportTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002236}
2237
Chris Lattner58a1eb02009-04-08 18:46:40 +00002238/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2239/// pseudo directive in the predefines buffer. This handles it by sucking all
2240/// tokens through the preprocessor and discarding them (only keeping the side
2241/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002242void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2243 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002244 // This directive should only occur in the predefines buffer. If not, emit an
2245 // error and reject it.
2246 SourceLocation Loc = IncludeMacrosTok.getLocation();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002247 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002248 Diag(IncludeMacrosTok.getLocation(),
2249 diag::pp_include_macros_out_of_predefines);
2250 DiscardUntilEndOfDirective();
2251 return;
2252 }
Mike Stump11289f42009-09-09 15:08:12 +00002253
Chris Lattnere01d82b2009-04-08 20:53:24 +00002254 // Treat this as a normal #include for checking purposes. If this is
2255 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002256 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002257
Chris Lattnere01d82b2009-04-08 20:53:24 +00002258 Token TmpTok;
2259 do {
2260 Lex(TmpTok);
2261 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2262 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002263}
2264
Chris Lattnerf64b3522008-03-09 01:54:53 +00002265//===----------------------------------------------------------------------===//
2266// Preprocessor Macro Directive Handling.
2267//===----------------------------------------------------------------------===//
2268
Faisal Valie8f430a2017-09-29 02:43:22 +00002269/// ReadMacroParameterList - The ( starting a parameter list of a macro
2270/// definition has just been read. Lex the rest of the parameters and the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002271/// closing ), updating MI with what we learn. Return true if an error occurs
Faisal Valie8f430a2017-09-29 02:43:22 +00002272/// parsing the param list.
Faisal Valiac506d72017-07-17 17:18:43 +00002273bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
Faisal Vali33df3912017-09-29 02:17:31 +00002274 SmallVector<IdentifierInfo*, 32> Parameters;
Mike Stump11289f42009-09-09 15:08:12 +00002275
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002276 while (true) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002277 LexUnexpandedToken(Tok);
2278 switch (Tok.getKind()) {
2279 case tok::r_paren:
Faisal Valie8f430a2017-09-29 02:43:22 +00002280 // Found the end of the parameter list.
Faisal Vali33df3912017-09-29 02:17:31 +00002281 if (Parameters.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002282 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002283 // Otherwise we have #define FOO(A,)
2284 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2285 return true;
2286 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002287 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002288 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002289 diag::warn_cxx98_compat_variadic_macro :
2290 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002291
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002292 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2293 if (LangOpts.OpenCL) {
Anastasia Stulova545652b2019-03-26 11:22:37 +00002294 Diag(Tok, diag::ext_pp_opencl_variadic_macros);
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002295 }
2296
Chris Lattnerf64b3522008-03-09 01:54:53 +00002297 // Lex the token after the identifier.
2298 LexUnexpandedToken(Tok);
2299 if (Tok.isNot(tok::r_paren)) {
2300 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2301 return true;
2302 }
Faisal Valie8f430a2017-09-29 02:43:22 +00002303 // Add the __VA_ARGS__ identifier as a parameter.
Faisal Vali33df3912017-09-29 02:17:31 +00002304 Parameters.push_back(Ident__VA_ARGS__);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002305 MI->setIsC99Varargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002306 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002307 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002308 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002309 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2310 return true;
2311 default:
2312 // Handle keywords and identifiers here to accept things like
2313 // #define Foo(for) for.
2314 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002315 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002316 // #define X(1
2317 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2318 return true;
2319 }
2320
Faisal Valie8f430a2017-09-29 02:43:22 +00002321 // If this is already used as a parameter, it is used multiple times (e.g.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002322 // #define X(A,A.
Fangrui Song75e74e02019-03-31 08:48:19 +00002323 if (llvm::find(Parameters, II) != Parameters.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002324 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002325 return true;
2326 }
Mike Stump11289f42009-09-09 15:08:12 +00002327
Faisal Valie8f430a2017-09-29 02:43:22 +00002328 // Add the parameter to the macro info.
Faisal Vali33df3912017-09-29 02:17:31 +00002329 Parameters.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002330
Chris Lattnerf64b3522008-03-09 01:54:53 +00002331 // Lex the token after the identifier.
2332 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002333
Chris Lattnerf64b3522008-03-09 01:54:53 +00002334 switch (Tok.getKind()) {
2335 default: // #define X(A B
2336 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2337 return true;
2338 case tok::r_paren: // #define X(A)
Faisal Vali33df3912017-09-29 02:17:31 +00002339 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002340 return false;
2341 case tok::comma: // #define X(A,
2342 break;
2343 case tok::ellipsis: // #define X(A... -> GCC extension
2344 // Diagnose extension.
2345 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002346
Chris Lattnerf64b3522008-03-09 01:54:53 +00002347 // Lex the token after the identifier.
2348 LexUnexpandedToken(Tok);
2349 if (Tok.isNot(tok::r_paren)) {
2350 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2351 return true;
2352 }
Mike Stump11289f42009-09-09 15:08:12 +00002353
Chris Lattnerf64b3522008-03-09 01:54:53 +00002354 MI->setIsGNUVarargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002355 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002356 return false;
2357 }
2358 }
2359 }
2360}
2361
Serge Pavlov07c0f042014-12-18 11:14:21 +00002362static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2363 const LangOptions &LOptions) {
2364 if (MI->getNumTokens() == 1) {
2365 const Token &Value = MI->getReplacementToken(0);
2366
2367 // Macro that is identity, like '#define inline inline' is a valid pattern.
2368 if (MacroName.getKind() == Value.getKind())
2369 return true;
2370
2371 // Macro that maps a keyword to the same keyword decorated with leading/
2372 // trailing underscores is a valid pattern:
2373 // #define inline __inline
2374 // #define inline __inline__
2375 // #define inline _inline (in MS compatibility mode)
2376 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2377 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2378 if (!II->isKeyword(LOptions))
2379 return false;
2380 StringRef ValueText = II->getName();
2381 StringRef TrimmedValue = ValueText;
2382 if (!ValueText.startswith("__")) {
2383 if (ValueText.startswith("_"))
2384 TrimmedValue = TrimmedValue.drop_front(1);
2385 else
2386 return false;
2387 } else {
2388 TrimmedValue = TrimmedValue.drop_front(2);
2389 if (TrimmedValue.endswith("__"))
2390 TrimmedValue = TrimmedValue.drop_back(2);
2391 }
2392 return TrimmedValue.equals(MacroText);
2393 } else {
2394 return false;
2395 }
2396 }
2397
2398 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002399 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2400 tok::kw_const) &&
2401 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002402}
2403
Faisal Valiac506d72017-07-17 17:18:43 +00002404// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2405// entire line) of the macro's tokens and adds them to MacroInfo, and while
2406// doing so performs certain validity checks including (but not limited to):
2407// - # (stringization) is followed by a macro parameter
2408//
2409// Returns a nullptr if an invalid sequence of tokens is encountered or returns
2410// a pointer to a MacroInfo object.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002411
Faisal Valiac506d72017-07-17 17:18:43 +00002412MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2413 const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002414
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002415 Token LastTok = MacroNameTok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002416 // Create the new macro.
Faisal Valiac506d72017-07-17 17:18:43 +00002417 MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002418
Chris Lattnerf64b3522008-03-09 01:54:53 +00002419 Token Tok;
2420 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002421
Ilya Biryukovb455fc42019-08-01 09:10:37 +00002422 // Ensure we consume the rest of the macro body if errors occur.
2423 auto _ = llvm::make_scope_exit([&]() {
2424 // The flag indicates if we are still waiting for 'eod'.
2425 if (CurLexer->ParsingPreprocessorDirective)
2426 DiscardUntilEndOfDirective();
2427 });
2428
Faisal Vali6bf67912017-07-25 03:15:36 +00002429 // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2430 // within their appropriate context.
2431 VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2432
Chris Lattnerf64b3522008-03-09 01:54:53 +00002433 // If this is a function-like macro definition, parse the argument list,
2434 // marking each of the identifiers as being used as macro arguments. Also,
2435 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002436 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002437 if (ImmediatelyAfterHeaderGuard) {
2438 // Save this macro information since it may part of a header guard.
2439 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2440 MacroNameTok.getLocation());
2441 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002442 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002443 } else if (Tok.hasLeadingSpace()) {
2444 // This is a normal token with leading space. Clear the leading space
2445 // marker on the first token to get proper expansion.
2446 Tok.clearFlag(Token::LeadingSpace);
2447 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002448 // This is a function-like macro definition. Read the argument list.
2449 MI->setIsFunctionLike();
Ilya Biryukovb455fc42019-08-01 09:10:37 +00002450 if (ReadMacroParameterList(MI, LastTok))
Faisal Valiac506d72017-07-17 17:18:43 +00002451 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002452
Faisal Vali6bf67912017-07-25 03:15:36 +00002453 // If this is a definition of an ISO C/C++ variadic function-like macro (not
2454 // using the GNU named varargs extension) inform our variadic scope guard
2455 // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2456 // allowed only within the definition of a variadic macro.
Mike Stump11289f42009-09-09 15:08:12 +00002457
Faisal Vali6bf67912017-07-25 03:15:36 +00002458 if (MI->isC99Varargs()) {
2459 VariadicMacroScopeGuard.enterScope();
2460 }
Mike Stump11289f42009-09-09 15:08:12 +00002461
Chris Lattnerf64b3522008-03-09 01:54:53 +00002462 // Read the first token after the arg list for down below.
2463 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002464 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002465 // C99 requires whitespace between the macro definition and the body. Emit
2466 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002467 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002468 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002469 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2470 // first character of a replacement list is not a character required by
2471 // subclause 5.2.1, then there shall be white-space separation between the
2472 // identifier and the replacement list.". 5.2.1 lists this set:
2473 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2474 // is irrelevant here.
2475 bool isInvalid = false;
2476 if (Tok.is(tok::at)) // @ is not in the list above.
2477 isInvalid = true;
2478 else if (Tok.is(tok::unknown)) {
2479 // If we have an unknown token, it is something strange like "`". Since
2480 // all of valid characters would have lexed into a single character
2481 // token of some sort, we know this is not a valid case.
2482 isInvalid = true;
2483 }
2484 if (isInvalid)
2485 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2486 else
2487 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002488 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002489
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002490 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002491 LastTok = Tok;
2492
Chris Lattnerf64b3522008-03-09 01:54:53 +00002493 // Read the rest of the macro body.
2494 if (MI->isObjectLike()) {
2495 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002496 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002497 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002498 MI->AddTokenToBody(Tok);
2499 // Get the next token of the macro.
2500 LexUnexpandedToken(Tok);
2501 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002502 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002503 // Otherwise, read the body of a function-like macro. While we are at it,
2504 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2505 // parameters in function-like macro expansions.
Faisal Vali18268422017-10-15 01:26:26 +00002506
2507 VAOptDefinitionContext VAOCtx(*this);
2508
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002509 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002510 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002511
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002512 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002513 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002514
Faisal Vali18268422017-10-15 01:26:26 +00002515 if (VAOCtx.isVAOptToken(Tok)) {
2516 // If we're already within a VAOPT, emit an error.
2517 if (VAOCtx.isInVAOpt()) {
2518 Diag(Tok, diag::err_pp_vaopt_nested_use);
2519 return nullptr;
2520 }
2521 // Ensure VAOPT is followed by a '(' .
2522 LexUnexpandedToken(Tok);
2523 if (Tok.isNot(tok::l_paren)) {
2524 Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
2525 return nullptr;
2526 }
2527 MI->AddTokenToBody(Tok);
2528 VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
2529 LexUnexpandedToken(Tok);
2530 if (Tok.is(tok::hashhash)) {
2531 Diag(Tok, diag::err_vaopt_paste_at_start);
2532 return nullptr;
2533 }
2534 continue;
2535 } else if (VAOCtx.isInVAOpt()) {
2536 if (Tok.is(tok::r_paren)) {
2537 if (VAOCtx.sawClosingParen()) {
2538 const unsigned NumTokens = MI->getNumTokens();
2539 assert(NumTokens >= 3 && "Must have seen at least __VA_OPT__( "
2540 "and a subsequent tok::r_paren");
2541 if (MI->getReplacementToken(NumTokens - 2).is(tok::hashhash)) {
2542 Diag(Tok, diag::err_vaopt_paste_at_end);
2543 return nullptr;
2544 }
2545 }
2546 } else if (Tok.is(tok::l_paren)) {
2547 VAOCtx.sawOpeningParen(Tok.getLocation());
2548 }
2549 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002550 // Get the next token of the macro.
2551 LexUnexpandedToken(Tok);
2552 continue;
2553 }
Mike Stump11289f42009-09-09 15:08:12 +00002554
Richard Smith701a3522013-07-09 01:00:29 +00002555 // If we're in -traditional mode, then we should ignore stringification
2556 // and token pasting. Mark the tokens as unknown so as not to confuse
2557 // things.
2558 if (getLangOpts().TraditionalCPP) {
2559 Tok.setKind(tok::unknown);
2560 MI->AddTokenToBody(Tok);
2561
2562 // Get the next token of the macro.
2563 LexUnexpandedToken(Tok);
2564 continue;
2565 }
2566
Eli Friedman14d3c792012-11-14 02:18:46 +00002567 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002568 // If we see token pasting, check if it looks like the gcc comma
2569 // pasting extension. We'll use this information to suppress
2570 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002571
Eli Friedman14d3c792012-11-14 02:18:46 +00002572 // Get the next token of the macro.
2573 LexUnexpandedToken(Tok);
2574
2575 if (Tok.is(tok::eod)) {
2576 MI->AddTokenToBody(LastTok);
2577 break;
2578 }
2579
2580 unsigned NumTokens = MI->getNumTokens();
2581 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2582 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2583 MI->setHasCommaPasting();
2584
David Majnemer76faf1f2013-11-05 09:30:17 +00002585 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002586 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002587 continue;
2588 }
2589
Faisal Vali18268422017-10-15 01:26:26 +00002590 // Our Token is a stringization operator.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002591 // Get the next token of the macro.
2592 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002593
Faisal Vali18268422017-10-15 01:26:26 +00002594 // Check for a valid macro arg identifier or __VA_OPT__.
2595 if (!VAOCtx.isVAOptToken(Tok) &&
2596 (Tok.getIdentifierInfo() == nullptr ||
2597 MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002598
2599 // If this is assembler-with-cpp mode, we accept random gibberish after
2600 // the '#' because '#' is often a comment character. However, change
2601 // the kind of the token to tok::unknown so that the preprocessor isn't
2602 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002603 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002604 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002605 MI->AddTokenToBody(LastTok);
2606 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002607 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002608 Diag(Tok, diag::err_pp_stringize_not_parameter)
2609 << LastTok.is(tok::hashat);
Faisal Valiac506d72017-07-17 17:18:43 +00002610 return nullptr;
Chris Lattner83bd8282009-05-25 17:16:10 +00002611 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002612 }
Mike Stump11289f42009-09-09 15:08:12 +00002613
Chris Lattner83bd8282009-05-25 17:16:10 +00002614 // Things look ok, add the '#' and param name tokens to the macro.
2615 MI->AddTokenToBody(LastTok);
Mike Stump11289f42009-09-09 15:08:12 +00002616
Faisal Vali18268422017-10-15 01:26:26 +00002617 // If the token following '#' is VAOPT, let the next iteration handle it
2618 // and check it for correctness, otherwise add the token and prime the
2619 // loop with the next one.
2620 if (!VAOCtx.isVAOptToken(Tok)) {
2621 MI->AddTokenToBody(Tok);
2622 LastTok = Tok;
2623
2624 // Get the next token of the macro.
2625 LexUnexpandedToken(Tok);
2626 }
2627 }
2628 if (VAOCtx.isInVAOpt()) {
2629 assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
2630 Diag(Tok, diag::err_pp_expected_after)
2631 << LastTok.getKind() << tok::r_paren;
2632 Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
2633 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002634 }
2635 }
Faisal Valiac506d72017-07-17 17:18:43 +00002636 MI->setDefinitionEndLoc(LastTok.getLocation());
Faisal Valiac506d72017-07-17 17:18:43 +00002637 return MI;
2638}
2639/// HandleDefineDirective - Implements \#define. This consumes the entire macro
2640/// line then lets the caller lex the next real token.
2641void Preprocessor::HandleDefineDirective(
2642 Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2643 ++NumDefined;
2644
2645 Token MacroNameTok;
2646 bool MacroShadowsKeyword;
2647 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2648
2649 // Error reading macro name? If so, diagnostic already issued.
2650 if (MacroNameTok.is(tok::eod))
2651 return;
2652
2653 // If we are supposed to keep comments in #defines, reenable comment saving
2654 // mode.
2655 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2656
2657 MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2658 MacroNameTok, ImmediatelyAfterHeaderGuard);
Fangrui Song6907ce22018-07-30 19:24:48 +00002659
Faisal Valiac506d72017-07-17 17:18:43 +00002660 if (!MI) return;
Mike Stump11289f42009-09-09 15:08:12 +00002661
Serge Pavlov07c0f042014-12-18 11:14:21 +00002662 if (MacroShadowsKeyword &&
2663 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2664 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
Fangrui Song6907ce22018-07-30 19:24:48 +00002665 }
Chris Lattner57540c52011-04-15 05:22:18 +00002666 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002667 // replacement list.
2668 unsigned NumTokens = MI->getNumTokens();
2669 if (NumTokens != 0) {
2670 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2671 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002672 return;
2673 }
2674 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2675 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002676 return;
2677 }
2678 }
Mike Stump11289f42009-09-09 15:08:12 +00002679
Erich Keane76675de2018-07-05 17:22:13 +00002680 // When skipping just warn about macros that do not match.
2681 if (SkippingUntilPCHThroughHeader) {
2682 const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
2683 if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
2684 /*Syntactic=*/LangOpts.MicrosoftExt))
2685 Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
2686 << MacroNameTok.getIdentifierInfo();
2687 return;
2688 }
Mike Stump11289f42009-09-09 15:08:12 +00002689
Chris Lattnerf64b3522008-03-09 01:54:53 +00002690 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002691 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002692 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002693 // In Objective-C, ignore attempts to directly redefine the builtin
2694 // definitions of the ownership qualifiers. It's still possible to
2695 // #undef them.
2696 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2697 return II->isStr("__strong") ||
2698 II->isStr("__weak") ||
2699 II->isStr("__unsafe_unretained") ||
2700 II->isStr("__autoreleasing");
2701 };
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002702 if (getLangOpts().ObjC &&
John McCall83760372015-12-10 23:31:01 +00002703 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2704 == getPredefinesFileID() &&
2705 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2706 // Warn if it changes the tokens.
2707 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2708 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2709 !MI->isIdenticalTo(*OtherMI, *this,
2710 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2711 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2712 }
2713 assert(!OtherMI->isWarnIfUnused());
2714 return;
2715 }
2716
Chris Lattner5244f342009-01-16 19:50:11 +00002717 // It is very common for system headers to have tons of macro redefinitions
2718 // and for warnings to be disabled in system headers. If this is the case,
2719 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002720 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002721 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002722 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002723 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002724
Taewook Oh755e4d22016-06-13 21:55:33 +00002725 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002726 // C++ [cpp.predefined]p4, but allow it as an extension.
2727 if (OtherMI->isBuiltinMacro())
2728 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002729 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002730 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002731 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002732 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002733 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2734 << MacroNameTok.getIdentifierInfo();
2735 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2736 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002737 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002738 if (OtherMI->isWarnIfUnused())
2739 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002740 }
Mike Stump11289f42009-09-09 15:08:12 +00002741
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002742 DefMacroDirective *MD =
2743 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002744
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002745 assert(!MI->isUsed());
2746 // If we need warning for not using the macro, add its location in the
2747 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002748 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002749 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002750 MI->setIsWarnIfUnused(true);
2751 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2752 }
2753
Chris Lattner928e9092009-04-12 01:39:54 +00002754 // If the callbacks want to know, tell them about the macro definition.
2755 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002756 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002757}
2758
James Dennettf6333ac2012-06-22 05:46:07 +00002759/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002760///
Erik Verbruggen4bddef92016-10-26 08:52:41 +00002761void Preprocessor::HandleUndefDirective() {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002762 ++NumUndefined;
2763
2764 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002765 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002766
Chris Lattnerf64b3522008-03-09 01:54:53 +00002767 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002768 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002769 return;
Mike Stump11289f42009-09-09 15:08:12 +00002770
Chris Lattnerf64b3522008-03-09 01:54:53 +00002771 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002772 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002773
Richard Smith20e883e2015-04-29 23:20:19 +00002774 // Okay, we have a valid identifier to undef.
2775 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002776 auto MD = getMacroDefinition(II);
Vedant Kumar349a6242017-04-26 21:05:44 +00002777 UndefMacroDirective *Undef = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00002778
Vedant Kumar349a6242017-04-26 21:05:44 +00002779 // If the macro is not defined, this is a noop undef.
2780 if (const MacroInfo *MI = MD.getMacroInfo()) {
2781 if (!MI->isUsed() && MI->isWarnIfUnused())
2782 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2783
2784 if (MI->isWarnIfUnused())
2785 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2786
2787 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
2788 }
Mike Stump11289f42009-09-09 15:08:12 +00002789
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002790 // If the callbacks want to know, tell them about the macro #undef.
2791 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002792 if (Callbacks)
Vedant Kumar349a6242017-04-26 21:05:44 +00002793 Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002794
Vedant Kumar349a6242017-04-26 21:05:44 +00002795 if (Undef)
2796 appendMacroDirective(II, Undef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002797}
2798
Chris Lattnerf64b3522008-03-09 01:54:53 +00002799//===----------------------------------------------------------------------===//
2800// Preprocessor Conditional Directive Handling.
2801//===----------------------------------------------------------------------===//
2802
James Dennettf6333ac2012-06-22 05:46:07 +00002803/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2804/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2805/// true if any tokens have been returned or pp-directives activated before this
2806/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002807///
Vedant Kumar3919a502017-09-11 20:47:42 +00002808void Preprocessor::HandleIfdefDirective(Token &Result,
2809 const Token &HashToken,
2810 bool isIfndef,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002811 bool ReadAnyTokensBeforeDirective) {
2812 ++NumIf;
2813 Token DirectiveTok = Result;
2814
2815 Token MacroNameTok;
2816 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002817
Chris Lattnerf64b3522008-03-09 01:54:53 +00002818 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002819 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002820 // Skip code until we get to #endif. This helps with recovery by not
2821 // emitting an error when the #endif is reached.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002822 SkipExcludedConditionalBlock(HashToken.getLocation(),
2823 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002824 /*Foundnonskip*/ false, /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002825 return;
2826 }
Mike Stump11289f42009-09-09 15:08:12 +00002827
Chris Lattnerf64b3522008-03-09 01:54:53 +00002828 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002829 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002830
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002831 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002832 auto MD = getMacroDefinition(MII);
2833 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002834
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002835 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002836 // If the start of a top-level #ifdef and if the macro is not defined,
2837 // inform MIOpt that this might be the start of a proper include guard.
2838 // Otherwise it is some other form of unknown conditional which we can't
2839 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002840 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002841 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002842 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002843 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002844 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002845 }
2846
Chris Lattnerf64b3522008-03-09 01:54:53 +00002847 // If there is a macro, process it.
2848 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002849 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002850
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002851 if (Callbacks) {
2852 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002853 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002854 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002855 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002856 }
2857
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00002858 bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
2859 getSourceManager().isInMainFile(DirectiveTok.getLocation());
2860
Chris Lattnerf64b3522008-03-09 01:54:53 +00002861 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002862 if (PPOpts->SingleFileParseMode && !MI) {
2863 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2864 // the directive blocks.
2865 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002866 /*wasskip*/false, /*foundnonskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002867 /*foundelse*/false);
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00002868 } else if (!MI == isIfndef || RetainExcludedCB) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002869 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002870 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2871 /*wasskip*/false, /*foundnonskip*/true,
2872 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002873 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002874 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002875 SkipExcludedConditionalBlock(HashToken.getLocation(),
2876 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002877 /*Foundnonskip*/ false,
2878 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002879 }
2880}
2881
James Dennettf6333ac2012-06-22 05:46:07 +00002882/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002883///
2884void Preprocessor::HandleIfDirective(Token &IfToken,
Vedant Kumar3919a502017-09-11 20:47:42 +00002885 const Token &HashToken,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002886 bool ReadAnyTokensBeforeDirective) {
2887 ++NumIf;
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002888
2889 // Parse and evaluate the conditional expression.
2890 IdentifierInfo *IfNDefMacro = nullptr;
2891 const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
2892 const bool ConditionalTrue = DER.Conditional;
2893
2894 // If this condition is equivalent to #ifndef X, and if this is the first
2895 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002896 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002897 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002898 // FIXME: Pass in the location of the macro name, not the 'if' token.
2899 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002900 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002901 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002902 }
2903
2904 if (Callbacks)
2905 Callbacks->If(
2906 IfToken.getLocation(), DER.ExprRange,
2907 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
2908
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00002909 bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
2910 getSourceManager().isInMainFile(IfToken.getLocation());
2911
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002912 // Should we include the stuff contained by this directive?
2913 if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002914 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2915 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002916 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002917 /*foundnonskip*/false, /*foundelse*/false);
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00002918 } else if (ConditionalTrue || RetainExcludedCB) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002919 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002920 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002921 /*foundnonskip*/true, /*foundelse*/false);
2922 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002923 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002924 SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002925 /*Foundnonskip*/ false,
2926 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002927 }
2928}
2929
James Dennettf6333ac2012-06-22 05:46:07 +00002930/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002931///
2932void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2933 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002934
Chris Lattnerf64b3522008-03-09 01:54:53 +00002935 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002936 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002937
Chris Lattnerf64b3522008-03-09 01:54:53 +00002938 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002939 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002940 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002941 Diag(EndifToken, diag::err_pp_endif_without_if);
2942 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002943 }
Mike Stump11289f42009-09-09 15:08:12 +00002944
Chris Lattnerf64b3522008-03-09 01:54:53 +00002945 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002946 if (CurPPLexer->getConditionalStackDepth() == 0)
2947 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002948
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002949 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002950 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002951
2952 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002953 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002954}
2955
James Dennettf6333ac2012-06-22 05:46:07 +00002956/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002957///
Vedant Kumar3919a502017-09-11 20:47:42 +00002958void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002959 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002960
Chris Lattnerf64b3522008-03-09 01:54:53 +00002961 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002962 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002963
Chris Lattnerf64b3522008-03-09 01:54:53 +00002964 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002965 if (CurPPLexer->popConditionalLevel(CI)) {
2966 Diag(Result, diag::pp_err_else_without_if);
2967 return;
2968 }
Mike Stump11289f42009-09-09 15:08:12 +00002969
Chris Lattnerf64b3522008-03-09 01:54:53 +00002970 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002971 if (CurPPLexer->getConditionalStackDepth() == 0)
2972 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002973
2974 // If this is a #else with a #else before it, report the error.
2975 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002976
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002977 if (Callbacks)
2978 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2979
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00002980 bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
2981 getSourceManager().isInMainFile(Result.getLocation());
2982
2983 if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002984 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2985 // the directive blocks.
2986 CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002987 /*foundnonskip*/false, /*foundelse*/true);
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002988 return;
2989 }
2990
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002991 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002992 SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
2993 /*Foundnonskip*/ true,
Vedant Kumar3919a502017-09-11 20:47:42 +00002994 /*FoundElse*/ true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002995}
2996
James Dennettf6333ac2012-06-22 05:46:07 +00002997/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002998///
Vedant Kumar3919a502017-09-11 20:47:42 +00002999void Preprocessor::HandleElifDirective(Token &ElifToken,
3000 const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00003001 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00003002
Chandler Carruthd92d70b2019-01-19 06:36:00 +00003003 // #elif directive in a non-skipping conditional... start skipping.
3004 // We don't care what the condition is, because we will always skip it (since
3005 // the block immediately before it was included).
3006 SourceRange ConditionRange = DiscardUntilEndOfDirective();
3007
3008 PPConditionalInfo CI;
3009 if (CurPPLexer->popConditionalLevel(CI)) {
Chris Lattner907dfe92008-11-18 07:59:24 +00003010 Diag(ElifToken, diag::pp_err_elif_without_if);
3011 return;
3012 }
Mike Stump11289f42009-09-09 15:08:12 +00003013
Chris Lattnerf64b3522008-03-09 01:54:53 +00003014 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00003015 if (CurPPLexer->getConditionalStackDepth() == 0)
3016 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00003017
Chris Lattnerf64b3522008-03-09 01:54:53 +00003018 // If this is a #elif with a #else before it, report the error.
Chandler Carruthd92d70b2019-01-19 06:36:00 +00003019 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
3020
3021 if (Callbacks)
3022 Callbacks->Elif(ElifToken.getLocation(), ConditionRange,
3023 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
3024
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003025 bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3026 getSourceManager().isInMainFile(ElifToken.getLocation());
3027
3028 if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00003029 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3030 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00003031 CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00003032 /*foundnonskip*/false, /*foundelse*/false);
3033 return;
3034 }
3035
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00003036 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003037 SkipExcludedConditionalBlock(
3038 HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
3039 /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00003040}