blob: 2756042f23eb20e0893eb72b3808de54ebaed1da [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"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/SmallVector.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000038#include "llvm/ADT/STLExtras.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000039#include "llvm/ADT/StringSwitch.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "llvm/ADT/StringRef.h"
41#include "llvm/Support/AlignOf.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000042#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaf6002232014-08-08 21:31:04 +000043#include "llvm/Support/Path.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000044#include <algorithm>
45#include <cassert>
46#include <cstring>
47#include <new>
48#include <string>
49#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000050
Chris Lattnerf64b3522008-03-09 01:54:53 +000051using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Utility Methods for Preprocessor Directive Handling.
55//===----------------------------------------------------------------------===//
56
Richard Smith3f6dd7a2017-05-12 23:40:52 +000057MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
58 auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead};
Ted Kremenekc8456f82010-10-19 22:15:20 +000059 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000060 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000061}
62
Richard Smith50474bf2015-04-23 23:29:05 +000063DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
64 SourceLocation Loc) {
Richard Smith713369b2015-04-23 20:40:50 +000065 return new (BP) DefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000066}
67
68UndefMacroDirective *
Richard Smith50474bf2015-04-23 23:29:05 +000069Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
Richard Smith713369b2015-04-23 20:40:50 +000070 return new (BP) UndefMacroDirective(UndefLoc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000071}
72
73VisibilityMacroDirective *
74Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
75 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000076 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000077}
Chandler Carruthd92d70b2019-01-19 06:36:00 +000078
79/// Read and discard all tokens remaining on the current line until
80/// the tok::eod token is found.
81SourceRange Preprocessor::DiscardUntilEndOfDirective() {
82 Token Tmp;
83 SourceRange Res;
84
85 LexUnexpandedToken(Tmp);
86 Res.setBegin(Tmp.getLocation());
87 while (Tmp.isNot(tok::eod)) {
88 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
89 LexUnexpandedToken(Tmp);
90 }
91 Res.setEnd(Tmp.getLocation());
92 return Res;
93}
94
95/// Enumerates possible cases of #define/#undef a reserved identifier.
Serge Pavlov07c0f042014-12-18 11:14:21 +000096enum MacroDiag {
97 MD_NoWarn, //> Not a reserved identifier
98 MD_KeywordDef, //> Macro hides keyword, enabled by default
99 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
100};
101
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000102/// Checks if the specified identifier is reserved in the specified
Serge Pavlov07c0f042014-12-18 11:14:21 +0000103/// language.
104/// This function does not check if the identifier is a keyword.
105static bool isReservedId(StringRef Text, const LangOptions &Lang) {
106 // C++ [macro.names], C11 7.1.3:
107 // All identifiers that begin with an underscore and either an uppercase
108 // letter or another underscore are always reserved for any use.
109 if (Text.size() >= 2 && Text[0] == '_' &&
110 (isUppercase(Text[1]) || Text[1] == '_'))
111 return true;
112 // C++ [global.names]
113 // Each name that contains a double underscore ... is reserved to the
114 // implementation for any use.
115 if (Lang.CPlusPlus) {
116 if (Text.find("__") != StringRef::npos)
117 return true;
118 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000119 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000120}
121
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +0000122// The -fmodule-name option tells the compiler to textually include headers in
123// the specified module, meaning clang won't build the specified module. This is
124// useful in a number of situations, for instance, when building a library that
125// vends a module map, one might want to avoid hitting intermediate build
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000126// products containimg the the module map or avoid finding the system installed
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +0000127// modulemap for that library.
128static bool isForModuleBuilding(Module *M, StringRef CurrentModule,
129 StringRef ModuleName) {
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +0000130 StringRef TopLevelName = M->getTopLevelModuleName();
131
132 // When building framework Foo, we wanna make sure that Foo *and* Foo_Private
133 // are textually included and no modules are built for both.
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +0000134 if (M->getTopLevelModule()->IsFramework && CurrentModule == ModuleName &&
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +0000135 !CurrentModule.endswith("_Private") && TopLevelName.endswith("_Private"))
136 TopLevelName = TopLevelName.drop_back(8);
137
138 return TopLevelName == CurrentModule;
139}
140
Serge Pavlov07c0f042014-12-18 11:14:21 +0000141static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
142 const LangOptions &Lang = PP.getLangOpts();
143 StringRef Text = II->getName();
144 if (isReservedId(Text, Lang))
145 return MD_ReservedMacro;
146 if (II->isKeyword(Lang))
147 return MD_KeywordDef;
148 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
149 return MD_KeywordDef;
150 return MD_NoWarn;
151}
152
153static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
154 const LangOptions &Lang = PP.getLangOpts();
155 StringRef Text = II->getName();
156 // Do not warn on keyword undef. It is generally harmless and widely used.
157 if (isReservedId(Text, Lang))
158 return MD_ReservedMacro;
159 return MD_NoWarn;
160}
161
Taewook Ohf42103c2016-06-13 20:40:21 +0000162// Return true if we want to issue a diagnostic by default if we
163// encounter this name in a #include with the wrong case. For now,
164// this includes the standard C and C++ headers, Posix headers,
165// and Boost headers. Improper case for these #includes is a
166// potential portability issue.
167static bool warnByDefaultOnWrongCase(StringRef Include) {
168 // If the first component of the path is "boost", treat this like a standard header
169 // for the purposes of diagnostics.
170 if (::llvm::sys::path::begin(Include)->equals_lower("boost"))
171 return true;
172
173 // "condition_variable" is the longest standard header name at 18 characters.
174 // If the include file name is longer than that, it can't be a standard header.
Taewook Oh755e4d22016-06-13 21:55:33 +0000175 static const size_t MaxStdHeaderNameLen = 18u;
Taewook Ohf42103c2016-06-13 20:40:21 +0000176 if (Include.size() > MaxStdHeaderNameLen)
177 return false;
178
179 // Lowercase and normalize the search string.
180 SmallString<32> LowerInclude{Include};
181 for (char &Ch : LowerInclude) {
182 // In the ASCII range?
George Burgess IV5d3bd932016-06-16 02:30:33 +0000183 if (static_cast<unsigned char>(Ch) > 0x7f)
Taewook Ohf42103c2016-06-13 20:40:21 +0000184 return false; // Can't be a standard header
185 // ASCII lowercase:
186 if (Ch >= 'A' && Ch <= 'Z')
187 Ch += 'a' - 'A';
188 // Normalize path separators for comparison purposes.
189 else if (::llvm::sys::path::is_separator(Ch))
190 Ch = '/';
191 }
192
193 // The standard C/C++ and Posix headers
194 return llvm::StringSwitch<bool>(LowerInclude)
195 // C library headers
196 .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
197 .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
198 .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
199 .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
200 .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
201 .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
202
203 // C++ headers for C library facilities
204 .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
205 .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
206 .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
207 .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
208 .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
209 .Case("cwctype", true)
210
211 // C++ library headers
212 .Cases("algorithm", "fstream", "list", "regex", "thread", true)
213 .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
214 .Cases("atomic", "future", "map", "set", "type_traits", true)
215 .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
216 .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
217 .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
218 .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
219 .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
220 .Cases("deque", "istream", "queue", "string", "valarray", true)
221 .Cases("exception", "iterator", "random", "strstream", "vector", true)
222 .Cases("forward_list", "limits", "ratio", "system_error", true)
223
224 // POSIX headers (which aren't also C headers)
225 .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
226 .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
227 .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
228 .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
229 .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
230 .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
231 .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
232 .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
233 .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
234 .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
235 .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
236 .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
237 .Default(false);
238}
239
Serge Pavlov07c0f042014-12-18 11:14:21 +0000240bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
241 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000242 // Missing macro name?
243 if (MacroNameTok.is(tok::eod))
244 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
245
246 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Olivier Goffart90f981b2017-07-14 09:23:40 +0000247 if (!II)
248 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000249
Olivier Goffart90f981b2017-07-14 09:23:40 +0000250 if (II->isCPlusPlusOperatorKeyword()) {
Alp Tokere03e9e12014-05-31 16:32:22 +0000251 // C++ 2.5p2: Alternative tokens behave the same as its primary token
252 // except for their spellings.
253 Diag(MacroNameTok, getLangOpts().MicrosoftExt
254 ? diag::ext_pp_operator_used_as_macro_name
255 : diag::err_pp_operator_used_as_macro_name)
256 << II << MacroNameTok.getKind();
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000257 // Allow #defining |and| and friends for Microsoft compatibility or
258 // recovery when legacy C headers are included in C++.
Alp Tokerb05e0b52014-05-21 06:13:51 +0000259 }
260
Serge Pavlovd024f522014-10-24 17:31:32 +0000261 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000262 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
263 return Diag(MacroNameTok, diag::err_defined_macro_name);
264 }
265
Richard Smith20e883e2015-04-29 23:20:19 +0000266 if (isDefineUndef == MU_Undef) {
267 auto *MI = getMacroInfo(II);
268 if (MI && MI->isBuiltinMacro()) {
269 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
270 // and C++ [cpp.predefined]p4], but allow it as an extension.
271 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
272 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000273 }
274
Serge Pavlov07c0f042014-12-18 11:14:21 +0000275 // If defining/undefining reserved identifier or a keyword, we need to issue
276 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000277 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000278 if (ShadowFlag)
279 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000280 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
Mehdi Amini99d1b292016-10-01 16:38:28 +0000281 (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000282 MacroDiag D = MD_NoWarn;
283 if (isDefineUndef == MU_Define) {
284 D = shouldWarnOnMacroDef(*this, II);
285 }
286 else if (isDefineUndef == MU_Undef)
287 D = shouldWarnOnMacroUndef(*this, II);
288 if (D == MD_KeywordDef) {
289 // We do not want to warn on some patterns widely used in configuration
290 // scripts. This requires analyzing next tokens, so do not issue warnings
291 // now, only inform caller.
292 if (ShadowFlag)
293 *ShadowFlag = true;
294 }
295 if (D == MD_ReservedMacro)
296 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000297 }
298
Alp Tokerb05e0b52014-05-21 06:13:51 +0000299 // Okay, we got a good identifier.
300 return false;
301}
302
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000303/// Lex and validate a macro name, which occurs after a
James Dennettf6333ac2012-06-22 05:46:07 +0000304/// \#define or \#undef.
305///
Serge Pavlovd024f522014-10-24 17:31:32 +0000306/// This sets the token kind to eod and discards the rest of the macro line if
307/// the macro name is invalid.
308///
309/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000310/// \param isDefineUndef Context in which macro is used.
311/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
312void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
313 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 // Read the token, don't allow macro expansion on it.
315 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000316
Douglas Gregor12785102010-08-24 20:21:13 +0000317 if (MacroNameTok.is(tok::code_completion)) {
318 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000319 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000320 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000321 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000322 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000323
Serge Pavlov07c0f042014-12-18 11:14:21 +0000324 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000325 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000326
327 // Invalid macro name, read and discard the rest of the line and set the
328 // token kind to tok::eod if necessary.
329 if (MacroNameTok.isNot(tok::eod)) {
330 MacroNameTok.setKind(tok::eod);
331 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000332 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000333}
334
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000335/// Ensure that the next token is a tok::eod token.
James Dennettf6333ac2012-06-22 05:46:07 +0000336///
337/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000338/// true, then we consider macros that expand to zero tokens as being ok.
Richard Smith8af8b862019-04-11 21:18:23 +0000339///
340/// Returns the location of the end of the directive.
341SourceLocation Preprocessor::CheckEndOfDirective(const char *DirType,
342 bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000343 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000344 // Lex unexpanded tokens for most directives: macros might expand to zero
345 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
346 // #line) allow empty macros.
347 if (EnableMacros)
348 Lex(Tmp);
349 else
350 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000351
Chris Lattnerf64b3522008-03-09 01:54:53 +0000352 // There should be no tokens after the directive, but we allow them as an
353 // extension.
354 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
355 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000356
Richard Smith8af8b862019-04-11 21:18:23 +0000357 if (Tmp.is(tok::eod))
358 return Tmp.getLocation();
359
360 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
361 // or if this is a macro-style preprocessing directive, because it is more
362 // trouble than it is worth to insert /**/ and check that there is no /**/
363 // in the range also.
364 FixItHint Hint;
365 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
366 !CurTokenLexer)
367 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
368 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
369 return DiscardUntilEndOfDirective().getEnd();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000370}
371
James Dennettf6333ac2012-06-22 05:46:07 +0000372/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
373/// decided that the subsequent tokens are in the \#if'd out portion of the
374/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000375/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000376/// this \#if directive, so \#else/\#elif blocks should never be entered.
377/// If ElseOk is true, then \#else directives are ok, if not, then we have
378/// already seen one so a \#else directive is a duplicate. When this returns,
379/// the caller can lex the first valid token.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000380void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
Vedant Kumar3919a502017-09-11 20:47:42 +0000381 SourceLocation IfTokenLoc,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000382 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000383 bool FoundElse,
384 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000386 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000387
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000388 if (PreambleConditionalStack.reachedEOFWhileSkipping())
389 PreambleConditionalStack.clearSkipInfo();
390 else
391 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
392 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000393
Chris Lattnerf64b3522008-03-09 01:54:53 +0000394 // Enter raw mode to disable identifier lookup (and thus macro expansion),
395 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000396 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000397 Token Tok;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000398 while (true) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000399 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000400
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000401 if (Tok.is(tok::code_completion)) {
402 if (CodeComplete)
403 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000404 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000405 continue;
406 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000407
Chris Lattnerf64b3522008-03-09 01:54:53 +0000408 // If this is the end of the buffer, we have an error.
409 if (Tok.is(tok::eof)) {
Ilya Biryukov8f738ac2017-09-12 08:35:57 +0000410 // We don't emit errors for unterminated conditionals here,
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000411 // Lexer::LexEndOfFile can do that properly.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000412 // Just return and let the caller lex after this #include.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000413 if (PreambleConditionalStack.isRecording())
414 PreambleConditionalStack.SkipInfo.emplace(
415 HashTokenLoc, IfTokenLoc, FoundNonSkipPortion, FoundElse, ElseLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000416 break;
417 }
Mike Stump11289f42009-09-09 15:08:12 +0000418
Chris Lattnerf64b3522008-03-09 01:54:53 +0000419 // If this token is not a preprocessor directive, just skip it.
420 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
421 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000422
Chris Lattnerf64b3522008-03-09 01:54:53 +0000423 // We just parsed a # character at the start of a line, so we're in
424 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000425 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000426 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000427 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000428
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattnerf64b3522008-03-09 01:54:53 +0000430 // Read the next token, the directive flavor.
431 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000432
Chris Lattnerf64b3522008-03-09 01:54:53 +0000433 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
434 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000435 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000436 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000437 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000438 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000439 continue;
440 }
441
442 // If the first letter isn't i or e, it isn't intesting to us. We know that
443 // this is safe in the face of spelling differences, because there is no way
444 // to spell an i/e in a strange way that is another letter. Skipping this
445 // allows us to avoid looking up the identifier info for #define/#undef and
446 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000447 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000448
Alp Toker2d57cea2014-05-17 04:53:25 +0000449 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000450 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000451 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000452 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000453 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000454 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000455 continue;
456 }
Mike Stump11289f42009-09-09 15:08:12 +0000457
Chris Lattnerf64b3522008-03-09 01:54:53 +0000458 // Get the identifier name without trigraphs or embedded newlines. Note
459 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
460 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000461 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000462 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000463 if (!Tok.needsCleaning() && RI.size() < 20) {
464 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000465 } else {
466 std::string DirectiveStr = getSpelling(Tok);
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000467 size_t IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000468 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000469 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000470 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000471 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000472 continue;
473 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000474 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000475 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000476 }
Mike Stump11289f42009-09-09 15:08:12 +0000477
Benjamin Kramer144884642009-12-31 13:32:38 +0000478 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000479 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000480 if (Sub.empty() || // "if"
481 Sub == "def" || // "ifdef"
482 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000483 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
484 // bother parsing the condition.
485 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000486 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000487 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000488 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000489 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000490 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000491 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000492 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000493 PPConditionalInfo CondInfo;
494 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000495 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000496 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000497 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattnerf64b3522008-03-09 01:54:53 +0000499 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000500 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000501 // Restore the value of LexingRawMode so that trailing comments
502 // are handled correctly, if we've reached the outermost block.
503 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000504 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000505 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000506 if (Callbacks)
507 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000508 break;
Richard Smithd0124572012-06-21 00:35:03 +0000509 } else {
510 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000511 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000512 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000513 // #else directive in a skipping conditional. If not in some other
514 // skipping conditional, and if #else hasn't already been seen, enter it
515 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000516 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000517
Chris Lattnerf64b3522008-03-09 01:54:53 +0000518 // If this is a #else with a #else before it, report the error.
519 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattnerf64b3522008-03-09 01:54:53 +0000521 // Note that we've seen a #else in this conditional.
522 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000523
Chris Lattnerf64b3522008-03-09 01:54:53 +0000524 // If the conditional is at the top level, and the #if block wasn't
525 // entered, enter the #else block now.
526 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
527 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000528 // Restore the value of LexingRawMode so that trailing comments
529 // are handled correctly.
530 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000531 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000532 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000533 if (Callbacks)
534 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000535 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000536 } else {
537 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000538 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000539 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000540 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000541
John Thompson17c35732013-12-04 20:19:30 +0000542 // If this is a #elif with a #else before it, report the error.
543 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
544
Chris Lattnerf64b3522008-03-09 01:54:53 +0000545 // If this is in a skipping block or if we're already handled this #if
546 // block, don't bother parsing the condition.
Chandler Carruthd92d70b2019-01-19 06:36:00 +0000547 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
548 DiscardUntilEndOfDirective();
549 } else {
550 // Restore the value of LexingRawMode so that identifiers are
551 // looked up, etc, inside the #elif expression.
552 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
553 CurPPLexer->LexingRawMode = false;
554 IdentifierInfo *IfNDefMacro = nullptr;
555 DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
556 const bool CondValue = DER.Conditional;
557 CurPPLexer->LexingRawMode = true;
558 if (Callbacks) {
559 Callbacks->Elif(
560 Tok.getLocation(), DER.ExprRange,
561 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
562 CondInfo.IfLoc);
563 }
564 // If this condition is true, enter it!
565 if (CondValue) {
John Thompson17c35732013-12-04 20:19:30 +0000566 CondInfo.FoundNonSkip = true;
567 break;
568 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000569 }
570 }
571 }
Mike Stump11289f42009-09-09 15:08:12 +0000572
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000573 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000574 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000575 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000576 }
577
578 // Finally, if we are out of the conditional (saw an #endif or ran off the end
579 // of the file, just stop skipping and return to lexing whatever came after
580 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000581 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000582
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000583 // The last skipped range isn't actually skipped yet if it's truncated
584 // by the end of the preamble; we'll resume parsing after the preamble.
585 if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
Vedant Kumar3919a502017-09-11 20:47:42 +0000586 Callbacks->SourceRangeSkipped(
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000587 SourceRange(HashTokenLoc, CurPPLexer->getSourceLocation()),
Vedant Kumar3919a502017-09-11 20:47:42 +0000588 Tok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000589}
590
Richard Smith2a553082015-04-23 22:58:06 +0000591Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000592 if (!SourceMgr.isInMainFile(Loc)) {
593 // Try to determine the module of the include directive.
594 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
595 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
596 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
597 // The include comes from an included file.
598 return HeaderInfo.getModuleMap()
599 .findModuleForHeader(EntryOfIncl)
600 .getModule();
601 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000602 }
Richard Smith7e82e012016-02-19 22:25:36 +0000603
604 // This is either in the main file or not in a file at all. It belongs
605 // to the current module, if there is one.
606 return getLangOpts().CurrentModule.empty()
607 ? nullptr
608 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000609}
610
Richard Smith4eb83932016-04-27 21:57:05 +0000611const FileEntry *
612Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000613 Module *M,
Richard Smith4eb83932016-04-27 21:57:05 +0000614 SourceLocation Loc) {
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000615 assert(M && "no module to include");
616
Richard Smithe867e982019-04-18 00:56:58 +0000617 // If the context is the global module fragment of some module, we never
618 // want to return that file; instead, we want the innermost include-guarded
619 // header that it included.
620 bool InGlobalModuleFragment = M->Kind == Module::GlobalModuleFragment;
621
Richard Smith4eb83932016-04-27 21:57:05 +0000622 // If we have a module import syntax, we shouldn't include a header to
623 // make a particular module visible.
Richard Smithe867e982019-04-18 00:56:58 +0000624 if ((getLangOpts().ObjC || getLangOpts().CPlusPlusModules ||
625 getLangOpts().ModulesTS) &&
626 !InGlobalModuleFragment)
Richard Smith4eb83932016-04-27 21:57:05 +0000627 return nullptr;
628
Richard Smith4eb83932016-04-27 21:57:05 +0000629 Module *TopM = M->getTopLevelModule();
630 Module *IncM = getModuleForLocation(IncLoc);
631
632 // Walk up through the include stack, looking through textual headers of M
633 // until we hit a non-textual header that we can #include. (We assume textual
634 // headers of a module with non-textual headers aren't meant to be used to
635 // import entities from the module.)
636 auto &SM = getSourceManager();
637 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
638 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
639 auto *FE = SM.getFileEntryForID(ID);
Richard Smith040e1262017-06-02 01:55:39 +0000640 if (!FE)
641 break;
Richard Smith4eb83932016-04-27 21:57:05 +0000642
Richard Smithe867e982019-04-18 00:56:58 +0000643 if (InGlobalModuleFragment) {
644 if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE))
645 return FE;
646 Loc = SM.getIncludeLoc(ID);
647 continue;
648 }
649
Richard Smith4eb83932016-04-27 21:57:05 +0000650 bool InTextualHeader = false;
651 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
652 if (!Header.getModule()->isSubModuleOf(TopM))
653 continue;
654
655 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
656 // If this is an accessible, non-textual header of M's top-level module
657 // that transitively includes the given location and makes the
658 // corresponding module visible, this is the thing to #include.
659 if (Header.isAccessibleFrom(IncM))
660 return FE;
661
662 // It's in a private header; we can't #include it.
663 // FIXME: If there's a public header in some module that re-exports it,
664 // then we could suggest including that, but it's not clear that's the
665 // expected way to make this entity visible.
666 continue;
667 }
668
669 InTextualHeader = true;
670 }
671
672 if (!InTextualHeader)
673 break;
674
675 Loc = SM.getIncludeLoc(ID);
676 }
677
678 return nullptr;
679}
680
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000681const FileEntry *Preprocessor::LookupFile(
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000682 SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
683 const DirectoryLookup *FromDir, const FileEntry *FromFile,
684 const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000685 SmallVectorImpl<char> *RelativePath,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000686 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
687 bool *IsFrameworkFound, bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000688 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000689 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000690
Will Wilson0fafd342013-12-27 19:46:16 +0000691 // If the header lookup mechanism may be relative to the current inclusion
692 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000693 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
694 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000695 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000696 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000697 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000698 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner022923a2009-02-04 19:45:07 +0000700 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000701 // predefines buffer or the module includes buffer. Any other file is not
702 // lexed with a normal lexer, so it won't be scanned for preprocessor
703 // directives.
704 //
705 // If we have the predefines buffer, resolve #include references (which come
706 // from the -include command line argument) from the current working
707 // directory instead of relative to the main file.
708 //
709 // If we have the module includes buffer, resolve #include references (which
710 // come from header declarations in the module map) relative to the module
711 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000712 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000713 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000714 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000715 BuildSystemModule = getCurrentModule()->IsSystem;
716 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000717 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000718 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
719 } else {
720 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
721 }
Will Wilson0fafd342013-12-27 19:46:16 +0000722
723 // MSVC searches the current include stack from top to bottom for
724 // headers included by quoted include directives.
725 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000726 if (LangOpts.MSVCCompat && !isAngled) {
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000727 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000728 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000729 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000730 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000731 }
Chris Lattner022923a2009-02-04 19:45:07 +0000732 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000733 }
Mike Stump11289f42009-09-09 15:08:12 +0000734
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000735 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000736
737 if (FromFile) {
738 // We're supposed to start looking from after a particular file. Search
739 // the include path until we find that file or run out of files.
740 const DirectoryLookup *TmpCurDir = CurDir;
741 const DirectoryLookup *TmpFromDir = nullptr;
742 while (const FileEntry *FE = HeaderInfo.LookupFile(
743 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000744 Includers, SearchPath, RelativePath, RequestingModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000745 SuggestedModule, /*IsMapped=*/nullptr,
746 /*IsFrameworkFound=*/nullptr, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000747 // Keep looking as if this file did a #include_next.
748 TmpFromDir = TmpCurDir;
749 ++TmpFromDir;
750 if (FE == FromFile) {
751 // Found it.
752 FromDir = TmpFromDir;
753 CurDir = TmpCurDir;
754 break;
755 }
756 }
757 }
758
759 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000760 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000761 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000762 RelativePath, RequestingModule, SuggestedModule, IsMapped,
763 IsFrameworkFound, SkipCache, BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000764 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000765 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000766 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000767 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
768 Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000769 return FE;
770 }
Mike Stump11289f42009-09-09 15:08:12 +0000771
Will Wilson0fafd342013-12-27 19:46:16 +0000772 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000773 // Otherwise, see if this is a subframework header. If so, this is relative
774 // to one of the headers on the #include stack. Walk the list of the current
775 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000776 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000777 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000778 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000779 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000780 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000781 SuggestedModule))) {
782 if (SuggestedModule && !LangOpts.AsmPreprocessor)
783 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000784 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
785 Filename, FE);
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())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000794 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000795 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +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,
800 FilenameLoc, Filename, FE);
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.
Craig Topperd2d442c2014-05-17 23:10:59 +0000808 return nullptr;
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) {
David Blaikie2eabcc92016-02-09 18:52:09 +00001025 auto Toks = llvm::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.
David Blaikie2eabcc92016-02-09 18:52:09 +00001515 auto Tok = llvm::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
1678/// Handle either a #include-like directive or an import declaration that names
1679/// a header file.
1680///
1681/// \param HashLoc The location of the '#' token for an include, or
1682/// SourceLocation() for an import declaration.
1683/// \param IncludeTok The include / include_next / import token.
1684/// \param FilenameTok The header-name token.
1685/// \param EndLoc The location at which any imported macros become visible.
1686/// \param LookupFrom For #include_next, the starting directory for the
1687/// directory lookup.
1688/// \param LookupFromFile For #include_next, the starting file for the directory
1689/// lookup.
1690Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
1691 SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok,
1692 SourceLocation EndLoc, const DirectoryLookup *LookupFrom,
1693 const FileEntry *LookupFromFile) {
Richard Smithb9b05102019-03-19 01:51:19 +00001694 SmallString<128> FilenameBuffer;
1695 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer);
1696 SourceLocation CharEnd = FilenameTok.getEndLoc();
1697
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001698 CharSourceRange FilenameRange
1699 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001700 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001701 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001702 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Richard Smith8af8b862019-04-11 21:18:23 +00001703
Chris Lattnerf64b3522008-03-09 01:54:53 +00001704 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1705 // error.
Richard Smith8af8b862019-04-11 21:18:23 +00001706 if (Filename.empty())
1707 return {ImportAction::None};
Mike Stump11289f42009-09-09 15:08:12 +00001708
Richard Smith8af8b862019-04-11 21:18:23 +00001709 bool IsImportDecl = HashLoc.isInvalid();
1710 SourceLocation StartLoc = IsImportDecl ? IncludeTok.getLocation() : HashLoc;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001711
John McCall32f5fe12011-09-30 05:12:12 +00001712 // Complain about attempts to #include files in an audit pragma.
1713 if (PragmaARCCFCodeAuditedLoc.isValid()) {
Richard Smith8af8b862019-04-11 21:18:23 +00001714 Diag(StartLoc, diag::err_pp_include_in_arc_cf_code_audited) << IsImportDecl;
John McCall32f5fe12011-09-30 05:12:12 +00001715 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1716
1717 // Immediately leave the pragma.
1718 PragmaARCCFCodeAuditedLoc = SourceLocation();
1719 }
1720
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001721 // Complain about attempts to #include files in an assume-nonnull pragma.
1722 if (PragmaAssumeNonNullLoc.isValid()) {
Richard Smith8af8b862019-04-11 21:18:23 +00001723 Diag(StartLoc, diag::err_pp_include_in_assume_nonnull) << IsImportDecl;
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001724 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1725
1726 // Immediately leave the pragma.
1727 PragmaAssumeNonNullLoc = SourceLocation();
1728 }
1729
Aaron Ballman611306e2012-03-02 22:51:54 +00001730 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001731 // Map the filename with the brackets still attached. If the name doesn't
1732 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001733 // spelling for.
1734 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1735 if (!NewName.empty())
1736 Filename = NewName;
1737 }
1738
Chris Lattnerf64b3522008-03-09 01:54:53 +00001739 // Search include directories.
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001740 bool IsMapped = false;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001741 bool IsFrameworkFound = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001742 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001743 SmallString<1024> SearchPath;
1744 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001745 // We get the raw path only if we have 'Callbacks' to which we later pass
1746 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001747 ModuleMap::KnownHeader SuggestedModule;
1748 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001749 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001750 if (LangOpts.MSVCCompat) {
1751 NormalizedPath = Filename.str();
Nico Weber1865df42018-04-27 19:11:14 +00001752#ifndef _WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001753 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001754#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001755 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001756 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001757 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001758 isAngled, LookupFrom, LookupFromFile, CurDir,
1759 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001760 &SuggestedModule, &IsMapped, &IsFrameworkFound);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001761
Richard Smithdbbc5232015-05-14 02:25:44 +00001762 if (!File) {
1763 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001764 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001765 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001766 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1767 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1768 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001769 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001770 HeaderInfo.AddSearchPath(DL, isAngled);
Taewook Oh755e4d22016-06-13 21:55:33 +00001771
Douglas Gregor11729f02011-11-30 18:12:06 +00001772 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001773 File = LookupFile(
1774 FilenameLoc,
1775 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1776 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001777 &SuggestedModule, &IsMapped, /*IsFrameworkFound=*/nullptr,
1778 /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001779 }
1780 }
1781 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001782
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001783 if (!SuppressIncludeNotFoundError) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001784 // If the file could not be located and it was included via angle
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001785 // brackets, we can attempt a lookup as though it were a quoted path to
1786 // provide the user with a possible fixit.
1787 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001788 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001789 FilenameLoc,
1790 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1791 LookupFrom, LookupFromFile, CurDir,
1792 Callbacks ? &SearchPath : nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001793 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
1794 /*IsFrameworkFound=*/nullptr);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001795 if (File) {
Richard Smithb9b05102019-03-19 01:51:19 +00001796 Diag(FilenameTok,
1797 diag::err_pp_file_not_found_angled_include_not_fatal)
Richard Smith8af8b862019-04-11 21:18:23 +00001798 << Filename << IsImportDecl
Richard Smithb9b05102019-03-19 01:51:19 +00001799 << FixItHint::CreateReplacement(FilenameRange,
1800 "\"" + Filename.str() + "\"");
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001801 }
1802 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001803
Richard Smith2ce63b42018-09-13 21:10:08 +00001804 // Check for likely typos due to leading or trailing non-isAlphanumeric
1805 // characters
Eric Christopher918b47f2018-09-20 17:21:56 +00001806 StringRef OriginalFilename = Filename;
Haojian Wudea57712018-10-02 13:59:49 +00001807 if (LangOpts.SpellChecking && !File) {
Haojian Wu1743ebe2018-10-01 14:38:43 +00001808 // A heuristic to correct a typo file name by removing leading and
1809 // trailing non-isAlphanumeric characters.
1810 auto CorrectTypoFilename = [](llvm::StringRef Filename) {
1811 Filename = Filename.drop_until(isAlphanumeric);
1812 while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
1813 Filename = Filename.drop_back();
1814 }
1815 return Filename;
1816 };
Haojian Wu714e9712018-10-02 14:42:51 +00001817 StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
Volodymyr Sapsai3bbdd872019-01-15 20:08:23 +00001818 SmallString<128> NormalizedTypoCorrectionPath;
1819 if (LangOpts.MSVCCompat) {
1820 NormalizedTypoCorrectionPath = TypoCorrectionName.str();
1821#ifndef _WIN32
1822 llvm::sys::path::native(NormalizedTypoCorrectionPath);
1823#endif
1824 }
Richard Smith2ce63b42018-09-13 21:10:08 +00001825 File = LookupFile(
1826 FilenameLoc,
Volodymyr Sapsai3bbdd872019-01-15 20:08:23 +00001827 LangOpts.MSVCCompat ? NormalizedTypoCorrectionPath.c_str()
1828 : TypoCorrectionName,
Haojian Wu714e9712018-10-02 14:42:51 +00001829 isAngled, LookupFrom, LookupFromFile, CurDir,
Richard Smith2ce63b42018-09-13 21:10:08 +00001830 Callbacks ? &SearchPath : nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001831 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
1832 /*IsFrameworkFound=*/nullptr);
Richard Smith2ce63b42018-09-13 21:10:08 +00001833 if (File) {
Richard Smithb9b05102019-03-19 01:51:19 +00001834 auto Hint =
1835 isAngled
1836 ? FixItHint::CreateReplacement(
1837 FilenameRange, "<" + TypoCorrectionName.str() + ">")
1838 : FixItHint::CreateReplacement(
1839 FilenameRange, "\"" + TypoCorrectionName.str() + "\"");
Richard Smith2ce63b42018-09-13 21:10:08 +00001840 Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
Haojian Wu714e9712018-10-02 14:42:51 +00001841 << OriginalFilename << TypoCorrectionName << Hint;
1842 // We found the file, so set the Filename to the name after typo
1843 // correction.
1844 Filename = TypoCorrectionName;
Richard Smith2ce63b42018-09-13 21:10:08 +00001845 }
1846 }
1847
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001848 // If the file is still not found, just go with the vanilla diagnostic
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001849 if (!File) {
Eric Christopher918b47f2018-09-20 17:21:56 +00001850 Diag(FilenameTok, diag::err_pp_file_not_found) << OriginalFilename
Erik Verbruggen45449542016-10-25 10:13:10 +00001851 << FilenameRange;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001852 if (IsFrameworkFound) {
1853 size_t SlashPos = OriginalFilename.find('/');
1854 assert(SlashPos != StringRef::npos &&
1855 "Include with framework name should have '/' in the filename");
1856 StringRef FrameworkName = OriginalFilename.substr(0, SlashPos);
1857 FrameworkCacheEntry &CacheEntry =
1858 HeaderInfo.LookupFrameworkCache(FrameworkName);
1859 assert(CacheEntry.Directory && "Found framework should be in cache");
1860 Diag(FilenameTok, diag::note_pp_framework_without_header)
1861 << OriginalFilename.substr(SlashPos + 1) << FrameworkName
1862 << CacheEntry.Directory->getName();
1863 }
1864 }
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001865 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001866 }
1867
Erich Keane76675de2018-07-05 17:22:13 +00001868 if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
1869 if (isPCHThroughHeader(File))
1870 SkippingUntilPCHThroughHeader = false;
Richard Smith8af8b862019-04-11 21:18:23 +00001871 return {ImportAction::None};
Erich Keane76675de2018-07-05 17:22:13 +00001872 }
1873
Nikolai Kosjar3c28a2d2019-05-10 10:25:35 +00001874 // Check for circular inclusion of the main file.
1875 // We can't generate a consistent preamble with regard to the conditional
1876 // stack if the main file is included again as due to the preamble bounds
1877 // some directives (e.g. #endif of a header guard) will never be seen.
1878 // Since this will lead to confusing errors, avoid the inclusion.
1879 if (File && PreambleConditionalStack.isRecording() &&
1880 SourceMgr.translateFile(File) == SourceMgr.getMainFileID()) {
1881 Diag(FilenameTok.getLocation(),
1882 diag::err_pp_including_mainfile_in_preamble);
1883 return {ImportAction::None};
1884 }
1885
Richard Smith86559dc2019-03-21 19:44:17 +00001886 // Should we enter the source file? Set to Skip if either the source file is
Richard Smith63b6fce2015-05-18 04:45:41 +00001887 // known to have no effect beyond its effect on module visibility -- that is,
Richard Smith86559dc2019-03-21 19:44:17 +00001888 // if it's got an include guard that is already defined, set to Import if it
1889 // is a modular header we've already built and should import.
1890 enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter;
Richard Smithdbbc5232015-05-14 02:25:44 +00001891
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001892 if (PPOpts->SingleFileParseMode)
Richard Smith86559dc2019-03-21 19:44:17 +00001893 Action = IncludeLimitReached;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001894
Volodymyr Sapsai978be4c12018-12-07 20:29:54 +00001895 // If we've reached the max allowed include depth, it is usually due to an
1896 // include cycle. Don't enter already processed files again as it can lead to
1897 // reaching the max allowed include depth again.
Richard Smith86559dc2019-03-21 19:44:17 +00001898 if (Action == Enter && HasReachedMaxIncludeDepth && File &&
Volodymyr Sapsai978be4c12018-12-07 20:29:54 +00001899 HeaderInfo.getFileInfo(File).NumIncludes)
Richard Smith86559dc2019-03-21 19:44:17 +00001900 Action = IncludeLimitReached;
Volodymyr Sapsai482070b2018-07-25 19:16:26 +00001901
Richard Smith63b6fce2015-05-18 04:45:41 +00001902 // Determine whether we should try to import the module for this #include, if
1903 // there is one. Don't do so if precompiled module support is disabled or we
1904 // are processing this module textually (because we're building the module).
Richard Smith86559dc2019-03-21 19:44:17 +00001905 if (Action == Enter && File && SuggestedModule && getLangOpts().Modules &&
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +00001906 !isForModuleBuilding(SuggestedModule.getModule(),
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00001907 getLangOpts().CurrentModule,
1908 getLangOpts().ModuleName)) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001909 // If this include corresponds to a module but that module is
1910 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001911 // FIXME: Remove this; loadModule does the same check (but produces
1912 // slightly worse diagnostics).
Richard Smith27e5aa02017-06-05 18:57:56 +00001913 if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
1914 SuggestedModule.getModule())) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001915 Diag(FilenameTok.getLocation(),
1916 diag::note_implicit_top_level_module_import_here)
Richard Smith27e5aa02017-06-05 18:57:56 +00001917 << SuggestedModule.getModule()->getTopLevelModuleName();
Richard Smith8af8b862019-04-11 21:18:23 +00001918 return {ImportAction::None};
Sean Silva8b7c0392015-08-17 16:39:30 +00001919 }
1920
Douglas Gregor71944202011-11-30 00:36:36 +00001921 // Compute the module access path corresponding to this module.
1922 // FIXME: Should we have a second loadModule() overload to avoid this
1923 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001924 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001925 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001926 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1927 FilenameTok.getLocation()));
1928 std::reverse(Path.begin(), Path.end());
1929
Douglas Gregor41e115a2011-11-30 18:02:36 +00001930 // Warn that we're replacing the include/import with a module import.
Richard Smith8af8b862019-04-11 21:18:23 +00001931 if (!IsImportDecl)
1932 diagnoseAutoModuleImport(*this, StartLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001933
Richard Smith10434f32015-05-02 02:08:26 +00001934 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001935 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001936 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1937 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001938 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1939 IncludeTok.getLocation(), Path, Module::Hidden,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001940 /*IsInclusionDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001941 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001942 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001943
Richard Smith86559dc2019-03-21 19:44:17 +00001944 if (Imported) {
1945 Action = Import;
1946 } else if (Imported.isMissingExpected()) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001947 // We failed to find a submodule that we assumed would exist (because it
1948 // was in the directory of an umbrella header, for instance), but no
Richard Smitha114c462016-12-06 00:40:17 +00001949 // actual module containing it exists (because the umbrella header is
Richard Smith63b6fce2015-05-18 04:45:41 +00001950 // incomplete). Treat this as a textual inclusion.
1951 SuggestedModule = ModuleMap::KnownHeader();
Richard Smitha114c462016-12-06 00:40:17 +00001952 } else if (Imported.isConfigMismatch()) {
1953 // On a configuration mismatch, enter the header textually. We still know
1954 // that it's part of the corresponding module.
Richard Smith63b6fce2015-05-18 04:45:41 +00001955 } else {
1956 // We hit an error processing the import. Bail out.
1957 if (hadModuleLoaderFatalFailure()) {
1958 // With a fatal failure in the module loader, we abort parsing.
1959 Token &Result = IncludeTok;
Erich Keane0a6b5b62018-12-04 14:34:09 +00001960 assert(CurLexer && "#include but no current lexer set!");
1961 Result.startToken();
1962 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1963 CurLexer->cutOffLexing();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001964 }
Richard Smith8af8b862019-04-11 21:18:23 +00001965 return {ImportAction::None};
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001966 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001967 }
1968
Richard Smithc5247e62017-05-30 02:03:19 +00001969 // The #included file will be considered to be a system header if either it is
1970 // in a system include directory, or if the #includer is a system include
1971 // header.
1972 SrcMgr::CharacteristicKind FileCharacter =
1973 SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
1974 if (File)
1975 FileCharacter = std::max(HeaderInfo.getFileDirFlavor(File), FileCharacter);
1976
Richard Smith8af8b862019-04-11 21:18:23 +00001977 // If this is a '#import' or an import-declaration, don't re-enter the file.
1978 //
1979 // FIXME: If we have a suggested module for a '#include', and we've already
1980 // visited this file, don't bother entering it again. We know it has no
1981 // further effect.
1982 bool EnterOnce =
1983 IsImportDecl ||
1984 IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import;
1985
Richard Smithc5247e62017-05-30 02:03:19 +00001986 // Ask HeaderInfo if we should enter this #include file. If not, #including
1987 // this file will have no effect.
Richard Smith86559dc2019-03-21 19:44:17 +00001988 if (Action == Enter && File &&
Richard Smith8af8b862019-04-11 21:18:23 +00001989 !HeaderInfo.ShouldEnterIncludeFile(*this, File, EnterOnce,
Richard Smithc5247e62017-05-30 02:03:19 +00001990 getLangOpts().Modules,
1991 SuggestedModule.getModule())) {
Richard Smith86559dc2019-03-21 19:44:17 +00001992 // Even if we've already preprocessed this header once and know that we
1993 // don't need to see its contents again, we still need to import it if it's
1994 // modular because we might not have imported it from this submodule before.
1995 //
1996 // FIXME: We don't do this when compiling a PCH because the AST
1997 // serialization layer can't cope with it. This means we get local
1998 // submodule visibility semantics wrong in that case.
1999 Action = (SuggestedModule && !getLangOpts().CompilingPCH) ? Import : Skip;
Richard Smithc5247e62017-05-30 02:03:19 +00002000 }
2001
Richard Smith8af8b862019-04-11 21:18:23 +00002002 if (Callbacks && !IsImportDecl) {
Richard Smith63b6fce2015-05-18 04:45:41 +00002003 // Notify the callback object that we've seen an inclusion directive.
Richard Smith8af8b862019-04-11 21:18:23 +00002004 // FIXME: Use a different callback for a pp-import?
Richard Smith63b6fce2015-05-18 04:45:41 +00002005 Callbacks->InclusionDirective(
2006 HashLoc, IncludeTok,
2007 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
2008 FilenameRange, File, SearchPath, RelativePath,
Richard Smith86559dc2019-03-21 19:44:17 +00002009 Action == Import ? SuggestedModule.getModule() : nullptr,
2010 FileCharacter);
2011 if (Action == Skip)
Richard Smithc5247e62017-05-30 02:03:19 +00002012 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Douglas Gregor97eec242011-09-15 22:00:41 +00002013 }
Richard Smith63b6fce2015-05-18 04:45:41 +00002014
2015 if (!File)
Richard Smith8af8b862019-04-11 21:18:23 +00002016 return {ImportAction::None};
Taewook Oh755e4d22016-06-13 21:55:33 +00002017
Richard Smith8af8b862019-04-11 21:18:23 +00002018 // If this is a C++20 pp-import declaration, diagnose if we didn't find any
2019 // module corresponding to the named header.
2020 if (IsImportDecl && !SuggestedModule) {
2021 Diag(FilenameTok, diag::err_header_import_not_header_unit)
2022 << OriginalFilename << File->getName();
2023 return {ImportAction::None};
2024 }
Richard Smith54ef4c32015-05-19 19:58:11 +00002025
Taewook Ohf42103c2016-06-13 20:40:21 +00002026 // Issue a diagnostic if the name of the file on disk has a different case
2027 // than the one we're about to open.
2028 const bool CheckIncludePathPortability =
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00002029 !IsMapped && File && !File->tryGetRealPathName().empty();
Taewook Ohf42103c2016-06-13 20:40:21 +00002030
2031 if (CheckIncludePathPortability) {
2032 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
2033 StringRef RealPathName = File->tryGetRealPathName();
2034 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
2035 llvm::sys::path::end(Name));
2036
2037 if (trySimplifyPath(Components, RealPathName)) {
2038 SmallString<128> Path;
2039 Path.reserve(Name.size()+2);
2040 Path.push_back(isAngled ? '<' : '"');
Taewook Ohcc89bac2017-02-21 22:30:55 +00002041 bool isLeadingSeparator = llvm::sys::path::is_absolute(Name);
Taewook Ohf42103c2016-06-13 20:40:21 +00002042 for (auto Component : Components) {
Taewook Ohcc89bac2017-02-21 22:30:55 +00002043 if (isLeadingSeparator)
2044 isLeadingSeparator = false;
2045 else
2046 Path.append(Component);
Taewook Ohf42103c2016-06-13 20:40:21 +00002047 // Append the separator the user used, or the close quote
2048 Path.push_back(
2049 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
2050 (isAngled ? '>' : '"'));
2051 }
Taewook Ohf42103c2016-06-13 20:40:21 +00002052 // For user files and known standard headers, by default we issue a diagnostic.
2053 // For other system headers, we don't. They can be controlled separately.
2054 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
2055 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
Reid Kleckner273895b2017-02-14 18:38:40 +00002056 Diag(FilenameTok, DiagId) << Path <<
Richard Smithb9b05102019-03-19 01:51:19 +00002057 FixItHint::CreateReplacement(FilenameRange, Path);
Taewook Ohf42103c2016-06-13 20:40:21 +00002058 }
2059 }
2060
Richard Smith86559dc2019-03-21 19:44:17 +00002061 switch (Action) {
2062 case Skip:
2063 // If we don't need to enter the file, stop now.
Richard Smithd652bdd2019-04-14 08:06:59 +00002064 if (Module *M = SuggestedModule.getModule())
2065 return {ImportAction::SkippedModuleImport, M};
Richard Smith8af8b862019-04-11 21:18:23 +00002066 return {ImportAction::None};
Richard Smith86559dc2019-03-21 19:44:17 +00002067
2068 case IncludeLimitReached:
2069 // If we reached our include limit and don't want to enter any more files,
2070 // don't go any further.
Richard Smith8af8b862019-04-11 21:18:23 +00002071 return {ImportAction::None};
Richard Smith86559dc2019-03-21 19:44:17 +00002072
2073 case Import: {
2074 // If this is a module import, make it visible if needed.
2075 Module *M = SuggestedModule.getModule();
2076 assert(M && "no module to import");
2077
Richard Smith8af8b862019-04-11 21:18:23 +00002078 makeModuleVisible(M, EndLoc);
Richard Smith86559dc2019-03-21 19:44:17 +00002079
Richard Smith8af8b862019-04-11 21:18:23 +00002080 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() ==
Richard Smith86559dc2019-03-21 19:44:17 +00002081 tok::pp___include_macros)
Richard Smith8af8b862019-04-11 21:18:23 +00002082 return {ImportAction::None};
2083
2084 return {ImportAction::ModuleImport, M};
Richard Smith86559dc2019-03-21 19:44:17 +00002085 }
2086
2087 case Enter:
2088 break;
Chris Lattner72286d62010-04-19 20:44:31 +00002089 }
2090
Richard Smith5a8ea4c2019-03-19 01:51:17 +00002091 // Check that we don't have infinite #include recursion.
2092 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
2093 Diag(FilenameTok, diag::err_pp_include_too_deep);
2094 HasReachedMaxIncludeDepth = true;
Richard Smith8af8b862019-04-11 21:18:23 +00002095 return {ImportAction::None};
Richard Smith5a8ea4c2019-03-19 01:51:17 +00002096 }
2097
Chris Lattnerf64b3522008-03-09 01:54:53 +00002098 // Look up the file, create a File ID for it.
Richard Smithb9b05102019-03-19 01:51:19 +00002099 SourceLocation IncludePos = FilenameTok.getLocation();
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002100 // If the filename string was the result of macro expansions, set the include
2101 // position on the file where it will be included and after the expansions.
2102 if (IncludePos.isMacroID())
Richard Smithb5f81712018-04-30 05:25:48 +00002103 IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002104 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002105 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002106
Richard Smith34f30512013-11-23 04:06:09 +00002107 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002108 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
Richard Smith8af8b862019-04-11 21:18:23 +00002109 return {ImportAction::None};
Richard Smith34f30512013-11-23 04:06:09 +00002110
Richard Smitha0aafa32015-05-18 03:52:30 +00002111 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002112 if (auto *M = SuggestedModule.getModule()) {
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00002113 if (M->getTopLevelModule()->ShadowingModule) {
2114 // We are building a submodule that belongs to a shadowed module. This
2115 // means we find header files in the shadowed module.
2116 Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule)
2117 << M->getFullModuleName();
2118 Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc,
2119 diag::note_previous_definition);
Richard Smith8af8b862019-04-11 21:18:23 +00002120 return {ImportAction::None};
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00002121 }
Manman Renffd3e9d2017-01-09 19:20:18 +00002122 // When building a pch, -fmodule-name tells the compiler to textually
2123 // include headers in the specified module. We are not building the
2124 // specified module.
Richard Smith86559dc2019-03-21 19:44:17 +00002125 //
2126 // FIXME: This is the wrong way to handle this. We should produce a PCH
2127 // that behaves the same as the header would behave in a compilation using
2128 // that PCH, which means we should enter the submodule. We need to teach
2129 // the AST serialization layer to deal with the resulting AST.
Manman Renffd3e9d2017-01-09 19:20:18 +00002130 if (getLangOpts().CompilingPCH &&
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00002131 isForModuleBuilding(M, getLangOpts().CurrentModule,
2132 getLangOpts().ModuleName))
Richard Smith8af8b862019-04-11 21:18:23 +00002133 return {ImportAction::None};
Manman Renffd3e9d2017-01-09 19:20:18 +00002134
Richard Smithd1386302017-05-04 00:29:54 +00002135 assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2136 CurLexerSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002137
Richard Smitha0aafa32015-05-18 03:52:30 +00002138 // Let the macro handling code know that any future macros are within
2139 // the new submodule.
Richard Smith8af8b862019-04-11 21:18:23 +00002140 EnterSubmodule(M, EndLoc, /*ForPragma*/false);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002141
Richard Smitha0aafa32015-05-18 03:52:30 +00002142 // Let the parser know that any future declarations are within the new
2143 // submodule.
2144 // FIXME: There's no point doing this if we're handling a #__include_macros
2145 // directive.
Richard Smith8af8b862019-04-11 21:18:23 +00002146 return {ImportAction::ModuleBegin, M};
Richard Smith67294e22014-01-31 20:47:44 +00002147 }
Richard Smith8af8b862019-04-11 21:18:23 +00002148
Richard Smithd652bdd2019-04-14 08:06:59 +00002149 assert(!IsImportDecl && "failed to diagnose missing module for import decl");
Richard Smith8af8b862019-04-11 21:18:23 +00002150 return {ImportAction::None};
Chris Lattnerf64b3522008-03-09 01:54:53 +00002151}
2152
James Dennettf6333ac2012-06-22 05:46:07 +00002153/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002154///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002155void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2156 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002157 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002158
Chris Lattnerf64b3522008-03-09 01:54:53 +00002159 // #include_next is like #include, except that we start searching after
2160 // the current found directory. If we can't do this, issue a
2161 // diagnostic.
2162 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002163 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00002164 if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2165 // If the main file is a header, then it's either for PCH/AST generation,
2166 // or libclang opened it. Either way, handle it as a normal include below
2167 // and do not complain about include_next.
2168 } else if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002169 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002170 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smithd1386302017-05-04 00:29:54 +00002171 } else if (CurLexerSubmodule) {
Richard Smith25d50752014-10-20 00:15:49 +00002172 // Start looking up in the directory *after* the one in which the current
2173 // file would be found, if any.
2174 assert(CurPPLexer && "#include_next directive in macro?");
2175 LookupFromFile = CurPPLexer->getFileEntry();
2176 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002177 } else if (!Lookup) {
Richard Smith6d69fec2019-03-21 20:42:13 +00002178 // The current file was not found by walking the include path. Either it
2179 // is the primary file (handled above), or it was found by absolute path,
2180 // or it was found relative to such a file.
2181 // FIXME: Track enough information so we know which case we're in.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002182 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2183 } else {
2184 // Start looking up in the next directory.
2185 ++Lookup;
2186 }
Mike Stump11289f42009-09-09 15:08:12 +00002187
Richard Smith25d50752014-10-20 00:15:49 +00002188 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2189 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002190}
2191
James Dennettf6333ac2012-06-22 05:46:07 +00002192/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002193void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2194 // The Microsoft #import directive takes a type library and generates header
2195 // files from it, and includes those. This is beyond the scope of what clang
2196 // does, so we ignore it and error out. However, #import can optionally have
2197 // trailing attributes that span multiple lines. We're going to eat those
2198 // so we can continue processing from there.
2199 Diag(Tok, diag::err_pp_import_directive_ms );
2200
Taewook Oh755e4d22016-06-13 21:55:33 +00002201 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002202 // directive can be split over multiple lines using the backslash character.
2203 DiscardUntilEndOfDirective();
2204}
2205
James Dennettf6333ac2012-06-22 05:46:07 +00002206/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002207///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002208void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2209 Token &ImportTok) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002210 if (!LangOpts.ObjC) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002211 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002212 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002213 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002214 }
Richard Smith8af8b862019-04-11 21:18:23 +00002215 return HandleIncludeDirective(HashLoc, ImportTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002216}
2217
Chris Lattner58a1eb02009-04-08 18:46:40 +00002218/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2219/// pseudo directive in the predefines buffer. This handles it by sucking all
2220/// tokens through the preprocessor and discarding them (only keeping the side
2221/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002222void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2223 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002224 // This directive should only occur in the predefines buffer. If not, emit an
2225 // error and reject it.
2226 SourceLocation Loc = IncludeMacrosTok.getLocation();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002227 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002228 Diag(IncludeMacrosTok.getLocation(),
2229 diag::pp_include_macros_out_of_predefines);
2230 DiscardUntilEndOfDirective();
2231 return;
2232 }
Mike Stump11289f42009-09-09 15:08:12 +00002233
Chris Lattnere01d82b2009-04-08 20:53:24 +00002234 // Treat this as a normal #include for checking purposes. If this is
2235 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002236 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002237
Chris Lattnere01d82b2009-04-08 20:53:24 +00002238 Token TmpTok;
2239 do {
2240 Lex(TmpTok);
2241 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2242 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002243}
2244
Chris Lattnerf64b3522008-03-09 01:54:53 +00002245//===----------------------------------------------------------------------===//
2246// Preprocessor Macro Directive Handling.
2247//===----------------------------------------------------------------------===//
2248
Faisal Valie8f430a2017-09-29 02:43:22 +00002249/// ReadMacroParameterList - The ( starting a parameter list of a macro
2250/// definition has just been read. Lex the rest of the parameters and the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002251/// closing ), updating MI with what we learn. Return true if an error occurs
Faisal Valie8f430a2017-09-29 02:43:22 +00002252/// parsing the param list.
Faisal Valiac506d72017-07-17 17:18:43 +00002253bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
Faisal Vali33df3912017-09-29 02:17:31 +00002254 SmallVector<IdentifierInfo*, 32> Parameters;
Mike Stump11289f42009-09-09 15:08:12 +00002255
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002256 while (true) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002257 LexUnexpandedToken(Tok);
2258 switch (Tok.getKind()) {
2259 case tok::r_paren:
Faisal Valie8f430a2017-09-29 02:43:22 +00002260 // Found the end of the parameter list.
Faisal Vali33df3912017-09-29 02:17:31 +00002261 if (Parameters.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002262 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002263 // Otherwise we have #define FOO(A,)
2264 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2265 return true;
2266 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002267 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002268 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002269 diag::warn_cxx98_compat_variadic_macro :
2270 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002271
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002272 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2273 if (LangOpts.OpenCL) {
Anastasia Stulova545652b2019-03-26 11:22:37 +00002274 Diag(Tok, diag::ext_pp_opencl_variadic_macros);
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002275 }
2276
Chris Lattnerf64b3522008-03-09 01:54:53 +00002277 // Lex the token after the identifier.
2278 LexUnexpandedToken(Tok);
2279 if (Tok.isNot(tok::r_paren)) {
2280 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2281 return true;
2282 }
Faisal Valie8f430a2017-09-29 02:43:22 +00002283 // Add the __VA_ARGS__ identifier as a parameter.
Faisal Vali33df3912017-09-29 02:17:31 +00002284 Parameters.push_back(Ident__VA_ARGS__);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002285 MI->setIsC99Varargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002286 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002287 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002288 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002289 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2290 return true;
2291 default:
2292 // Handle keywords and identifiers here to accept things like
2293 // #define Foo(for) for.
2294 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002295 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002296 // #define X(1
2297 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2298 return true;
2299 }
2300
Faisal Valie8f430a2017-09-29 02:43:22 +00002301 // If this is already used as a parameter, it is used multiple times (e.g.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002302 // #define X(A,A.
Fangrui Song75e74e02019-03-31 08:48:19 +00002303 if (llvm::find(Parameters, II) != Parameters.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002304 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002305 return true;
2306 }
Mike Stump11289f42009-09-09 15:08:12 +00002307
Faisal Valie8f430a2017-09-29 02:43:22 +00002308 // Add the parameter to the macro info.
Faisal Vali33df3912017-09-29 02:17:31 +00002309 Parameters.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002310
Chris Lattnerf64b3522008-03-09 01:54:53 +00002311 // Lex the token after the identifier.
2312 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002313
Chris Lattnerf64b3522008-03-09 01:54:53 +00002314 switch (Tok.getKind()) {
2315 default: // #define X(A B
2316 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2317 return true;
2318 case tok::r_paren: // #define X(A)
Faisal Vali33df3912017-09-29 02:17:31 +00002319 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002320 return false;
2321 case tok::comma: // #define X(A,
2322 break;
2323 case tok::ellipsis: // #define X(A... -> GCC extension
2324 // Diagnose extension.
2325 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002326
Chris Lattnerf64b3522008-03-09 01:54:53 +00002327 // Lex the token after the identifier.
2328 LexUnexpandedToken(Tok);
2329 if (Tok.isNot(tok::r_paren)) {
2330 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2331 return true;
2332 }
Mike Stump11289f42009-09-09 15:08:12 +00002333
Chris Lattnerf64b3522008-03-09 01:54:53 +00002334 MI->setIsGNUVarargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002335 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002336 return false;
2337 }
2338 }
2339 }
2340}
2341
Serge Pavlov07c0f042014-12-18 11:14:21 +00002342static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2343 const LangOptions &LOptions) {
2344 if (MI->getNumTokens() == 1) {
2345 const Token &Value = MI->getReplacementToken(0);
2346
2347 // Macro that is identity, like '#define inline inline' is a valid pattern.
2348 if (MacroName.getKind() == Value.getKind())
2349 return true;
2350
2351 // Macro that maps a keyword to the same keyword decorated with leading/
2352 // trailing underscores is a valid pattern:
2353 // #define inline __inline
2354 // #define inline __inline__
2355 // #define inline _inline (in MS compatibility mode)
2356 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2357 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2358 if (!II->isKeyword(LOptions))
2359 return false;
2360 StringRef ValueText = II->getName();
2361 StringRef TrimmedValue = ValueText;
2362 if (!ValueText.startswith("__")) {
2363 if (ValueText.startswith("_"))
2364 TrimmedValue = TrimmedValue.drop_front(1);
2365 else
2366 return false;
2367 } else {
2368 TrimmedValue = TrimmedValue.drop_front(2);
2369 if (TrimmedValue.endswith("__"))
2370 TrimmedValue = TrimmedValue.drop_back(2);
2371 }
2372 return TrimmedValue.equals(MacroText);
2373 } else {
2374 return false;
2375 }
2376 }
2377
2378 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002379 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2380 tok::kw_const) &&
2381 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002382}
2383
Faisal Valiac506d72017-07-17 17:18:43 +00002384// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2385// entire line) of the macro's tokens and adds them to MacroInfo, and while
2386// doing so performs certain validity checks including (but not limited to):
2387// - # (stringization) is followed by a macro parameter
2388//
2389// Returns a nullptr if an invalid sequence of tokens is encountered or returns
2390// a pointer to a MacroInfo object.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002391
Faisal Valiac506d72017-07-17 17:18:43 +00002392MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2393 const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002394
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002395 Token LastTok = MacroNameTok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002396 // Create the new macro.
Faisal Valiac506d72017-07-17 17:18:43 +00002397 MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002398
Chris Lattnerf64b3522008-03-09 01:54:53 +00002399 Token Tok;
2400 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002401
Faisal Vali6bf67912017-07-25 03:15:36 +00002402 // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2403 // within their appropriate context.
2404 VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2405
Chris Lattnerf64b3522008-03-09 01:54:53 +00002406 // If this is a function-like macro definition, parse the argument list,
2407 // marking each of the identifiers as being used as macro arguments. Also,
2408 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002409 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002410 if (ImmediatelyAfterHeaderGuard) {
2411 // Save this macro information since it may part of a header guard.
2412 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2413 MacroNameTok.getLocation());
2414 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002415 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002416 } else if (Tok.hasLeadingSpace()) {
2417 // This is a normal token with leading space. Clear the leading space
2418 // marker on the first token to get proper expansion.
2419 Tok.clearFlag(Token::LeadingSpace);
2420 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002421 // This is a function-like macro definition. Read the argument list.
2422 MI->setIsFunctionLike();
Faisal Valiac506d72017-07-17 17:18:43 +00002423 if (ReadMacroParameterList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002424 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002425 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002426 DiscardUntilEndOfDirective();
Faisal Valiac506d72017-07-17 17:18:43 +00002427 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002428 }
2429
Faisal Vali6bf67912017-07-25 03:15:36 +00002430 // If this is a definition of an ISO C/C++ variadic function-like macro (not
2431 // using the GNU named varargs extension) inform our variadic scope guard
2432 // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2433 // allowed only within the definition of a variadic macro.
Mike Stump11289f42009-09-09 15:08:12 +00002434
Faisal Vali6bf67912017-07-25 03:15:36 +00002435 if (MI->isC99Varargs()) {
2436 VariadicMacroScopeGuard.enterScope();
2437 }
Mike Stump11289f42009-09-09 15:08:12 +00002438
Chris Lattnerf64b3522008-03-09 01:54:53 +00002439 // Read the first token after the arg list for down below.
2440 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002441 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002442 // C99 requires whitespace between the macro definition and the body. Emit
2443 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002444 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002445 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002446 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2447 // first character of a replacement list is not a character required by
2448 // subclause 5.2.1, then there shall be white-space separation between the
2449 // identifier and the replacement list.". 5.2.1 lists this set:
2450 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2451 // is irrelevant here.
2452 bool isInvalid = false;
2453 if (Tok.is(tok::at)) // @ is not in the list above.
2454 isInvalid = true;
2455 else if (Tok.is(tok::unknown)) {
2456 // If we have an unknown token, it is something strange like "`". Since
2457 // all of valid characters would have lexed into a single character
2458 // token of some sort, we know this is not a valid case.
2459 isInvalid = true;
2460 }
2461 if (isInvalid)
2462 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2463 else
2464 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002465 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002466
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002467 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002468 LastTok = Tok;
2469
Chris Lattnerf64b3522008-03-09 01:54:53 +00002470 // Read the rest of the macro body.
2471 if (MI->isObjectLike()) {
2472 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002473 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002474 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002475 MI->AddTokenToBody(Tok);
2476 // Get the next token of the macro.
2477 LexUnexpandedToken(Tok);
2478 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002479 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002480 // Otherwise, read the body of a function-like macro. While we are at it,
2481 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2482 // parameters in function-like macro expansions.
Faisal Vali18268422017-10-15 01:26:26 +00002483
2484 VAOptDefinitionContext VAOCtx(*this);
2485
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002486 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002487 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002488
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002489 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002490 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002491
Faisal Vali18268422017-10-15 01:26:26 +00002492 if (VAOCtx.isVAOptToken(Tok)) {
2493 // If we're already within a VAOPT, emit an error.
2494 if (VAOCtx.isInVAOpt()) {
2495 Diag(Tok, diag::err_pp_vaopt_nested_use);
2496 return nullptr;
2497 }
2498 // Ensure VAOPT is followed by a '(' .
2499 LexUnexpandedToken(Tok);
2500 if (Tok.isNot(tok::l_paren)) {
2501 Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
2502 return nullptr;
2503 }
2504 MI->AddTokenToBody(Tok);
2505 VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
2506 LexUnexpandedToken(Tok);
2507 if (Tok.is(tok::hashhash)) {
2508 Diag(Tok, diag::err_vaopt_paste_at_start);
2509 return nullptr;
2510 }
2511 continue;
2512 } else if (VAOCtx.isInVAOpt()) {
2513 if (Tok.is(tok::r_paren)) {
2514 if (VAOCtx.sawClosingParen()) {
2515 const unsigned NumTokens = MI->getNumTokens();
2516 assert(NumTokens >= 3 && "Must have seen at least __VA_OPT__( "
2517 "and a subsequent tok::r_paren");
2518 if (MI->getReplacementToken(NumTokens - 2).is(tok::hashhash)) {
2519 Diag(Tok, diag::err_vaopt_paste_at_end);
2520 return nullptr;
2521 }
2522 }
2523 } else if (Tok.is(tok::l_paren)) {
2524 VAOCtx.sawOpeningParen(Tok.getLocation());
2525 }
2526 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002527 // Get the next token of the macro.
2528 LexUnexpandedToken(Tok);
2529 continue;
2530 }
Mike Stump11289f42009-09-09 15:08:12 +00002531
Richard Smith701a3522013-07-09 01:00:29 +00002532 // If we're in -traditional mode, then we should ignore stringification
2533 // and token pasting. Mark the tokens as unknown so as not to confuse
2534 // things.
2535 if (getLangOpts().TraditionalCPP) {
2536 Tok.setKind(tok::unknown);
2537 MI->AddTokenToBody(Tok);
2538
2539 // Get the next token of the macro.
2540 LexUnexpandedToken(Tok);
2541 continue;
2542 }
2543
Eli Friedman14d3c792012-11-14 02:18:46 +00002544 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002545 // If we see token pasting, check if it looks like the gcc comma
2546 // pasting extension. We'll use this information to suppress
2547 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002548
Eli Friedman14d3c792012-11-14 02:18:46 +00002549 // Get the next token of the macro.
2550 LexUnexpandedToken(Tok);
2551
2552 if (Tok.is(tok::eod)) {
2553 MI->AddTokenToBody(LastTok);
2554 break;
2555 }
2556
2557 unsigned NumTokens = MI->getNumTokens();
2558 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2559 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2560 MI->setHasCommaPasting();
2561
David Majnemer76faf1f2013-11-05 09:30:17 +00002562 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002563 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002564 continue;
2565 }
2566
Faisal Vali18268422017-10-15 01:26:26 +00002567 // Our Token is a stringization operator.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002568 // Get the next token of the macro.
2569 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002570
Faisal Vali18268422017-10-15 01:26:26 +00002571 // Check for a valid macro arg identifier or __VA_OPT__.
2572 if (!VAOCtx.isVAOptToken(Tok) &&
2573 (Tok.getIdentifierInfo() == nullptr ||
2574 MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002575
2576 // If this is assembler-with-cpp mode, we accept random gibberish after
2577 // the '#' because '#' is often a comment character. However, change
2578 // the kind of the token to tok::unknown so that the preprocessor isn't
2579 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002580 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002581 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002582 MI->AddTokenToBody(LastTok);
2583 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002584 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002585 Diag(Tok, diag::err_pp_stringize_not_parameter)
2586 << LastTok.is(tok::hashat);
Faisal Valiac506d72017-07-17 17:18:43 +00002587 return nullptr;
Chris Lattner83bd8282009-05-25 17:16:10 +00002588 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002589 }
Mike Stump11289f42009-09-09 15:08:12 +00002590
Chris Lattner83bd8282009-05-25 17:16:10 +00002591 // Things look ok, add the '#' and param name tokens to the macro.
2592 MI->AddTokenToBody(LastTok);
Mike Stump11289f42009-09-09 15:08:12 +00002593
Faisal Vali18268422017-10-15 01:26:26 +00002594 // If the token following '#' is VAOPT, let the next iteration handle it
2595 // and check it for correctness, otherwise add the token and prime the
2596 // loop with the next one.
2597 if (!VAOCtx.isVAOptToken(Tok)) {
2598 MI->AddTokenToBody(Tok);
2599 LastTok = Tok;
2600
2601 // Get the next token of the macro.
2602 LexUnexpandedToken(Tok);
2603 }
2604 }
2605 if (VAOCtx.isInVAOpt()) {
2606 assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
2607 Diag(Tok, diag::err_pp_expected_after)
2608 << LastTok.getKind() << tok::r_paren;
2609 Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
2610 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002611 }
2612 }
Faisal Valiac506d72017-07-17 17:18:43 +00002613 MI->setDefinitionEndLoc(LastTok.getLocation());
Faisal Valiac506d72017-07-17 17:18:43 +00002614 return MI;
2615}
2616/// HandleDefineDirective - Implements \#define. This consumes the entire macro
2617/// line then lets the caller lex the next real token.
2618void Preprocessor::HandleDefineDirective(
2619 Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2620 ++NumDefined;
2621
2622 Token MacroNameTok;
2623 bool MacroShadowsKeyword;
2624 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2625
2626 // Error reading macro name? If so, diagnostic already issued.
2627 if (MacroNameTok.is(tok::eod))
2628 return;
2629
2630 // If we are supposed to keep comments in #defines, reenable comment saving
2631 // mode.
2632 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2633
2634 MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2635 MacroNameTok, ImmediatelyAfterHeaderGuard);
Fangrui Song6907ce22018-07-30 19:24:48 +00002636
Faisal Valiac506d72017-07-17 17:18:43 +00002637 if (!MI) return;
Mike Stump11289f42009-09-09 15:08:12 +00002638
Serge Pavlov07c0f042014-12-18 11:14:21 +00002639 if (MacroShadowsKeyword &&
2640 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2641 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
Fangrui Song6907ce22018-07-30 19:24:48 +00002642 }
Chris Lattner57540c52011-04-15 05:22:18 +00002643 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002644 // replacement list.
2645 unsigned NumTokens = MI->getNumTokens();
2646 if (NumTokens != 0) {
2647 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2648 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002649 return;
2650 }
2651 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2652 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002653 return;
2654 }
2655 }
Mike Stump11289f42009-09-09 15:08:12 +00002656
Erich Keane76675de2018-07-05 17:22:13 +00002657 // When skipping just warn about macros that do not match.
2658 if (SkippingUntilPCHThroughHeader) {
2659 const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
2660 if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
2661 /*Syntactic=*/LangOpts.MicrosoftExt))
2662 Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
2663 << MacroNameTok.getIdentifierInfo();
2664 return;
2665 }
Mike Stump11289f42009-09-09 15:08:12 +00002666
Chris Lattnerf64b3522008-03-09 01:54:53 +00002667 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002668 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002669 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002670 // In Objective-C, ignore attempts to directly redefine the builtin
2671 // definitions of the ownership qualifiers. It's still possible to
2672 // #undef them.
2673 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2674 return II->isStr("__strong") ||
2675 II->isStr("__weak") ||
2676 II->isStr("__unsafe_unretained") ||
2677 II->isStr("__autoreleasing");
2678 };
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002679 if (getLangOpts().ObjC &&
John McCall83760372015-12-10 23:31:01 +00002680 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2681 == getPredefinesFileID() &&
2682 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2683 // Warn if it changes the tokens.
2684 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2685 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2686 !MI->isIdenticalTo(*OtherMI, *this,
2687 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2688 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2689 }
2690 assert(!OtherMI->isWarnIfUnused());
2691 return;
2692 }
2693
Chris Lattner5244f342009-01-16 19:50:11 +00002694 // It is very common for system headers to have tons of macro redefinitions
2695 // and for warnings to be disabled in system headers. If this is the case,
2696 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002697 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002698 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002699 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002700 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002701
Taewook Oh755e4d22016-06-13 21:55:33 +00002702 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002703 // C++ [cpp.predefined]p4, but allow it as an extension.
2704 if (OtherMI->isBuiltinMacro())
2705 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002706 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002707 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002708 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002709 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002710 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2711 << MacroNameTok.getIdentifierInfo();
2712 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2713 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002714 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002715 if (OtherMI->isWarnIfUnused())
2716 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002717 }
Mike Stump11289f42009-09-09 15:08:12 +00002718
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002719 DefMacroDirective *MD =
2720 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002721
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002722 assert(!MI->isUsed());
2723 // If we need warning for not using the macro, add its location in the
2724 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002725 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002726 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002727 MI->setIsWarnIfUnused(true);
2728 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2729 }
2730
Chris Lattner928e9092009-04-12 01:39:54 +00002731 // If the callbacks want to know, tell them about the macro definition.
2732 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002733 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002734}
2735
James Dennettf6333ac2012-06-22 05:46:07 +00002736/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002737///
Erik Verbruggen4bddef92016-10-26 08:52:41 +00002738void Preprocessor::HandleUndefDirective() {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002739 ++NumUndefined;
2740
2741 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002742 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002743
Chris Lattnerf64b3522008-03-09 01:54:53 +00002744 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002745 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002746 return;
Mike Stump11289f42009-09-09 15:08:12 +00002747
Chris Lattnerf64b3522008-03-09 01:54:53 +00002748 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002749 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002750
Richard Smith20e883e2015-04-29 23:20:19 +00002751 // Okay, we have a valid identifier to undef.
2752 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002753 auto MD = getMacroDefinition(II);
Vedant Kumar349a6242017-04-26 21:05:44 +00002754 UndefMacroDirective *Undef = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00002755
Vedant Kumar349a6242017-04-26 21:05:44 +00002756 // If the macro is not defined, this is a noop undef.
2757 if (const MacroInfo *MI = MD.getMacroInfo()) {
2758 if (!MI->isUsed() && MI->isWarnIfUnused())
2759 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2760
2761 if (MI->isWarnIfUnused())
2762 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2763
2764 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
2765 }
Mike Stump11289f42009-09-09 15:08:12 +00002766
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002767 // If the callbacks want to know, tell them about the macro #undef.
2768 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002769 if (Callbacks)
Vedant Kumar349a6242017-04-26 21:05:44 +00002770 Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002771
Vedant Kumar349a6242017-04-26 21:05:44 +00002772 if (Undef)
2773 appendMacroDirective(II, Undef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002774}
2775
Chris Lattnerf64b3522008-03-09 01:54:53 +00002776//===----------------------------------------------------------------------===//
2777// Preprocessor Conditional Directive Handling.
2778//===----------------------------------------------------------------------===//
2779
James Dennettf6333ac2012-06-22 05:46:07 +00002780/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2781/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2782/// true if any tokens have been returned or pp-directives activated before this
2783/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002784///
Vedant Kumar3919a502017-09-11 20:47:42 +00002785void Preprocessor::HandleIfdefDirective(Token &Result,
2786 const Token &HashToken,
2787 bool isIfndef,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002788 bool ReadAnyTokensBeforeDirective) {
2789 ++NumIf;
2790 Token DirectiveTok = Result;
2791
2792 Token MacroNameTok;
2793 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002794
Chris Lattnerf64b3522008-03-09 01:54:53 +00002795 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002796 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002797 // Skip code until we get to #endif. This helps with recovery by not
2798 // emitting an error when the #endif is reached.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002799 SkipExcludedConditionalBlock(HashToken.getLocation(),
2800 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002801 /*Foundnonskip*/ false, /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002802 return;
2803 }
Mike Stump11289f42009-09-09 15:08:12 +00002804
Chris Lattnerf64b3522008-03-09 01:54:53 +00002805 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002806 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002807
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002808 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002809 auto MD = getMacroDefinition(MII);
2810 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002811
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002812 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002813 // If the start of a top-level #ifdef and if the macro is not defined,
2814 // inform MIOpt that this might be the start of a proper include guard.
2815 // Otherwise it is some other form of unknown conditional which we can't
2816 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002817 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002818 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002819 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002820 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002821 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002822 }
2823
Chris Lattnerf64b3522008-03-09 01:54:53 +00002824 // If there is a macro, process it.
2825 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002826 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002827
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002828 if (Callbacks) {
2829 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002830 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002831 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002832 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002833 }
2834
Chris Lattnerf64b3522008-03-09 01:54:53 +00002835 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002836 if (PPOpts->SingleFileParseMode && !MI) {
2837 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2838 // the directive blocks.
2839 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002840 /*wasskip*/false, /*foundnonskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002841 /*foundelse*/false);
2842 } else if (!MI == isIfndef) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002843 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002844 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2845 /*wasskip*/false, /*foundnonskip*/true,
2846 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002847 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002848 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002849 SkipExcludedConditionalBlock(HashToken.getLocation(),
2850 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002851 /*Foundnonskip*/ false,
2852 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002853 }
2854}
2855
James Dennettf6333ac2012-06-22 05:46:07 +00002856/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002857///
2858void Preprocessor::HandleIfDirective(Token &IfToken,
Vedant Kumar3919a502017-09-11 20:47:42 +00002859 const Token &HashToken,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002860 bool ReadAnyTokensBeforeDirective) {
2861 ++NumIf;
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002862
2863 // Parse and evaluate the conditional expression.
2864 IdentifierInfo *IfNDefMacro = nullptr;
2865 const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
2866 const bool ConditionalTrue = DER.Conditional;
2867
2868 // If this condition is equivalent to #ifndef X, and if this is the first
2869 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002870 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002871 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002872 // FIXME: Pass in the location of the macro name, not the 'if' token.
2873 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002874 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002875 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002876 }
2877
2878 if (Callbacks)
2879 Callbacks->If(
2880 IfToken.getLocation(), DER.ExprRange,
2881 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
2882
2883 // Should we include the stuff contained by this directive?
2884 if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002885 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2886 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002887 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002888 /*foundnonskip*/false, /*foundelse*/false);
2889 } else if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002890 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002891 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002892 /*foundnonskip*/true, /*foundelse*/false);
2893 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002894 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002895 SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002896 /*Foundnonskip*/ false,
2897 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002898 }
2899}
2900
James Dennettf6333ac2012-06-22 05:46:07 +00002901/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002902///
2903void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2904 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002905
Chris Lattnerf64b3522008-03-09 01:54:53 +00002906 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002907 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002908
Chris Lattnerf64b3522008-03-09 01:54:53 +00002909 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002910 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002911 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002912 Diag(EndifToken, diag::err_pp_endif_without_if);
2913 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002914 }
Mike Stump11289f42009-09-09 15:08:12 +00002915
Chris Lattnerf64b3522008-03-09 01:54:53 +00002916 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002917 if (CurPPLexer->getConditionalStackDepth() == 0)
2918 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002919
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002920 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002921 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002922
2923 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002924 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002925}
2926
James Dennettf6333ac2012-06-22 05:46:07 +00002927/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002928///
Vedant Kumar3919a502017-09-11 20:47:42 +00002929void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002930 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002931
Chris Lattnerf64b3522008-03-09 01:54:53 +00002932 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002933 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002934
Chris Lattnerf64b3522008-03-09 01:54:53 +00002935 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002936 if (CurPPLexer->popConditionalLevel(CI)) {
2937 Diag(Result, diag::pp_err_else_without_if);
2938 return;
2939 }
Mike Stump11289f42009-09-09 15:08:12 +00002940
Chris Lattnerf64b3522008-03-09 01:54:53 +00002941 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002942 if (CurPPLexer->getConditionalStackDepth() == 0)
2943 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002944
2945 // If this is a #else with a #else before it, report the error.
2946 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002947
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002948 if (Callbacks)
2949 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2950
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002951 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002952 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2953 // the directive blocks.
2954 CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002955 /*foundnonskip*/false, /*foundelse*/true);
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002956 return;
2957 }
2958
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002959 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002960 SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
2961 /*Foundnonskip*/ true,
Vedant Kumar3919a502017-09-11 20:47:42 +00002962 /*FoundElse*/ true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002963}
2964
James Dennettf6333ac2012-06-22 05:46:07 +00002965/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002966///
Vedant Kumar3919a502017-09-11 20:47:42 +00002967void Preprocessor::HandleElifDirective(Token &ElifToken,
2968 const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002969 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002970
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002971 // #elif directive in a non-skipping conditional... start skipping.
2972 // We don't care what the condition is, because we will always skip it (since
2973 // the block immediately before it was included).
2974 SourceRange ConditionRange = DiscardUntilEndOfDirective();
2975
2976 PPConditionalInfo CI;
2977 if (CurPPLexer->popConditionalLevel(CI)) {
Chris Lattner907dfe92008-11-18 07:59:24 +00002978 Diag(ElifToken, diag::pp_err_elif_without_if);
2979 return;
2980 }
Mike Stump11289f42009-09-09 15:08:12 +00002981
Chris Lattnerf64b3522008-03-09 01:54:53 +00002982 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002983 if (CurPPLexer->getConditionalStackDepth() == 0)
2984 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002985
Chris Lattnerf64b3522008-03-09 01:54:53 +00002986 // If this is a #elif with a #else before it, report the error.
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002987 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2988
2989 if (Callbacks)
2990 Callbacks->Elif(ElifToken.getLocation(), ConditionRange,
2991 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
2992
2993 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002994 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2995 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002996 CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002997 /*foundnonskip*/false, /*foundelse*/false);
2998 return;
2999 }
3000
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00003001 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003002 SkipExcludedConditionalBlock(
3003 HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
3004 /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00003005}