blob: 62796293b4dc50fc9e09846364536b1f7772730e [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.
339void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000340 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000341 // Lex unexpanded tokens for most directives: macros might expand to zero
342 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
343 // #line) allow empty macros.
344 if (EnableMacros)
345 Lex(Tmp);
346 else
347 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000348
Chris Lattnerf64b3522008-03-09 01:54:53 +0000349 // There should be no tokens after the directive, but we allow them as an
350 // extension.
351 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
352 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000353
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000354 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000355 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000356 // or if this is a macro-style preprocessing directive, because it is more
357 // trouble than it is worth to insert /**/ and check that there is no /**/
358 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000359 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000360 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000361 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000362 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
363 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000364 DiscardUntilEndOfDirective();
365 }
366}
367
James Dennettf6333ac2012-06-22 05:46:07 +0000368/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
369/// decided that the subsequent tokens are in the \#if'd out portion of the
370/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000371/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000372/// this \#if directive, so \#else/\#elif blocks should never be entered.
373/// If ElseOk is true, then \#else directives are ok, if not, then we have
374/// already seen one so a \#else directive is a duplicate. When this returns,
375/// the caller can lex the first valid token.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000376void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
Vedant Kumar3919a502017-09-11 20:47:42 +0000377 SourceLocation IfTokenLoc,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000378 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000379 bool FoundElse,
380 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000381 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000382 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000383
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000384 if (PreambleConditionalStack.reachedEOFWhileSkipping())
385 PreambleConditionalStack.clearSkipInfo();
386 else
387 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
388 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000389
Chris Lattnerf64b3522008-03-09 01:54:53 +0000390 // Enter raw mode to disable identifier lookup (and thus macro expansion),
391 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000392 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000393 Token Tok;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000394 while (true) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000395 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000396
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000397 if (Tok.is(tok::code_completion)) {
398 if (CodeComplete)
399 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000400 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000401 continue;
402 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000403
Chris Lattnerf64b3522008-03-09 01:54:53 +0000404 // If this is the end of the buffer, we have an error.
405 if (Tok.is(tok::eof)) {
Ilya Biryukov8f738ac2017-09-12 08:35:57 +0000406 // We don't emit errors for unterminated conditionals here,
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000407 // Lexer::LexEndOfFile can do that properly.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000408 // Just return and let the caller lex after this #include.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000409 if (PreambleConditionalStack.isRecording())
410 PreambleConditionalStack.SkipInfo.emplace(
411 HashTokenLoc, IfTokenLoc, FoundNonSkipPortion, FoundElse, ElseLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000412 break;
413 }
Mike Stump11289f42009-09-09 15:08:12 +0000414
Chris Lattnerf64b3522008-03-09 01:54:53 +0000415 // If this token is not a preprocessor directive, just skip it.
416 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
417 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000418
Chris Lattnerf64b3522008-03-09 01:54:53 +0000419 // We just parsed a # character at the start of a line, so we're in
420 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000421 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000422 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000423 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000424
Mike Stump11289f42009-09-09 15:08:12 +0000425
Chris Lattnerf64b3522008-03-09 01:54:53 +0000426 // Read the next token, the directive flavor.
427 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattnerf64b3522008-03-09 01:54:53 +0000429 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
430 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000431 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000432 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000433 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000434 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000435 continue;
436 }
437
438 // If the first letter isn't i or e, it isn't intesting to us. We know that
439 // this is safe in the face of spelling differences, because there is no way
440 // to spell an i/e in a strange way that is another letter. Skipping this
441 // allows us to avoid looking up the identifier info for #define/#undef and
442 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000443 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000444
Alp Toker2d57cea2014-05-17 04:53:25 +0000445 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000446 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000447 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000448 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000449 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000450 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000451 continue;
452 }
Mike Stump11289f42009-09-09 15:08:12 +0000453
Chris Lattnerf64b3522008-03-09 01:54:53 +0000454 // Get the identifier name without trigraphs or embedded newlines. Note
455 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
456 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000457 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000458 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000459 if (!Tok.needsCleaning() && RI.size() < 20) {
460 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000461 } else {
462 std::string DirectiveStr = getSpelling(Tok);
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000463 size_t IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000464 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000465 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000466 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000467 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000468 continue;
469 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000470 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000471 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000472 }
Mike Stump11289f42009-09-09 15:08:12 +0000473
Benjamin Kramer144884642009-12-31 13:32:38 +0000474 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000475 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000476 if (Sub.empty() || // "if"
477 Sub == "def" || // "ifdef"
478 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000479 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
480 // bother parsing the condition.
481 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000482 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000483 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000484 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000485 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000486 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000487 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000488 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000489 PPConditionalInfo CondInfo;
490 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000491 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000492 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000493 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000494
Chris Lattnerf64b3522008-03-09 01:54:53 +0000495 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000496 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000497 // Restore the value of LexingRawMode so that trailing comments
498 // are handled correctly, if we've reached the outermost block.
499 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000500 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000501 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000502 if (Callbacks)
503 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000504 break;
Richard Smithd0124572012-06-21 00:35:03 +0000505 } else {
506 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000507 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000508 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000509 // #else directive in a skipping conditional. If not in some other
510 // skipping conditional, and if #else hasn't already been seen, enter it
511 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000512 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000513
Chris Lattnerf64b3522008-03-09 01:54:53 +0000514 // If this is a #else with a #else before it, report the error.
515 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chris Lattnerf64b3522008-03-09 01:54:53 +0000517 // Note that we've seen a #else in this conditional.
518 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000519
Chris Lattnerf64b3522008-03-09 01:54:53 +0000520 // If the conditional is at the top level, and the #if block wasn't
521 // entered, enter the #else block now.
522 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
523 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000524 // Restore the value of LexingRawMode so that trailing comments
525 // are handled correctly.
526 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000527 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000528 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000529 if (Callbacks)
530 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000531 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000532 } else {
533 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000534 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000535 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000536 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000537
John Thompson17c35732013-12-04 20:19:30 +0000538 // If this is a #elif with a #else before it, report the error.
539 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
540
Chris Lattnerf64b3522008-03-09 01:54:53 +0000541 // If this is in a skipping block or if we're already handled this #if
542 // block, don't bother parsing the condition.
Chandler Carruthd92d70b2019-01-19 06:36:00 +0000543 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
544 DiscardUntilEndOfDirective();
545 } else {
546 // Restore the value of LexingRawMode so that identifiers are
547 // looked up, etc, inside the #elif expression.
548 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
549 CurPPLexer->LexingRawMode = false;
550 IdentifierInfo *IfNDefMacro = nullptr;
551 DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
552 const bool CondValue = DER.Conditional;
553 CurPPLexer->LexingRawMode = true;
554 if (Callbacks) {
555 Callbacks->Elif(
556 Tok.getLocation(), DER.ExprRange,
557 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
558 CondInfo.IfLoc);
559 }
560 // If this condition is true, enter it!
561 if (CondValue) {
John Thompson17c35732013-12-04 20:19:30 +0000562 CondInfo.FoundNonSkip = true;
563 break;
564 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000565 }
566 }
567 }
Mike Stump11289f42009-09-09 15:08:12 +0000568
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000569 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000570 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000571 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000572 }
573
574 // Finally, if we are out of the conditional (saw an #endif or ran off the end
575 // of the file, just stop skipping and return to lexing whatever came after
576 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000577 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000578
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000579 // The last skipped range isn't actually skipped yet if it's truncated
580 // by the end of the preamble; we'll resume parsing after the preamble.
581 if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
Vedant Kumar3919a502017-09-11 20:47:42 +0000582 Callbacks->SourceRangeSkipped(
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000583 SourceRange(HashTokenLoc, CurPPLexer->getSourceLocation()),
Vedant Kumar3919a502017-09-11 20:47:42 +0000584 Tok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000585}
586
Richard Smith2a553082015-04-23 22:58:06 +0000587Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000588 if (!SourceMgr.isInMainFile(Loc)) {
589 // Try to determine the module of the include directive.
590 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
591 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
592 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
593 // The include comes from an included file.
594 return HeaderInfo.getModuleMap()
595 .findModuleForHeader(EntryOfIncl)
596 .getModule();
597 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000598 }
Richard Smith7e82e012016-02-19 22:25:36 +0000599
600 // This is either in the main file or not in a file at all. It belongs
601 // to the current module, if there is one.
602 return getLangOpts().CurrentModule.empty()
603 ? nullptr
604 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000605}
606
Richard Smith4eb83932016-04-27 21:57:05 +0000607const FileEntry *
608Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000609 Module *M,
Richard Smith4eb83932016-04-27 21:57:05 +0000610 SourceLocation Loc) {
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000611 assert(M && "no module to include");
612
Richard Smith4eb83932016-04-27 21:57:05 +0000613 // If we have a module import syntax, we shouldn't include a header to
614 // make a particular module visible.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000615 if (getLangOpts().ObjC)
Richard Smith4eb83932016-04-27 21:57:05 +0000616 return nullptr;
617
Richard Smith4eb83932016-04-27 21:57:05 +0000618 Module *TopM = M->getTopLevelModule();
619 Module *IncM = getModuleForLocation(IncLoc);
620
621 // Walk up through the include stack, looking through textual headers of M
622 // until we hit a non-textual header that we can #include. (We assume textual
623 // headers of a module with non-textual headers aren't meant to be used to
624 // import entities from the module.)
625 auto &SM = getSourceManager();
626 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
627 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
628 auto *FE = SM.getFileEntryForID(ID);
Richard Smith040e1262017-06-02 01:55:39 +0000629 if (!FE)
630 break;
Richard Smith4eb83932016-04-27 21:57:05 +0000631
632 bool InTextualHeader = false;
633 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
634 if (!Header.getModule()->isSubModuleOf(TopM))
635 continue;
636
637 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
638 // If this is an accessible, non-textual header of M's top-level module
639 // that transitively includes the given location and makes the
640 // corresponding module visible, this is the thing to #include.
641 if (Header.isAccessibleFrom(IncM))
642 return FE;
643
644 // It's in a private header; we can't #include it.
645 // FIXME: If there's a public header in some module that re-exports it,
646 // then we could suggest including that, but it's not clear that's the
647 // expected way to make this entity visible.
648 continue;
649 }
650
651 InTextualHeader = true;
652 }
653
654 if (!InTextualHeader)
655 break;
656
657 Loc = SM.getIncludeLoc(ID);
658 }
659
660 return nullptr;
661}
662
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000663const FileEntry *Preprocessor::LookupFile(
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000664 SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
665 const DirectoryLookup *FromDir, const FileEntry *FromFile,
666 const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000667 SmallVectorImpl<char> *RelativePath,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000668 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
669 bool *IsFrameworkFound, bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000670 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000671 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000672
Will Wilson0fafd342013-12-27 19:46:16 +0000673 // If the header lookup mechanism may be relative to the current inclusion
674 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000675 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
676 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000677 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000678 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000679 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000680 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000681
Chris Lattner022923a2009-02-04 19:45:07 +0000682 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000683 // predefines buffer or the module includes buffer. Any other file is not
684 // lexed with a normal lexer, so it won't be scanned for preprocessor
685 // directives.
686 //
687 // If we have the predefines buffer, resolve #include references (which come
688 // from the -include command line argument) from the current working
689 // directory instead of relative to the main file.
690 //
691 // If we have the module includes buffer, resolve #include references (which
692 // come from header declarations in the module map) relative to the module
693 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000694 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000695 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000696 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000697 BuildSystemModule = getCurrentModule()->IsSystem;
698 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000699 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000700 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
701 } else {
702 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
703 }
Will Wilson0fafd342013-12-27 19:46:16 +0000704
705 // MSVC searches the current include stack from top to bottom for
706 // headers included by quoted include directives.
707 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000708 if (LangOpts.MSVCCompat && !isAngled) {
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000709 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000710 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000711 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000712 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000713 }
Chris Lattner022923a2009-02-04 19:45:07 +0000714 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000715 }
Mike Stump11289f42009-09-09 15:08:12 +0000716
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000717 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000718
719 if (FromFile) {
720 // We're supposed to start looking from after a particular file. Search
721 // the include path until we find that file or run out of files.
722 const DirectoryLookup *TmpCurDir = CurDir;
723 const DirectoryLookup *TmpFromDir = nullptr;
724 while (const FileEntry *FE = HeaderInfo.LookupFile(
725 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000726 Includers, SearchPath, RelativePath, RequestingModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000727 SuggestedModule, /*IsMapped=*/nullptr,
728 /*IsFrameworkFound=*/nullptr, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000729 // Keep looking as if this file did a #include_next.
730 TmpFromDir = TmpCurDir;
731 ++TmpFromDir;
732 if (FE == FromFile) {
733 // Found it.
734 FromDir = TmpFromDir;
735 CurDir = TmpCurDir;
736 break;
737 }
738 }
739 }
740
741 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000742 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000743 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000744 RelativePath, RequestingModule, SuggestedModule, IsMapped,
745 IsFrameworkFound, SkipCache, BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000746 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000747 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000748 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000749 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
750 Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000751 return FE;
752 }
Mike Stump11289f42009-09-09 15:08:12 +0000753
Will Wilson0fafd342013-12-27 19:46:16 +0000754 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000755 // Otherwise, see if this is a subframework header. If so, this is relative
756 // to one of the headers on the #include stack. Walk the list of the current
757 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000758 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000759 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000760 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000761 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000762 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000763 SuggestedModule))) {
764 if (SuggestedModule && !LangOpts.AsmPreprocessor)
765 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000766 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
767 Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000768 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000769 }
770 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000771 }
Mike Stump11289f42009-09-09 15:08:12 +0000772
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000773 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000774 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000775 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000776 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000777 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000778 RequestingModule, SuggestedModule))) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000779 if (SuggestedModule && !LangOpts.AsmPreprocessor)
780 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000781 RequestingModule, RequestingModuleIsModuleInterface,
782 FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000783 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000784 }
785 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000786 }
787 }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000789 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000790 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000791}
792
Chris Lattnerf64b3522008-03-09 01:54:53 +0000793//===----------------------------------------------------------------------===//
794// Preprocessor Directive Handling.
795//===----------------------------------------------------------------------===//
796
David Blaikied5321242012-06-06 18:52:13 +0000797class Preprocessor::ResetMacroExpansionHelper {
798public:
799 ResetMacroExpansionHelper(Preprocessor *pp)
800 : PP(pp), save(pp->DisableMacroExpansion) {
801 if (pp->MacroExpansionInDirectivesOverride)
802 pp->DisableMacroExpansion = false;
803 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000804
David Blaikied5321242012-06-06 18:52:13 +0000805 ~ResetMacroExpansionHelper() {
806 PP->DisableMacroExpansion = save;
807 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000808
David Blaikied5321242012-06-06 18:52:13 +0000809private:
810 Preprocessor *PP;
811 bool save;
812};
813
Mike Rice58df1af2018-09-11 17:10:44 +0000814/// Process a directive while looking for the through header or a #pragma
815/// hdrstop. The following directives are handled:
816/// #include (to check if it is the through header)
817/// #define (to warn about macros that don't match the PCH)
818/// #pragma (to check for pragma hdrstop).
819/// All other directives are completely discarded.
820void Preprocessor::HandleSkippedDirectiveWhileUsingPCH(Token &Result,
Erich Keane76675de2018-07-05 17:22:13 +0000821 SourceLocation HashLoc) {
822 if (const IdentifierInfo *II = Result.getIdentifierInfo()) {
Mike Rice58df1af2018-09-11 17:10:44 +0000823 if (II->getPPKeywordID() == tok::pp_define) {
Erich Keane76675de2018-07-05 17:22:13 +0000824 return HandleDefineDirective(Result,
825 /*ImmediatelyAfterHeaderGuard=*/false);
Mike Rice58df1af2018-09-11 17:10:44 +0000826 }
827 if (SkippingUntilPCHThroughHeader &&
828 II->getPPKeywordID() == tok::pp_include) {
829 return HandleIncludeDirective(HashLoc, Result);
830 }
831 if (SkippingUntilPragmaHdrStop && II->getPPKeywordID() == tok::pp_pragma) {
832 Token P = LookAhead(0);
833 auto *II = P.getIdentifierInfo();
834 if (II && II->getName() == "hdrstop")
835 return HandlePragmaDirective(HashLoc, PIK_HashPragma);
836 }
Erich Keane76675de2018-07-05 17:22:13 +0000837 }
838 DiscardUntilEndOfDirective();
839}
840
Chris Lattnerf64b3522008-03-09 01:54:53 +0000841/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000842/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000843/// lexer/preprocessor state, and advances the lexer(s) so that the next token
844/// read is the correct one.
845void Preprocessor::HandleDirective(Token &Result) {
846 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chris Lattnerf64b3522008-03-09 01:54:53 +0000848 // We just parsed a # character at the start of a line, so we're in directive
849 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000850 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000851 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000852 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000853
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000854 bool ImmediatelyAfterTopLevelIfndef =
855 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
856 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
857
Chris Lattnerf64b3522008-03-09 01:54:53 +0000858 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000859
Chris Lattnerf64b3522008-03-09 01:54:53 +0000860 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000861 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000862 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000863 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000864
Chris Lattner2d17ab72009-03-18 21:00:25 +0000865 // Save the '#' token in case we need to return it later.
866 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000867
Chris Lattnerf64b3522008-03-09 01:54:53 +0000868 // Read the next token, the directive flavor. This isn't expanded due to
869 // C99 6.10.3p8.
870 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000871
Chris Lattnerf64b3522008-03-09 01:54:53 +0000872 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
873 // #define A(x) #x
874 // A(abc
875 // #warning blah
876 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000877 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
878 // not support this for #include-like directives, since that can result in
879 // terrible diagnostics, and does not work in GCC.
880 if (InMacroArgs) {
881 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
882 switch (II->getPPKeywordID()) {
883 case tok::pp_include:
884 case tok::pp_import:
885 case tok::pp_include_next:
886 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000887 case tok::pp_pragma:
888 Diag(Result, diag::err_embedded_directive) << II->getName();
Nico Weber023dd1e2019-02-14 04:13:17 +0000889 Diag(*ArgMacro, diag::note_macro_expansion_here)
890 << ArgMacro->getIdentifierInfo();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000891 DiscardUntilEndOfDirective();
892 return;
893 default:
894 break;
895 }
896 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000897 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000898 }
Mike Stump11289f42009-09-09 15:08:12 +0000899
David Blaikied5321242012-06-06 18:52:13 +0000900 // Temporarily enable macro expansion if set so
901 // and reset to previous state when returning from this function.
902 ResetMacroExpansionHelper helper(this);
903
Mike Rice58df1af2018-09-11 17:10:44 +0000904 if (SkippingUntilPCHThroughHeader || SkippingUntilPragmaHdrStop)
905 return HandleSkippedDirectiveWhileUsingPCH(Result, SavedHash.getLocation());
Erich Keane76675de2018-07-05 17:22:13 +0000906
Chris Lattnerf64b3522008-03-09 01:54:53 +0000907 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000908 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000909 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000910 case tok::code_completion:
911 if (CodeComplete)
912 CodeComplete->CodeCompleteDirective(
913 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000914 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000915 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000916 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000917 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000918 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000919 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000920 default:
921 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000922 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000923
Chris Lattnerf64b3522008-03-09 01:54:53 +0000924 // Ask what the preprocessor keyword ID is.
925 switch (II->getPPKeywordID()) {
926 default: break;
927 // C99 6.10.1 - Conditional Inclusion.
928 case tok::pp_if:
Vedant Kumar3919a502017-09-11 20:47:42 +0000929 return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000930 case tok::pp_ifdef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000931 return HandleIfdefDirective(Result, SavedHash, false,
932 true /*not valid for miopt*/);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000933 case tok::pp_ifndef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000934 return HandleIfdefDirective(Result, SavedHash, true,
935 ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000936 case tok::pp_elif:
Vedant Kumar3919a502017-09-11 20:47:42 +0000937 return HandleElifDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000938 case tok::pp_else:
Vedant Kumar3919a502017-09-11 20:47:42 +0000939 return HandleElseDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000940 case tok::pp_endif:
941 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattnerf64b3522008-03-09 01:54:53 +0000943 // C99 6.10.2 - Source File Inclusion.
944 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000945 // Handle #include.
946 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000947 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000948 // Handle -imacros.
Taewook Oh755e4d22016-06-13 21:55:33 +0000949 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000950
Chris Lattnerf64b3522008-03-09 01:54:53 +0000951 // C99 6.10.3 - Macro Replacement.
952 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000953 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000954 case tok::pp_undef:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000955 return HandleUndefDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000956
957 // C99 6.10.4 - Line Control.
958 case tok::pp_line:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000959 return HandleLineDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chris Lattnerf64b3522008-03-09 01:54:53 +0000961 // C99 6.10.5 - Error Directive.
962 case tok::pp_error:
963 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000964
Chris Lattnerf64b3522008-03-09 01:54:53 +0000965 // C99 6.10.6 - Pragma Directive.
966 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000967 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattnerf64b3522008-03-09 01:54:53 +0000969 // GNU Extensions.
970 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000971 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000972 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000973 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattnerf64b3522008-03-09 01:54:53 +0000975 case tok::pp_warning:
976 Diag(Result, diag::ext_pp_warning_directive);
977 return HandleUserDiagnosticDirective(Result, true);
978 case tok::pp_ident:
979 return HandleIdentSCCSDirective(Result);
980 case tok::pp_sccs:
981 return HandleIdentSCCSDirective(Result);
982 case tok::pp_assert:
983 //isExtension = true; // FIXME: implement #assert
984 break;
985 case tok::pp_unassert:
986 //isExtension = true; // FIXME: implement #unassert
987 break;
Taewook Oh755e4d22016-06-13 21:55:33 +0000988
Douglas Gregor663b48f2012-01-03 19:48:16 +0000989 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000990 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000991 return HandleMacroPublicDirective(Result);
992 break;
Taewook Oh755e4d22016-06-13 21:55:33 +0000993
Douglas Gregor663b48f2012-01-03 19:48:16 +0000994 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000995 if (getLangOpts().Modules)
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000996 return HandleMacroPrivateDirective();
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000997 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000998 }
999 break;
1000 }
Mike Stump11289f42009-09-09 15:08:12 +00001001
Chris Lattner2d17ab72009-03-18 21:00:25 +00001002 // If this is a .S file, treat unknown # directives as non-preprocessor
1003 // directives. This is important because # may be a comment or introduce
1004 // various pseudo-ops. Just return the # token and push back the following
1005 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001006 if (getLangOpts().AsmPreprocessor) {
David Blaikie2eabcc92016-02-09 18:52:09 +00001007 auto Toks = llvm::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001008 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001009 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001010 Toks[1] = Result;
Taewook Oh755e4d22016-06-13 21:55:33 +00001011
Chris Lattner56f64c12011-01-06 05:01:51 +00001012 // If the second token is a hashhash token, then we need to translate it to
1013 // unknown so the token lexer doesn't try to perform token pasting.
1014 if (Result.is(tok::hashhash))
1015 Toks[1].setKind(tok::unknown);
Taewook Oh755e4d22016-06-13 21:55:33 +00001016
Chris Lattner2d17ab72009-03-18 21:00:25 +00001017 // Enter this token stream so that we re-lex the tokens. Make sure to
1018 // enable macro expansion, in case the token after the # is an identifier
1019 // that is expanded.
David Blaikie2eabcc92016-02-09 18:52:09 +00001020 EnterTokenStream(std::move(Toks), 2, false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001021 return;
1022 }
Mike Stump11289f42009-09-09 15:08:12 +00001023
Chris Lattnerf64b3522008-03-09 01:54:53 +00001024 // If we reached here, the preprocessing token is not valid!
1025 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001026
Chris Lattnerf64b3522008-03-09 01:54:53 +00001027 // Read the rest of the PP line.
1028 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001029
Chris Lattnerf64b3522008-03-09 01:54:53 +00001030 // Okay, we're done parsing the directive.
1031}
1032
Chris Lattner76e68962009-01-26 06:19:46 +00001033/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1034/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1035static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001036 unsigned DiagID, Preprocessor &PP,
1037 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001038 if (DigitTok.isNot(tok::numeric_constant)) {
1039 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001040
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001041 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001042 PP.DiscardUntilEndOfDirective();
1043 return true;
1044 }
Mike Stump11289f42009-09-09 15:08:12 +00001045
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001046 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001047 IntegerBuffer.resize(DigitTok.getLength());
1048 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001049 bool Invalid = false;
1050 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1051 if (Invalid)
1052 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001053
Chris Lattnerd66f1722009-04-18 18:35:15 +00001054 // Verify that we have a simple digit-sequence, and compute the value. This
1055 // is always a simple digit string computed in decimal, so we do this manually
1056 // here.
1057 Val = 0;
1058 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001059 // C++1y [lex.fcon]p1:
1060 // Optional separating single quotes in a digit-sequence are ignored
1061 if (DigitTokBegin[i] == '\'')
1062 continue;
1063
Jordan Rosea7d03842013-02-08 22:30:41 +00001064 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001065 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001066 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001067 PP.DiscardUntilEndOfDirective();
1068 return true;
1069 }
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chris Lattnerd66f1722009-04-18 18:35:15 +00001071 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1072 if (NextVal < Val) { // overflow.
1073 PP.Diag(DigitTok, DiagID);
1074 PP.DiscardUntilEndOfDirective();
1075 return true;
1076 }
1077 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001078 }
Mike Stump11289f42009-09-09 15:08:12 +00001079
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001080 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001081 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1082 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001083
Chris Lattner76e68962009-01-26 06:19:46 +00001084 return false;
1085}
1086
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001087/// Handle a \#line directive: C99 6.10.4.
James Dennettf6333ac2012-06-22 05:46:07 +00001088///
1089/// The two acceptable forms are:
1090/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001091/// # line digit-sequence
1092/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001093/// \endverbatim
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001094void Preprocessor::HandleLineDirective() {
Chris Lattner100c65e2009-01-26 05:29:08 +00001095 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1096 // expanded.
1097 Token DigitTok;
1098 Lex(DigitTok);
1099
Chris Lattner100c65e2009-01-26 05:29:08 +00001100 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001101 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001102 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001103 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001104
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001105 if (LineNo == 0)
1106 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001107
Chris Lattner76e68962009-01-26 06:19:46 +00001108 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1109 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001110 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001111 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001112 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001113 if (LineNo >= LineLimit)
1114 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001115 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001116 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001117
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001118 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001119 Token StrTok;
1120 Lex(StrTok);
1121
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001122 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1123 // string followed by eod.
1124 if (StrTok.is(tok::eod))
Chandler Carruthd92d70b2019-01-19 06:36:00 +00001125 ; // ok
1126 else if (StrTok.isNot(tok::string_literal)) {
1127 Diag(StrTok, diag::err_pp_line_invalid_filename);
1128 DiscardUntilEndOfDirective();
1129 return;
1130 } else if (StrTok.hasUDSuffix()) {
1131 Diag(StrTok, diag::err_invalid_string_udl);
1132 DiscardUntilEndOfDirective();
1133 return;
1134 } else {
1135 // Parse and validate the string, converting it into a unique ID.
1136 StringLiteralParser Literal(StrTok, *this);
1137 assert(Literal.isAscii() && "Didn't allow wide strings in");
1138 if (Literal.hadError) {
1139 DiscardUntilEndOfDirective();
1140 return;
1141 }
1142 if (Literal.Pascal) {
1143 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1144 DiscardUntilEndOfDirective();
1145 return;
1146 }
1147 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1148
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001149 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001150 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1151 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001152 }
Mike Stump11289f42009-09-09 15:08:12 +00001153
Reid Klecknereb00ee02017-05-22 21:42:58 +00001154 // Take the file kind of the file containing the #line directive. #line
1155 // directives are often used for generated sources from the same codebase, so
1156 // the new file should generally be classified the same way as the current
1157 // file. This is visible in GCC's pre-processed output, which rewrites #line
1158 // to GNU line markers.
1159 SrcMgr::CharacteristicKind FileKind =
1160 SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1161
1162 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1163 false, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001164
Chris Lattner839150e2009-03-27 17:13:49 +00001165 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001166 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Reid Klecknereb00ee02017-05-22 21:42:58 +00001167 PPCallbacks::RenameFile, FileKind);
Chris Lattner100c65e2009-01-26 05:29:08 +00001168}
1169
Chris Lattner76e68962009-01-26 06:19:46 +00001170/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1171/// marker directive.
1172static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
Reid Klecknereb00ee02017-05-22 21:42:58 +00001173 SrcMgr::CharacteristicKind &FileKind,
Chris Lattner76e68962009-01-26 06:19:46 +00001174 Preprocessor &PP) {
1175 unsigned FlagVal;
1176 Token FlagTok;
1177 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001178 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001179 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1180 return true;
1181
1182 if (FlagVal == 1) {
1183 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001184
Chris Lattner76e68962009-01-26 06:19:46 +00001185 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001186 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001187 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1188 return true;
1189 } else if (FlagVal == 2) {
1190 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001191
Chris Lattner1c967782009-02-04 06:25:26 +00001192 SourceManager &SM = PP.getSourceManager();
1193 // If we are leaving the current presumed file, check to make sure the
1194 // presumed include stack isn't empty!
1195 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001196 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001197 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001198 if (PLoc.isInvalid())
1199 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001200
Chris Lattner1c967782009-02-04 06:25:26 +00001201 // If there is no include loc (main file) or if the include loc is in a
1202 // different physical file, then we aren't in a "1" line marker flag region.
1203 SourceLocation IncLoc = PLoc.getIncludeLoc();
1204 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001205 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001206 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1207 PP.DiscardUntilEndOfDirective();
1208 return true;
1209 }
Mike Stump11289f42009-09-09 15:08:12 +00001210
Chris Lattner76e68962009-01-26 06:19:46 +00001211 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001212 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001213 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1214 return true;
1215 }
1216
1217 // We must have 3 if there are still flags.
1218 if (FlagVal != 3) {
1219 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001220 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001221 return true;
1222 }
Mike Stump11289f42009-09-09 15:08:12 +00001223
Reid Klecknereb00ee02017-05-22 21:42:58 +00001224 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001225
Chris Lattner76e68962009-01-26 06:19:46 +00001226 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001227 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001228 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001229 return true;
1230
1231 // We must have 4 if there is yet another flag.
1232 if (FlagVal != 4) {
1233 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001234 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001235 return true;
1236 }
Mike Stump11289f42009-09-09 15:08:12 +00001237
Reid Klecknereb00ee02017-05-22 21:42:58 +00001238 FileKind = SrcMgr::C_ExternCSystem;
Mike Stump11289f42009-09-09 15:08:12 +00001239
Chris Lattner76e68962009-01-26 06:19:46 +00001240 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001241 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001242
1243 // There are no more valid flags here.
1244 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001245 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001246 return true;
1247}
1248
1249/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1250/// one of the following forms:
1251///
1252/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001253/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001254/// # 42 "file" ('1' | '2')? '3' '4'?
1255///
1256void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1257 // Validate the number and convert it to an unsigned. GNU does not have a
1258 // line # limit other than it fit in 32-bits.
1259 unsigned LineNo;
1260 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001261 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001262 return;
Mike Stump11289f42009-09-09 15:08:12 +00001263
Chris Lattner76e68962009-01-26 06:19:46 +00001264 Token StrTok;
1265 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001266
Chris Lattner76e68962009-01-26 06:19:46 +00001267 bool IsFileEntry = false, IsFileExit = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001268 int FilenameID = -1;
Reid Klecknereb00ee02017-05-22 21:42:58 +00001269 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001270
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001271 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1272 // string followed by eod.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001273 if (StrTok.is(tok::eod)) {
1274 // Treat this like "#line NN", which doesn't change file characteristics.
Chandler Carruthd92d70b2019-01-19 06:36:00 +00001275 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1276 } else if (StrTok.isNot(tok::string_literal)) {
1277 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1278 DiscardUntilEndOfDirective();
1279 return;
1280 } else if (StrTok.hasUDSuffix()) {
1281 Diag(StrTok, diag::err_invalid_string_udl);
1282 DiscardUntilEndOfDirective();
1283 return;
1284 } else {
1285 // Parse and validate the string, converting it into a unique ID.
1286 StringLiteralParser Literal(StrTok, *this);
1287 assert(Literal.isAscii() && "Didn't allow wide strings in");
1288 if (Literal.hadError) {
1289 DiscardUntilEndOfDirective();
1290 return;
1291 }
1292 if (Literal.Pascal) {
1293 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1294 DiscardUntilEndOfDirective();
1295 return;
1296 }
1297 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1298
Chris Lattner76e68962009-01-26 06:19:46 +00001299 // If a filename was present, read any flags that are present.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001300 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001301 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001302 }
Mike Stump11289f42009-09-09 15:08:12 +00001303
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001304 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001305 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1306 IsFileExit, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001307
Chris Lattner839150e2009-03-27 17:13:49 +00001308 // If the preprocessor has callbacks installed, notify them of the #line
1309 // change. This is used so that the line marker comes out in -E mode for
1310 // example.
1311 if (Callbacks) {
1312 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1313 if (IsFileEntry)
1314 Reason = PPCallbacks::EnterFile;
1315 else if (IsFileExit)
1316 Reason = PPCallbacks::ExitFile;
Mike Stump11289f42009-09-09 15:08:12 +00001317
Chris Lattnerc745cec2010-04-14 04:28:50 +00001318 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001319 }
Chris Lattner76e68962009-01-26 06:19:46 +00001320}
1321
Chris Lattner38d7fd22009-01-26 05:30:54 +00001322/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1323///
Mike Stump11289f42009-09-09 15:08:12 +00001324void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001325 bool isWarning) {
1326 // Read the rest of the line raw. We do this because we don't want macros
1327 // to be expanded and we don't require that the tokens be valid preprocessing
1328 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001329 // collapse multiple consecutive white space between tokens, but this isn't
Chris Lattnerf64b3522008-03-09 01:54:53 +00001330 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001331 SmallString<128> Message;
1332 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001333
1334 // Find the first non-whitespace character, so that we can make the
1335 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001336 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001337
Chris Lattner100c65e2009-01-26 05:29:08 +00001338 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001339 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001340 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001341 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001342}
1343
1344/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1345///
1346void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1347 // Yes, this directive is an extension.
1348 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001349
Chris Lattnerf64b3522008-03-09 01:54:53 +00001350 // Read the string argument.
1351 Token StrTok;
1352 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001353
Chris Lattnerf64b3522008-03-09 01:54:53 +00001354 // If the token kind isn't a string, it's a malformed directive.
1355 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001356 StrTok.isNot(tok::wide_string_literal)) {
1357 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001358 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001359 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001360 return;
1361 }
Chandler Carruthd92d70b2019-01-19 06:36:00 +00001362
1363 if (StrTok.hasUDSuffix()) {
1364 Diag(StrTok, diag::err_invalid_string_udl);
1365 DiscardUntilEndOfDirective();
1366 return;
1367 }
1368
1369 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001370 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001371
Douglas Gregordc970f02010-03-16 22:30:13 +00001372 if (Callbacks) {
1373 bool Invalid = false;
1374 std::string Str = getSpelling(StrTok, &Invalid);
1375 if (!Invalid)
1376 Callbacks->Ident(Tok.getLocation(), Str);
1377 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001378}
1379
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001380/// Handle a #public directive.
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001381void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001382 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001383 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001384
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001385 // Error reading macro name? If so, diagnostic already issued.
1386 if (MacroNameTok.is(tok::eod))
1387 return;
1388
Douglas Gregor663b48f2012-01-03 19:48:16 +00001389 // Check to see if this is the last token on the #__public_macro line.
1390 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001391
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001392 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001393 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001394 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001395
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001396 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001397 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001398 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001399 return;
1400 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001401
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001402 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001403 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1404 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001405}
1406
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001407/// Handle a #private directive.
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001408void Preprocessor::HandleMacroPrivateDirective() {
Douglas Gregorebf00492011-10-17 15:32:29 +00001409 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001410 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001411
Douglas Gregorebf00492011-10-17 15:32:29 +00001412 // Error reading macro name? If so, diagnostic already issued.
1413 if (MacroNameTok.is(tok::eod))
1414 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001415
Douglas Gregor663b48f2012-01-03 19:48:16 +00001416 // Check to see if this is the last token on the #__private_macro line.
1417 CheckEndOfDirective("__private_macro");
Taewook Oh755e4d22016-06-13 21:55:33 +00001418
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001419 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001420 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001421 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001422
Douglas Gregorebf00492011-10-17 15:32:29 +00001423 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001424 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001425 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001426 return;
1427 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001428
Douglas Gregorebf00492011-10-17 15:32:29 +00001429 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001430 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1431 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001432}
1433
Chris Lattnerf64b3522008-03-09 01:54:53 +00001434//===----------------------------------------------------------------------===//
1435// Preprocessor Include Directive Handling.
1436//===----------------------------------------------------------------------===//
1437
1438/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001439/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001440/// true if the input filename was in <>'s or false if it were in ""'s. The
1441/// caller is expected to provide a buffer that is large enough to hold the
1442/// spelling of the filename, but is also expected to handle the case when
1443/// this method decides to use a different buffer.
1444bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001445 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001446 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001447 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001448
Chris Lattnerf64b3522008-03-09 01:54:53 +00001449 // Make sure the filename is <x> or "x".
1450 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001451 if (Buffer[0] == '<') {
1452 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001453 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001454 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001455 return true;
1456 }
1457 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001458 } else if (Buffer[0] == '"') {
1459 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001460 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001461 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001462 return true;
1463 }
1464 isAngled = false;
1465 } else {
1466 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001467 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001468 return true;
1469 }
Mike Stump11289f42009-09-09 15:08:12 +00001470
Chris Lattnerf64b3522008-03-09 01:54:53 +00001471 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001472 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001473 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001474 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001475 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001476 }
Mike Stump11289f42009-09-09 15:08:12 +00001477
Chris Lattnerf64b3522008-03-09 01:54:53 +00001478 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001479 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001480 return isAngled;
1481}
1482
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001483// Handle cases where the \#include name is expanded from a macro
James Dennett4a4f72d2013-11-27 01:27:40 +00001484// as multiple tokens, which need to be glued together.
1485//
1486// This occurs for code like:
1487// \code
1488// \#define FOO <a/b.h>
1489// \#include FOO
1490// \endcode
1491// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1492//
1493// This code concatenates and consumes tokens up to the '>' token. It returns
1494// false if the > was found, otherwise it returns true if it finds and consumes
1495// the EOD marker.
1496bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001497 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001498 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001499
John Thompsonb5353522009-10-30 13:49:06 +00001500 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001501 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001502 End = CurTok.getLocation();
Taewook Oh755e4d22016-06-13 21:55:33 +00001503
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001504 // FIXME: Provide code completion for #includes.
1505 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001506 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001507 Lex(CurTok);
1508 continue;
1509 }
1510
Chris Lattnerf64b3522008-03-09 01:54:53 +00001511 // Append the spelling of this token to the buffer. If there was a space
1512 // before it, add it now.
1513 if (CurTok.hasLeadingSpace())
1514 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001515
Chris Lattnerf64b3522008-03-09 01:54:53 +00001516 // Get the spelling of the token, directly into FilenameBuffer if possible.
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001517 size_t PreAppendSize = FilenameBuffer.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001518 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001519
Chris Lattnerf64b3522008-03-09 01:54:53 +00001520 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001521 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001522
Chris Lattnerf64b3522008-03-09 01:54:53 +00001523 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1524 if (BufPtr != &FilenameBuffer[PreAppendSize])
1525 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattnerf64b3522008-03-09 01:54:53 +00001527 // Resize FilenameBuffer to the correct size.
1528 if (CurTok.getLength() != ActualLen)
1529 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001530
Chris Lattnerf64b3522008-03-09 01:54:53 +00001531 // If we found the '>' marker, return success.
1532 if (CurTok.is(tok::greater))
1533 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001534
John Thompsonb5353522009-10-30 13:49:06 +00001535 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001536 }
1537
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001538 // If we hit the eod marker, emit an error and return true so that the caller
1539 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001540 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001541 return true;
1542}
1543
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001544/// Push a token onto the token stream containing an annotation.
Richard Smithc51c38b2017-04-29 00:34:47 +00001545void Preprocessor::EnterAnnotationToken(SourceRange Range,
1546 tok::TokenKind Kind,
1547 void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001548 // FIXME: Produce this as the current token directly, rather than
1549 // allocating a new token for it.
David Blaikie2eabcc92016-02-09 18:52:09 +00001550 auto Tok = llvm::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001551 Tok[0].startToken();
1552 Tok[0].setKind(Kind);
Richard Smithc51c38b2017-04-29 00:34:47 +00001553 Tok[0].setLocation(Range.getBegin());
1554 Tok[0].setAnnotationEndLoc(Range.getEnd());
Richard Smith34f30512013-11-23 04:06:09 +00001555 Tok[0].setAnnotationValue(AnnotationVal);
Richard Smithc51c38b2017-04-29 00:34:47 +00001556 EnterTokenStream(std::move(Tok), 1, true);
Richard Smith34f30512013-11-23 04:06:09 +00001557}
1558
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001559/// Produce a diagnostic informing the user that a #include or similar
Richard Smith63b6fce2015-05-18 04:45:41 +00001560/// was implicitly treated as a module import.
1561static void diagnoseAutoModuleImport(
1562 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1563 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1564 SourceLocation PathEnd) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00001565 assert(PP.getLangOpts().ObjC && "no import syntax available");
Richard Smith63b6fce2015-05-18 04:45:41 +00001566
1567 SmallString<128> PathString;
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001568 for (size_t I = 0, N = Path.size(); I != N; ++I) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001569 if (I)
1570 PathString += '.';
1571 PathString += Path[I].first->getName();
1572 }
1573 int IncludeKind = 0;
Taewook Oh755e4d22016-06-13 21:55:33 +00001574
Richard Smith63b6fce2015-05-18 04:45:41 +00001575 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1576 case tok::pp_include:
1577 IncludeKind = 0;
1578 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001579
Richard Smith63b6fce2015-05-18 04:45:41 +00001580 case tok::pp_import:
1581 IncludeKind = 1;
Taewook Oh755e4d22016-06-13 21:55:33 +00001582 break;
1583
Richard Smith63b6fce2015-05-18 04:45:41 +00001584 case tok::pp_include_next:
1585 IncludeKind = 2;
1586 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001587
Richard Smith63b6fce2015-05-18 04:45:41 +00001588 case tok::pp___include_macros:
1589 IncludeKind = 3;
1590 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001591
Richard Smith63b6fce2015-05-18 04:45:41 +00001592 default:
1593 llvm_unreachable("unknown include directive kind");
1594 }
1595
1596 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1597 /*IsTokenRange=*/false);
1598 PP.Diag(HashLoc, diag::warn_auto_module_import)
1599 << IncludeKind << PathString
1600 << FixItHint::CreateReplacement(ReplaceRange,
1601 ("@import " + PathString + ";").str());
1602}
1603
Taewook Ohf42103c2016-06-13 20:40:21 +00001604// Given a vector of path components and a string containing the real
1605// path to the file, build a properly-cased replacement in the vector,
1606// and return true if the replacement should be suggested.
1607static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1608 StringRef RealPathName) {
1609 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1610 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1611 int Cnt = 0;
1612 bool SuggestReplacement = false;
1613 // Below is a best-effort to handle ".." in paths. It is admittedly
1614 // not 100% correct in the presence of symlinks.
1615 for (auto &Component : llvm::reverse(Components)) {
1616 if ("." == Component) {
1617 } else if (".." == Component) {
1618 ++Cnt;
1619 } else if (Cnt) {
1620 --Cnt;
1621 } else if (RealPathComponentIter != RealPathComponentEnd) {
1622 if (Component != *RealPathComponentIter) {
1623 // If these path components differ by more than just case, then we
1624 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1625 // noisy false positives.
1626 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1627 if (!SuggestReplacement)
1628 break;
1629 Component = *RealPathComponentIter;
1630 }
1631 ++RealPathComponentIter;
1632 }
1633 }
1634 return SuggestReplacement;
1635}
1636
Richard Smith27e5aa02017-06-05 18:57:56 +00001637bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
1638 const TargetInfo &TargetInfo,
1639 DiagnosticsEngine &Diags, Module *M) {
1640 Module::Requirement Requirement;
1641 Module::UnresolvedHeaderDirective MissingHeader;
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00001642 Module *ShadowingModule = nullptr;
1643 if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
1644 ShadowingModule))
Richard Smith27e5aa02017-06-05 18:57:56 +00001645 return false;
1646
1647 if (MissingHeader.FileNameLoc.isValid()) {
1648 Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1649 << MissingHeader.IsUmbrella << MissingHeader.FileName;
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00001650 } else if (ShadowingModule) {
1651 Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name;
1652 Diags.Report(ShadowingModule->DefinitionLoc,
1653 diag::note_previous_definition);
Richard Smith27e5aa02017-06-05 18:57:56 +00001654 } else {
1655 // FIXME: Track the location at which the requirement was specified, and
1656 // use it here.
1657 Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
1658 << M->getFullModuleName() << Requirement.second << Requirement.first;
1659 }
1660 return true;
1661}
1662
James Dennettf6333ac2012-06-22 05:46:07 +00001663/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1664/// the file to be included from the lexer, then include it! This is a common
1665/// routine with functionality shared between \#include, \#include_next and
1666/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001667/// specifies the file to start searching from.
Taewook Oh755e4d22016-06-13 21:55:33 +00001668void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001669 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001670 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001671 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001672 bool isImport) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001673 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001674 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001675
Chris Lattnerf64b3522008-03-09 01:54:53 +00001676 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001677 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001678 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001679 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001680 SourceLocation CharEnd; // the end of this directive, in characters
Taewook Oh755e4d22016-06-13 21:55:33 +00001681
Chris Lattnerf64b3522008-03-09 01:54:53 +00001682 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001683 case tok::eod:
1684 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001685 return;
Mike Stump11289f42009-09-09 15:08:12 +00001686
Chris Lattnerf64b3522008-03-09 01:54:53 +00001687 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001688 case tok::string_literal:
1689 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001690 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001691 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001692 break;
Mike Stump11289f42009-09-09 15:08:12 +00001693
Chris Lattnerf64b3522008-03-09 01:54:53 +00001694 case tok::less:
1695 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1696 // case, glue the tokens together into FilenameBuffer and interpret those.
1697 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001698 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001699 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001700 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001701 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001702 break;
1703 default:
1704 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1705 DiscardUntilEndOfDirective();
1706 return;
1707 }
Mike Stump11289f42009-09-09 15:08:12 +00001708
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001709 CharSourceRange FilenameRange
1710 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001711 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001712 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001713 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001714 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1715 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001716 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001717 DiscardUntilEndOfDirective();
1718 return;
1719 }
Mike Stump11289f42009-09-09 15:08:12 +00001720
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001721 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001722 // we allow macros that expand to nothing after the filename, because this
1723 // falls into the category of "#include pp-tokens new-line" specified in
1724 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001725 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001726
John McCall32f5fe12011-09-30 05:12:12 +00001727 // Complain about attempts to #include files in an audit pragma.
1728 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1729 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1730 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1731
1732 // Immediately leave the pragma.
1733 PragmaARCCFCodeAuditedLoc = SourceLocation();
1734 }
1735
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001736 // Complain about attempts to #include files in an assume-nonnull pragma.
1737 if (PragmaAssumeNonNullLoc.isValid()) {
1738 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1739 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1740
1741 // Immediately leave the pragma.
1742 PragmaAssumeNonNullLoc = SourceLocation();
1743 }
1744
Aaron Ballman611306e2012-03-02 22:51:54 +00001745 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001746 // Map the filename with the brackets still attached. If the name doesn't
1747 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001748 // spelling for.
1749 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1750 if (!NewName.empty())
1751 Filename = NewName;
1752 }
1753
Chris Lattnerf64b3522008-03-09 01:54:53 +00001754 // Search include directories.
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001755 bool IsMapped = false;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001756 bool IsFrameworkFound = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001757 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001758 SmallString<1024> SearchPath;
1759 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001760 // We get the raw path only if we have 'Callbacks' to which we later pass
1761 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001762 ModuleMap::KnownHeader SuggestedModule;
1763 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001764 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001765 if (LangOpts.MSVCCompat) {
1766 NormalizedPath = Filename.str();
Nico Weber1865df42018-04-27 19:11:14 +00001767#ifndef _WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001768 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001769#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001770 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001771 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001772 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001773 isAngled, LookupFrom, LookupFromFile, CurDir,
1774 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001775 &SuggestedModule, &IsMapped, &IsFrameworkFound);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001776
Richard Smithdbbc5232015-05-14 02:25:44 +00001777 if (!File) {
1778 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001779 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001780 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001781 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1782 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1783 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001784 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001785 HeaderInfo.AddSearchPath(DL, isAngled);
Taewook Oh755e4d22016-06-13 21:55:33 +00001786
Douglas Gregor11729f02011-11-30 18:12:06 +00001787 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001788 File = LookupFile(
1789 FilenameLoc,
1790 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1791 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001792 &SuggestedModule, &IsMapped, /*IsFrameworkFound=*/nullptr,
1793 /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001794 }
1795 }
1796 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001797
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001798 if (!SuppressIncludeNotFoundError) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001799 // If the file could not be located and it was included via angle
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001800 // brackets, we can attempt a lookup as though it were a quoted path to
1801 // provide the user with a possible fixit.
1802 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001803 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001804 FilenameLoc,
1805 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1806 LookupFrom, LookupFromFile, CurDir,
1807 Callbacks ? &SearchPath : nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001808 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
1809 /*IsFrameworkFound=*/nullptr);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001810 if (File) {
1811 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Richard Smith2ce63b42018-09-13 21:10:08 +00001812 Diag(FilenameTok, diag::err_pp_file_not_found_angled_include_not_fatal) <<
Taewook Oh755e4d22016-06-13 21:55:33 +00001813 Filename <<
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001814 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1815 }
1816 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001817
Richard Smith2ce63b42018-09-13 21:10:08 +00001818 // Check for likely typos due to leading or trailing non-isAlphanumeric
1819 // characters
Eric Christopher918b47f2018-09-20 17:21:56 +00001820 StringRef OriginalFilename = Filename;
Haojian Wudea57712018-10-02 13:59:49 +00001821 if (LangOpts.SpellChecking && !File) {
Haojian Wu1743ebe2018-10-01 14:38:43 +00001822 // A heuristic to correct a typo file name by removing leading and
1823 // trailing non-isAlphanumeric characters.
1824 auto CorrectTypoFilename = [](llvm::StringRef Filename) {
1825 Filename = Filename.drop_until(isAlphanumeric);
1826 while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
1827 Filename = Filename.drop_back();
1828 }
1829 return Filename;
1830 };
Haojian Wu714e9712018-10-02 14:42:51 +00001831 StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
Volodymyr Sapsai3bbdd872019-01-15 20:08:23 +00001832 SmallString<128> NormalizedTypoCorrectionPath;
1833 if (LangOpts.MSVCCompat) {
1834 NormalizedTypoCorrectionPath = TypoCorrectionName.str();
1835#ifndef _WIN32
1836 llvm::sys::path::native(NormalizedTypoCorrectionPath);
1837#endif
1838 }
Richard Smith2ce63b42018-09-13 21:10:08 +00001839 File = LookupFile(
1840 FilenameLoc,
Volodymyr Sapsai3bbdd872019-01-15 20:08:23 +00001841 LangOpts.MSVCCompat ? NormalizedTypoCorrectionPath.c_str()
1842 : TypoCorrectionName,
Haojian Wu714e9712018-10-02 14:42:51 +00001843 isAngled, LookupFrom, LookupFromFile, CurDir,
Richard Smith2ce63b42018-09-13 21:10:08 +00001844 Callbacks ? &SearchPath : nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001845 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
1846 /*IsFrameworkFound=*/nullptr);
Richard Smith2ce63b42018-09-13 21:10:08 +00001847 if (File) {
1848 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Haojian Wu714e9712018-10-02 14:42:51 +00001849 auto Hint = isAngled
1850 ? FixItHint::CreateReplacement(
1851 Range, "<" + TypoCorrectionName.str() + ">")
1852 : FixItHint::CreateReplacement(
1853 Range, "\"" + TypoCorrectionName.str() + "\"");
Richard Smith2ce63b42018-09-13 21:10:08 +00001854 Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
Haojian Wu714e9712018-10-02 14:42:51 +00001855 << OriginalFilename << TypoCorrectionName << Hint;
1856 // We found the file, so set the Filename to the name after typo
1857 // correction.
1858 Filename = TypoCorrectionName;
Richard Smith2ce63b42018-09-13 21:10:08 +00001859 }
1860 }
1861
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001862 // If the file is still not found, just go with the vanilla diagnostic
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001863 if (!File) {
Eric Christopher918b47f2018-09-20 17:21:56 +00001864 Diag(FilenameTok, diag::err_pp_file_not_found) << OriginalFilename
Erik Verbruggen45449542016-10-25 10:13:10 +00001865 << FilenameRange;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +00001866 if (IsFrameworkFound) {
1867 size_t SlashPos = OriginalFilename.find('/');
1868 assert(SlashPos != StringRef::npos &&
1869 "Include with framework name should have '/' in the filename");
1870 StringRef FrameworkName = OriginalFilename.substr(0, SlashPos);
1871 FrameworkCacheEntry &CacheEntry =
1872 HeaderInfo.LookupFrameworkCache(FrameworkName);
1873 assert(CacheEntry.Directory && "Found framework should be in cache");
1874 Diag(FilenameTok, diag::note_pp_framework_without_header)
1875 << OriginalFilename.substr(SlashPos + 1) << FrameworkName
1876 << CacheEntry.Directory->getName();
1877 }
1878 }
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001879 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001880 }
1881
Erich Keane76675de2018-07-05 17:22:13 +00001882 if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
1883 if (isPCHThroughHeader(File))
1884 SkippingUntilPCHThroughHeader = false;
1885 return;
1886 }
1887
Richard Smith63b6fce2015-05-18 04:45:41 +00001888 // Should we enter the source file? Set to false if either the source file is
1889 // known to have no effect beyond its effect on module visibility -- that is,
1890 // if it's got an include guard that is already defined or is a modular header
1891 // we've imported or already built.
1892 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001893
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001894 if (PPOpts->SingleFileParseMode)
1895 ShouldEnter = false;
1896
Volodymyr Sapsai978be4c12018-12-07 20:29:54 +00001897 // If we've reached the max allowed include depth, it is usually due to an
1898 // include cycle. Don't enter already processed files again as it can lead to
1899 // reaching the max allowed include depth again.
1900 if (ShouldEnter && HasReachedMaxIncludeDepth && File &&
1901 HeaderInfo.getFileInfo(File).NumIncludes)
Volodymyr Sapsai482070b2018-07-25 19:16:26 +00001902 ShouldEnter = false;
1903
Richard Smith63b6fce2015-05-18 04:45:41 +00001904 // Determine whether we should try to import the module for this #include, if
1905 // there is one. Don't do so if precompiled module support is disabled or we
1906 // are processing this module textually (because we're building the module).
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001907 if (ShouldEnter && File && SuggestedModule && getLangOpts().Modules &&
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +00001908 !isForModuleBuilding(SuggestedModule.getModule(),
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00001909 getLangOpts().CurrentModule,
1910 getLangOpts().ModuleName)) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001911 // If this include corresponds to a module but that module is
1912 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001913 // FIXME: Remove this; loadModule does the same check (but produces
1914 // slightly worse diagnostics).
Richard Smith27e5aa02017-06-05 18:57:56 +00001915 if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
1916 SuggestedModule.getModule())) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001917 Diag(FilenameTok.getLocation(),
1918 diag::note_implicit_top_level_module_import_here)
Richard Smith27e5aa02017-06-05 18:57:56 +00001919 << SuggestedModule.getModule()->getTopLevelModuleName();
Sean Silva8b7c0392015-08-17 16:39:30 +00001920 return;
1921 }
1922
Douglas Gregor71944202011-11-30 00:36:36 +00001923 // Compute the module access path corresponding to this module.
1924 // FIXME: Should we have a second loadModule() overload to avoid this
1925 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001926 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001927 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001928 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1929 FilenameTok.getLocation()));
1930 std::reverse(Path.begin(), Path.end());
1931
Douglas Gregor41e115a2011-11-30 18:02:36 +00001932 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001933 // We only do this in Objective-C, where we have a module-import syntax.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00001934 if (getLangOpts().ObjC)
Richard Smith63b6fce2015-05-18 04:45:41 +00001935 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001936
Richard Smith10434f32015-05-02 02:08:26 +00001937 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001938 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001939 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1940 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001941 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1942 IncludeTok.getLocation(), Path, Module::Hidden,
1943 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001944 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001945 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001946
Richard Smith63b6fce2015-05-18 04:45:41 +00001947 if (Imported)
1948 ShouldEnter = false;
1949 else if (Imported.isMissingExpected()) {
1950 // We failed to find a submodule that we assumed would exist (because it
1951 // was in the directory of an umbrella header, for instance), but no
Richard Smitha114c462016-12-06 00:40:17 +00001952 // actual module containing it exists (because the umbrella header is
Richard Smith63b6fce2015-05-18 04:45:41 +00001953 // incomplete). Treat this as a textual inclusion.
1954 SuggestedModule = ModuleMap::KnownHeader();
Richard Smitha114c462016-12-06 00:40:17 +00001955 } else if (Imported.isConfigMismatch()) {
1956 // On a configuration mismatch, enter the header textually. We still know
1957 // that it's part of the corresponding module.
Richard Smith63b6fce2015-05-18 04:45:41 +00001958 } else {
1959 // We hit an error processing the import. Bail out.
1960 if (hadModuleLoaderFatalFailure()) {
1961 // With a fatal failure in the module loader, we abort parsing.
1962 Token &Result = IncludeTok;
Erich Keane0a6b5b62018-12-04 14:34:09 +00001963 assert(CurLexer && "#include but no current lexer set!");
1964 Result.startToken();
1965 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1966 CurLexer->cutOffLexing();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001967 }
1968 return;
1969 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001970 }
1971
Richard Smithc5247e62017-05-30 02:03:19 +00001972 // The #included file will be considered to be a system header if either it is
1973 // in a system include directory, or if the #includer is a system include
1974 // header.
1975 SrcMgr::CharacteristicKind FileCharacter =
1976 SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
1977 if (File)
1978 FileCharacter = std::max(HeaderInfo.getFileDirFlavor(File), FileCharacter);
1979
1980 // Ask HeaderInfo if we should enter this #include file. If not, #including
1981 // this file will have no effect.
1982 bool SkipHeader = false;
1983 if (ShouldEnter && File &&
1984 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
1985 getLangOpts().Modules,
1986 SuggestedModule.getModule())) {
1987 ShouldEnter = false;
1988 SkipHeader = true;
1989 }
1990
Richard Smith63b6fce2015-05-18 04:45:41 +00001991 if (Callbacks) {
1992 // Notify the callback object that we've seen an inclusion directive.
1993 Callbacks->InclusionDirective(
1994 HashLoc, IncludeTok,
1995 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1996 FilenameRange, File, SearchPath, RelativePath,
Julie Hockett96fbe582018-05-10 19:05:36 +00001997 ShouldEnter ? nullptr : SuggestedModule.getModule(), FileCharacter);
Richard Smithc5247e62017-05-30 02:03:19 +00001998 if (SkipHeader && !SuggestedModule.getModule())
1999 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Douglas Gregor97eec242011-09-15 22:00:41 +00002000 }
Richard Smith63b6fce2015-05-18 04:45:41 +00002001
2002 if (!File)
2003 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00002004
Richard Smith54ef4c32015-05-19 19:58:11 +00002005 // FIXME: If we have a suggested module, and we've already visited this file,
2006 // don't bother entering it again. We know it has no further effect.
2007
Taewook Ohf42103c2016-06-13 20:40:21 +00002008 // Issue a diagnostic if the name of the file on disk has a different case
2009 // than the one we're about to open.
2010 const bool CheckIncludePathPortability =
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00002011 !IsMapped && File && !File->tryGetRealPathName().empty();
Taewook Ohf42103c2016-06-13 20:40:21 +00002012
2013 if (CheckIncludePathPortability) {
2014 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
2015 StringRef RealPathName = File->tryGetRealPathName();
2016 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
2017 llvm::sys::path::end(Name));
2018
2019 if (trySimplifyPath(Components, RealPathName)) {
2020 SmallString<128> Path;
2021 Path.reserve(Name.size()+2);
2022 Path.push_back(isAngled ? '<' : '"');
Taewook Ohcc89bac2017-02-21 22:30:55 +00002023 bool isLeadingSeparator = llvm::sys::path::is_absolute(Name);
Taewook Ohf42103c2016-06-13 20:40:21 +00002024 for (auto Component : Components) {
Taewook Ohcc89bac2017-02-21 22:30:55 +00002025 if (isLeadingSeparator)
2026 isLeadingSeparator = false;
2027 else
2028 Path.append(Component);
Taewook Ohf42103c2016-06-13 20:40:21 +00002029 // Append the separator the user used, or the close quote
2030 Path.push_back(
2031 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
2032 (isAngled ? '>' : '"'));
2033 }
Taewook Ohf42103c2016-06-13 20:40:21 +00002034 // For user files and known standard headers, by default we issue a diagnostic.
2035 // For other system headers, we don't. They can be controlled separately.
2036 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
2037 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
2038 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Reid Kleckner273895b2017-02-14 18:38:40 +00002039 Diag(FilenameTok, DiagId) << Path <<
2040 FixItHint::CreateReplacement(Range, Path);
Taewook Ohf42103c2016-06-13 20:40:21 +00002041 }
2042 }
2043
Richard Smith63b6fce2015-05-18 04:45:41 +00002044 // If we don't need to enter the file, stop now.
2045 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00002046 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00002047 if (auto *M = SuggestedModule.getModule()) {
Manman Renffd3e9d2017-01-09 19:20:18 +00002048 // When building a pch, -fmodule-name tells the compiler to textually
2049 // include headers in the specified module. But it is possible that
2050 // ShouldEnter is false because we are skipping the header. In that
2051 // case, We are not importing the specified module.
2052 if (SkipHeader && getLangOpts().CompilingPCH &&
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00002053 isForModuleBuilding(M, getLangOpts().CurrentModule,
2054 getLangOpts().ModuleName))
Manman Renffd3e9d2017-01-09 19:20:18 +00002055 return;
2056
Richard Smitha0aafa32015-05-18 03:52:30 +00002057 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00002058
2059 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
2060 tok::pp___include_macros)
Richard Smithc51c38b2017-04-29 00:34:47 +00002061 EnterAnnotationToken(SourceRange(HashLoc, End),
2062 tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00002063 }
Chris Lattner72286d62010-04-19 20:44:31 +00002064 return;
2065 }
2066
Richard Smith5a8ea4c2019-03-19 01:51:17 +00002067 // Check that we don't have infinite #include recursion.
2068 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
2069 Diag(FilenameTok, diag::err_pp_include_too_deep);
2070 HasReachedMaxIncludeDepth = true;
2071 return;
2072 }
2073
Chris Lattnerf64b3522008-03-09 01:54:53 +00002074 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002075 SourceLocation IncludePos = End;
2076 // If the filename string was the result of macro expansions, set the include
2077 // position on the file where it will be included and after the expansions.
2078 if (IncludePos.isMacroID())
Richard Smithb5f81712018-04-30 05:25:48 +00002079 IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002080 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002081 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002082
Richard Smith34f30512013-11-23 04:06:09 +00002083 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002084 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
2085 return;
Richard Smith34f30512013-11-23 04:06:09 +00002086
Richard Smitha0aafa32015-05-18 03:52:30 +00002087 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002088 if (auto *M = SuggestedModule.getModule()) {
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00002089 if (M->getTopLevelModule()->ShadowingModule) {
2090 // We are building a submodule that belongs to a shadowed module. This
2091 // means we find header files in the shadowed module.
2092 Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule)
2093 << M->getFullModuleName();
2094 Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc,
2095 diag::note_previous_definition);
2096 return;
2097 }
Manman Renffd3e9d2017-01-09 19:20:18 +00002098 // When building a pch, -fmodule-name tells the compiler to textually
2099 // include headers in the specified module. We are not building the
2100 // specified module.
2101 if (getLangOpts().CompilingPCH &&
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00002102 isForModuleBuilding(M, getLangOpts().CurrentModule,
2103 getLangOpts().ModuleName))
Manman Renffd3e9d2017-01-09 19:20:18 +00002104 return;
2105
Richard Smithd1386302017-05-04 00:29:54 +00002106 assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2107 CurLexerSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002108
Richard Smitha0aafa32015-05-18 03:52:30 +00002109 // Let the macro handling code know that any future macros are within
2110 // the new submodule.
Richard Smithd1386302017-05-04 00:29:54 +00002111 EnterSubmodule(M, HashLoc, /*ForPragma*/false);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002112
Richard Smitha0aafa32015-05-18 03:52:30 +00002113 // Let the parser know that any future declarations are within the new
2114 // submodule.
2115 // FIXME: There's no point doing this if we're handling a #__include_macros
2116 // directive.
Richard Smithc51c38b2017-04-29 00:34:47 +00002117 EnterAnnotationToken(SourceRange(HashLoc, End), tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00002118 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002119}
2120
James Dennettf6333ac2012-06-22 05:46:07 +00002121/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002122///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002123void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2124 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002125 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002126
Chris Lattnerf64b3522008-03-09 01:54:53 +00002127 // #include_next is like #include, except that we start searching after
2128 // the current found directory. If we can't do this, issue a
2129 // diagnostic.
2130 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002131 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00002132 if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2133 // If the main file is a header, then it's either for PCH/AST generation,
2134 // or libclang opened it. Either way, handle it as a normal include below
2135 // and do not complain about include_next.
2136 } else if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002137 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002138 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smithd1386302017-05-04 00:29:54 +00002139 } else if (CurLexerSubmodule) {
Richard Smith25d50752014-10-20 00:15:49 +00002140 // Start looking up in the directory *after* the one in which the current
2141 // file would be found, if any.
2142 assert(CurPPLexer && "#include_next directive in macro?");
2143 LookupFromFile = CurPPLexer->getFileEntry();
2144 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002145 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002146 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2147 } else {
2148 // Start looking up in the next directory.
2149 ++Lookup;
2150 }
Mike Stump11289f42009-09-09 15:08:12 +00002151
Richard Smith25d50752014-10-20 00:15:49 +00002152 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2153 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002154}
2155
James Dennettf6333ac2012-06-22 05:46:07 +00002156/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002157void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2158 // The Microsoft #import directive takes a type library and generates header
2159 // files from it, and includes those. This is beyond the scope of what clang
2160 // does, so we ignore it and error out. However, #import can optionally have
2161 // trailing attributes that span multiple lines. We're going to eat those
2162 // so we can continue processing from there.
2163 Diag(Tok, diag::err_pp_import_directive_ms );
2164
Taewook Oh755e4d22016-06-13 21:55:33 +00002165 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002166 // directive can be split over multiple lines using the backslash character.
2167 DiscardUntilEndOfDirective();
2168}
2169
James Dennettf6333ac2012-06-22 05:46:07 +00002170/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002171///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002172void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2173 Token &ImportTok) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002174 if (!LangOpts.ObjC) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002175 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002176 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002177 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002178 }
Richard Smith25d50752014-10-20 00:15:49 +00002179 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002180}
2181
Chris Lattner58a1eb02009-04-08 18:46:40 +00002182/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2183/// pseudo directive in the predefines buffer. This handles it by sucking all
2184/// tokens through the preprocessor and discarding them (only keeping the side
2185/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002186void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2187 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002188 // This directive should only occur in the predefines buffer. If not, emit an
2189 // error and reject it.
2190 SourceLocation Loc = IncludeMacrosTok.getLocation();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002191 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002192 Diag(IncludeMacrosTok.getLocation(),
2193 diag::pp_include_macros_out_of_predefines);
2194 DiscardUntilEndOfDirective();
2195 return;
2196 }
Mike Stump11289f42009-09-09 15:08:12 +00002197
Chris Lattnere01d82b2009-04-08 20:53:24 +00002198 // Treat this as a normal #include for checking purposes. If this is
2199 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002200 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002201
Chris Lattnere01d82b2009-04-08 20:53:24 +00002202 Token TmpTok;
2203 do {
2204 Lex(TmpTok);
2205 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2206 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002207}
2208
Chris Lattnerf64b3522008-03-09 01:54:53 +00002209//===----------------------------------------------------------------------===//
2210// Preprocessor Macro Directive Handling.
2211//===----------------------------------------------------------------------===//
2212
Faisal Valie8f430a2017-09-29 02:43:22 +00002213/// ReadMacroParameterList - The ( starting a parameter list of a macro
2214/// definition has just been read. Lex the rest of the parameters and the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002215/// closing ), updating MI with what we learn. Return true if an error occurs
Faisal Valie8f430a2017-09-29 02:43:22 +00002216/// parsing the param list.
Faisal Valiac506d72017-07-17 17:18:43 +00002217bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
Faisal Vali33df3912017-09-29 02:17:31 +00002218 SmallVector<IdentifierInfo*, 32> Parameters;
Mike Stump11289f42009-09-09 15:08:12 +00002219
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002220 while (true) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002221 LexUnexpandedToken(Tok);
2222 switch (Tok.getKind()) {
2223 case tok::r_paren:
Faisal Valie8f430a2017-09-29 02:43:22 +00002224 // Found the end of the parameter list.
Faisal Vali33df3912017-09-29 02:17:31 +00002225 if (Parameters.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002226 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002227 // Otherwise we have #define FOO(A,)
2228 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2229 return true;
2230 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002231 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002232 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002233 diag::warn_cxx98_compat_variadic_macro :
2234 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002235
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002236 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2237 if (LangOpts.OpenCL) {
2238 Diag(Tok, diag::err_pp_opencl_variadic_macros);
2239 return true;
2240 }
2241
Chris Lattnerf64b3522008-03-09 01:54:53 +00002242 // Lex the token after the identifier.
2243 LexUnexpandedToken(Tok);
2244 if (Tok.isNot(tok::r_paren)) {
2245 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2246 return true;
2247 }
Faisal Valie8f430a2017-09-29 02:43:22 +00002248 // Add the __VA_ARGS__ identifier as a parameter.
Faisal Vali33df3912017-09-29 02:17:31 +00002249 Parameters.push_back(Ident__VA_ARGS__);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002250 MI->setIsC99Varargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002251 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002252 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002253 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002254 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2255 return true;
2256 default:
2257 // Handle keywords and identifiers here to accept things like
2258 // #define Foo(for) for.
2259 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002260 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002261 // #define X(1
2262 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2263 return true;
2264 }
2265
Faisal Valie8f430a2017-09-29 02:43:22 +00002266 // If this is already used as a parameter, it is used multiple times (e.g.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002267 // #define X(A,A.
Faisal Vali33df3912017-09-29 02:17:31 +00002268 if (std::find(Parameters.begin(), Parameters.end(), II) !=
2269 Parameters.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002270 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002271 return true;
2272 }
Mike Stump11289f42009-09-09 15:08:12 +00002273
Faisal Valie8f430a2017-09-29 02:43:22 +00002274 // Add the parameter to the macro info.
Faisal Vali33df3912017-09-29 02:17:31 +00002275 Parameters.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002276
Chris Lattnerf64b3522008-03-09 01:54:53 +00002277 // Lex the token after the identifier.
2278 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002279
Chris Lattnerf64b3522008-03-09 01:54:53 +00002280 switch (Tok.getKind()) {
2281 default: // #define X(A B
2282 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2283 return true;
2284 case tok::r_paren: // #define X(A)
Faisal Vali33df3912017-09-29 02:17:31 +00002285 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002286 return false;
2287 case tok::comma: // #define X(A,
2288 break;
2289 case tok::ellipsis: // #define X(A... -> GCC extension
2290 // Diagnose extension.
2291 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002292
Chris Lattnerf64b3522008-03-09 01:54:53 +00002293 // Lex the token after the identifier.
2294 LexUnexpandedToken(Tok);
2295 if (Tok.isNot(tok::r_paren)) {
2296 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2297 return true;
2298 }
Mike Stump11289f42009-09-09 15:08:12 +00002299
Chris Lattnerf64b3522008-03-09 01:54:53 +00002300 MI->setIsGNUVarargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002301 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002302 return false;
2303 }
2304 }
2305 }
2306}
2307
Serge Pavlov07c0f042014-12-18 11:14:21 +00002308static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2309 const LangOptions &LOptions) {
2310 if (MI->getNumTokens() == 1) {
2311 const Token &Value = MI->getReplacementToken(0);
2312
2313 // Macro that is identity, like '#define inline inline' is a valid pattern.
2314 if (MacroName.getKind() == Value.getKind())
2315 return true;
2316
2317 // Macro that maps a keyword to the same keyword decorated with leading/
2318 // trailing underscores is a valid pattern:
2319 // #define inline __inline
2320 // #define inline __inline__
2321 // #define inline _inline (in MS compatibility mode)
2322 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2323 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2324 if (!II->isKeyword(LOptions))
2325 return false;
2326 StringRef ValueText = II->getName();
2327 StringRef TrimmedValue = ValueText;
2328 if (!ValueText.startswith("__")) {
2329 if (ValueText.startswith("_"))
2330 TrimmedValue = TrimmedValue.drop_front(1);
2331 else
2332 return false;
2333 } else {
2334 TrimmedValue = TrimmedValue.drop_front(2);
2335 if (TrimmedValue.endswith("__"))
2336 TrimmedValue = TrimmedValue.drop_back(2);
2337 }
2338 return TrimmedValue.equals(MacroText);
2339 } else {
2340 return false;
2341 }
2342 }
2343
2344 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002345 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2346 tok::kw_const) &&
2347 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002348}
2349
Faisal Valiac506d72017-07-17 17:18:43 +00002350// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2351// entire line) of the macro's tokens and adds them to MacroInfo, and while
2352// doing so performs certain validity checks including (but not limited to):
2353// - # (stringization) is followed by a macro parameter
2354//
2355// Returns a nullptr if an invalid sequence of tokens is encountered or returns
2356// a pointer to a MacroInfo object.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002357
Faisal Valiac506d72017-07-17 17:18:43 +00002358MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2359 const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002360
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002361 Token LastTok = MacroNameTok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002362 // Create the new macro.
Faisal Valiac506d72017-07-17 17:18:43 +00002363 MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002364
Chris Lattnerf64b3522008-03-09 01:54:53 +00002365 Token Tok;
2366 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002367
Faisal Vali6bf67912017-07-25 03:15:36 +00002368 // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2369 // within their appropriate context.
2370 VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2371
Chris Lattnerf64b3522008-03-09 01:54:53 +00002372 // If this is a function-like macro definition, parse the argument list,
2373 // marking each of the identifiers as being used as macro arguments. Also,
2374 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002375 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002376 if (ImmediatelyAfterHeaderGuard) {
2377 // Save this macro information since it may part of a header guard.
2378 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2379 MacroNameTok.getLocation());
2380 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002381 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002382 } else if (Tok.hasLeadingSpace()) {
2383 // This is a normal token with leading space. Clear the leading space
2384 // marker on the first token to get proper expansion.
2385 Tok.clearFlag(Token::LeadingSpace);
2386 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002387 // This is a function-like macro definition. Read the argument list.
2388 MI->setIsFunctionLike();
Faisal Valiac506d72017-07-17 17:18:43 +00002389 if (ReadMacroParameterList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002390 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002391 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002392 DiscardUntilEndOfDirective();
Faisal Valiac506d72017-07-17 17:18:43 +00002393 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002394 }
2395
Faisal Vali6bf67912017-07-25 03:15:36 +00002396 // If this is a definition of an ISO C/C++ variadic function-like macro (not
2397 // using the GNU named varargs extension) inform our variadic scope guard
2398 // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2399 // allowed only within the definition of a variadic macro.
Mike Stump11289f42009-09-09 15:08:12 +00002400
Faisal Vali6bf67912017-07-25 03:15:36 +00002401 if (MI->isC99Varargs()) {
2402 VariadicMacroScopeGuard.enterScope();
2403 }
Mike Stump11289f42009-09-09 15:08:12 +00002404
Chris Lattnerf64b3522008-03-09 01:54:53 +00002405 // Read the first token after the arg list for down below.
2406 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002407 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002408 // C99 requires whitespace between the macro definition and the body. Emit
2409 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002410 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002411 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002412 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2413 // first character of a replacement list is not a character required by
2414 // subclause 5.2.1, then there shall be white-space separation between the
2415 // identifier and the replacement list.". 5.2.1 lists this set:
2416 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2417 // is irrelevant here.
2418 bool isInvalid = false;
2419 if (Tok.is(tok::at)) // @ is not in the list above.
2420 isInvalid = true;
2421 else if (Tok.is(tok::unknown)) {
2422 // If we have an unknown token, it is something strange like "`". Since
2423 // all of valid characters would have lexed into a single character
2424 // token of some sort, we know this is not a valid case.
2425 isInvalid = true;
2426 }
2427 if (isInvalid)
2428 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2429 else
2430 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002431 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002432
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002433 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002434 LastTok = Tok;
2435
Chris Lattnerf64b3522008-03-09 01:54:53 +00002436 // Read the rest of the macro body.
2437 if (MI->isObjectLike()) {
2438 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002439 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002440 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002441 MI->AddTokenToBody(Tok);
2442 // Get the next token of the macro.
2443 LexUnexpandedToken(Tok);
2444 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002445 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002446 // Otherwise, read the body of a function-like macro. While we are at it,
2447 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2448 // parameters in function-like macro expansions.
Faisal Vali18268422017-10-15 01:26:26 +00002449
2450 VAOptDefinitionContext VAOCtx(*this);
2451
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002452 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002453 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002454
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002455 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002456 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002457
Faisal Vali18268422017-10-15 01:26:26 +00002458 if (VAOCtx.isVAOptToken(Tok)) {
2459 // If we're already within a VAOPT, emit an error.
2460 if (VAOCtx.isInVAOpt()) {
2461 Diag(Tok, diag::err_pp_vaopt_nested_use);
2462 return nullptr;
2463 }
2464 // Ensure VAOPT is followed by a '(' .
2465 LexUnexpandedToken(Tok);
2466 if (Tok.isNot(tok::l_paren)) {
2467 Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
2468 return nullptr;
2469 }
2470 MI->AddTokenToBody(Tok);
2471 VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
2472 LexUnexpandedToken(Tok);
2473 if (Tok.is(tok::hashhash)) {
2474 Diag(Tok, diag::err_vaopt_paste_at_start);
2475 return nullptr;
2476 }
2477 continue;
2478 } else if (VAOCtx.isInVAOpt()) {
2479 if (Tok.is(tok::r_paren)) {
2480 if (VAOCtx.sawClosingParen()) {
2481 const unsigned NumTokens = MI->getNumTokens();
2482 assert(NumTokens >= 3 && "Must have seen at least __VA_OPT__( "
2483 "and a subsequent tok::r_paren");
2484 if (MI->getReplacementToken(NumTokens - 2).is(tok::hashhash)) {
2485 Diag(Tok, diag::err_vaopt_paste_at_end);
2486 return nullptr;
2487 }
2488 }
2489 } else if (Tok.is(tok::l_paren)) {
2490 VAOCtx.sawOpeningParen(Tok.getLocation());
2491 }
2492 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002493 // Get the next token of the macro.
2494 LexUnexpandedToken(Tok);
2495 continue;
2496 }
Mike Stump11289f42009-09-09 15:08:12 +00002497
Richard Smith701a3522013-07-09 01:00:29 +00002498 // If we're in -traditional mode, then we should ignore stringification
2499 // and token pasting. Mark the tokens as unknown so as not to confuse
2500 // things.
2501 if (getLangOpts().TraditionalCPP) {
2502 Tok.setKind(tok::unknown);
2503 MI->AddTokenToBody(Tok);
2504
2505 // Get the next token of the macro.
2506 LexUnexpandedToken(Tok);
2507 continue;
2508 }
2509
Eli Friedman14d3c792012-11-14 02:18:46 +00002510 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002511 // If we see token pasting, check if it looks like the gcc comma
2512 // pasting extension. We'll use this information to suppress
2513 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002514
Eli Friedman14d3c792012-11-14 02:18:46 +00002515 // Get the next token of the macro.
2516 LexUnexpandedToken(Tok);
2517
2518 if (Tok.is(tok::eod)) {
2519 MI->AddTokenToBody(LastTok);
2520 break;
2521 }
2522
2523 unsigned NumTokens = MI->getNumTokens();
2524 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2525 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2526 MI->setHasCommaPasting();
2527
David Majnemer76faf1f2013-11-05 09:30:17 +00002528 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002529 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002530 continue;
2531 }
2532
Faisal Vali18268422017-10-15 01:26:26 +00002533 // Our Token is a stringization operator.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002534 // Get the next token of the macro.
2535 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002536
Faisal Vali18268422017-10-15 01:26:26 +00002537 // Check for a valid macro arg identifier or __VA_OPT__.
2538 if (!VAOCtx.isVAOptToken(Tok) &&
2539 (Tok.getIdentifierInfo() == nullptr ||
2540 MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002541
2542 // If this is assembler-with-cpp mode, we accept random gibberish after
2543 // the '#' because '#' is often a comment character. However, change
2544 // the kind of the token to tok::unknown so that the preprocessor isn't
2545 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002546 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002547 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002548 MI->AddTokenToBody(LastTok);
2549 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002550 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002551 Diag(Tok, diag::err_pp_stringize_not_parameter)
2552 << LastTok.is(tok::hashat);
Faisal Valiac506d72017-07-17 17:18:43 +00002553 return nullptr;
Chris Lattner83bd8282009-05-25 17:16:10 +00002554 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002555 }
Mike Stump11289f42009-09-09 15:08:12 +00002556
Chris Lattner83bd8282009-05-25 17:16:10 +00002557 // Things look ok, add the '#' and param name tokens to the macro.
2558 MI->AddTokenToBody(LastTok);
Mike Stump11289f42009-09-09 15:08:12 +00002559
Faisal Vali18268422017-10-15 01:26:26 +00002560 // If the token following '#' is VAOPT, let the next iteration handle it
2561 // and check it for correctness, otherwise add the token and prime the
2562 // loop with the next one.
2563 if (!VAOCtx.isVAOptToken(Tok)) {
2564 MI->AddTokenToBody(Tok);
2565 LastTok = Tok;
2566
2567 // Get the next token of the macro.
2568 LexUnexpandedToken(Tok);
2569 }
2570 }
2571 if (VAOCtx.isInVAOpt()) {
2572 assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
2573 Diag(Tok, diag::err_pp_expected_after)
2574 << LastTok.getKind() << tok::r_paren;
2575 Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
2576 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002577 }
2578 }
Faisal Valiac506d72017-07-17 17:18:43 +00002579 MI->setDefinitionEndLoc(LastTok.getLocation());
Faisal Valiac506d72017-07-17 17:18:43 +00002580 return MI;
2581}
2582/// HandleDefineDirective - Implements \#define. This consumes the entire macro
2583/// line then lets the caller lex the next real token.
2584void Preprocessor::HandleDefineDirective(
2585 Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2586 ++NumDefined;
2587
2588 Token MacroNameTok;
2589 bool MacroShadowsKeyword;
2590 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2591
2592 // Error reading macro name? If so, diagnostic already issued.
2593 if (MacroNameTok.is(tok::eod))
2594 return;
2595
2596 // If we are supposed to keep comments in #defines, reenable comment saving
2597 // mode.
2598 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2599
2600 MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2601 MacroNameTok, ImmediatelyAfterHeaderGuard);
Fangrui Song6907ce22018-07-30 19:24:48 +00002602
Faisal Valiac506d72017-07-17 17:18:43 +00002603 if (!MI) return;
Mike Stump11289f42009-09-09 15:08:12 +00002604
Serge Pavlov07c0f042014-12-18 11:14:21 +00002605 if (MacroShadowsKeyword &&
2606 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2607 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
Fangrui Song6907ce22018-07-30 19:24:48 +00002608 }
Chris Lattner57540c52011-04-15 05:22:18 +00002609 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002610 // replacement list.
2611 unsigned NumTokens = MI->getNumTokens();
2612 if (NumTokens != 0) {
2613 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2614 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002615 return;
2616 }
2617 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2618 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002619 return;
2620 }
2621 }
Mike Stump11289f42009-09-09 15:08:12 +00002622
Erich Keane76675de2018-07-05 17:22:13 +00002623 // When skipping just warn about macros that do not match.
2624 if (SkippingUntilPCHThroughHeader) {
2625 const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
2626 if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
2627 /*Syntactic=*/LangOpts.MicrosoftExt))
2628 Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
2629 << MacroNameTok.getIdentifierInfo();
2630 return;
2631 }
Mike Stump11289f42009-09-09 15:08:12 +00002632
Chris Lattnerf64b3522008-03-09 01:54:53 +00002633 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002634 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002635 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002636 // In Objective-C, ignore attempts to directly redefine the builtin
2637 // definitions of the ownership qualifiers. It's still possible to
2638 // #undef them.
2639 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2640 return II->isStr("__strong") ||
2641 II->isStr("__weak") ||
2642 II->isStr("__unsafe_unretained") ||
2643 II->isStr("__autoreleasing");
2644 };
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002645 if (getLangOpts().ObjC &&
John McCall83760372015-12-10 23:31:01 +00002646 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2647 == getPredefinesFileID() &&
2648 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2649 // Warn if it changes the tokens.
2650 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2651 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2652 !MI->isIdenticalTo(*OtherMI, *this,
2653 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2654 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2655 }
2656 assert(!OtherMI->isWarnIfUnused());
2657 return;
2658 }
2659
Chris Lattner5244f342009-01-16 19:50:11 +00002660 // It is very common for system headers to have tons of macro redefinitions
2661 // and for warnings to be disabled in system headers. If this is the case,
2662 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002663 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002664 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002665 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002666 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002667
Taewook Oh755e4d22016-06-13 21:55:33 +00002668 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002669 // C++ [cpp.predefined]p4, but allow it as an extension.
2670 if (OtherMI->isBuiltinMacro())
2671 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002672 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002673 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002674 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002675 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002676 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2677 << MacroNameTok.getIdentifierInfo();
2678 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2679 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002680 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002681 if (OtherMI->isWarnIfUnused())
2682 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002683 }
Mike Stump11289f42009-09-09 15:08:12 +00002684
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002685 DefMacroDirective *MD =
2686 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002687
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002688 assert(!MI->isUsed());
2689 // If we need warning for not using the macro, add its location in the
2690 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002691 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002692 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002693 MI->setIsWarnIfUnused(true);
2694 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2695 }
2696
Chris Lattner928e9092009-04-12 01:39:54 +00002697 // If the callbacks want to know, tell them about the macro definition.
2698 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002699 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002700}
2701
James Dennettf6333ac2012-06-22 05:46:07 +00002702/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002703///
Erik Verbruggen4bddef92016-10-26 08:52:41 +00002704void Preprocessor::HandleUndefDirective() {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002705 ++NumUndefined;
2706
2707 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002708 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002709
Chris Lattnerf64b3522008-03-09 01:54:53 +00002710 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002711 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002712 return;
Mike Stump11289f42009-09-09 15:08:12 +00002713
Chris Lattnerf64b3522008-03-09 01:54:53 +00002714 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002715 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002716
Richard Smith20e883e2015-04-29 23:20:19 +00002717 // Okay, we have a valid identifier to undef.
2718 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002719 auto MD = getMacroDefinition(II);
Vedant Kumar349a6242017-04-26 21:05:44 +00002720 UndefMacroDirective *Undef = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00002721
Vedant Kumar349a6242017-04-26 21:05:44 +00002722 // If the macro is not defined, this is a noop undef.
2723 if (const MacroInfo *MI = MD.getMacroInfo()) {
2724 if (!MI->isUsed() && MI->isWarnIfUnused())
2725 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2726
2727 if (MI->isWarnIfUnused())
2728 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2729
2730 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
2731 }
Mike Stump11289f42009-09-09 15:08:12 +00002732
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002733 // If the callbacks want to know, tell them about the macro #undef.
2734 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002735 if (Callbacks)
Vedant Kumar349a6242017-04-26 21:05:44 +00002736 Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002737
Vedant Kumar349a6242017-04-26 21:05:44 +00002738 if (Undef)
2739 appendMacroDirective(II, Undef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002740}
2741
Chris Lattnerf64b3522008-03-09 01:54:53 +00002742//===----------------------------------------------------------------------===//
2743// Preprocessor Conditional Directive Handling.
2744//===----------------------------------------------------------------------===//
2745
James Dennettf6333ac2012-06-22 05:46:07 +00002746/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2747/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2748/// true if any tokens have been returned or pp-directives activated before this
2749/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002750///
Vedant Kumar3919a502017-09-11 20:47:42 +00002751void Preprocessor::HandleIfdefDirective(Token &Result,
2752 const Token &HashToken,
2753 bool isIfndef,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002754 bool ReadAnyTokensBeforeDirective) {
2755 ++NumIf;
2756 Token DirectiveTok = Result;
2757
2758 Token MacroNameTok;
2759 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002760
Chris Lattnerf64b3522008-03-09 01:54:53 +00002761 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002762 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002763 // Skip code until we get to #endif. This helps with recovery by not
2764 // emitting an error when the #endif is reached.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002765 SkipExcludedConditionalBlock(HashToken.getLocation(),
2766 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002767 /*Foundnonskip*/ false, /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002768 return;
2769 }
Mike Stump11289f42009-09-09 15:08:12 +00002770
Chris Lattnerf64b3522008-03-09 01:54:53 +00002771 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002772 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002773
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002774 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002775 auto MD = getMacroDefinition(MII);
2776 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002777
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002778 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002779 // If the start of a top-level #ifdef and if the macro is not defined,
2780 // inform MIOpt that this might be the start of a proper include guard.
2781 // Otherwise it is some other form of unknown conditional which we can't
2782 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002783 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002784 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002785 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002786 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002787 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002788 }
2789
Chris Lattnerf64b3522008-03-09 01:54:53 +00002790 // If there is a macro, process it.
2791 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002792 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002793
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002794 if (Callbacks) {
2795 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002796 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002797 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002798 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002799 }
2800
Chris Lattnerf64b3522008-03-09 01:54:53 +00002801 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002802 if (PPOpts->SingleFileParseMode && !MI) {
2803 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2804 // the directive blocks.
2805 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002806 /*wasskip*/false, /*foundnonskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002807 /*foundelse*/false);
2808 } else if (!MI == isIfndef) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002809 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002810 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2811 /*wasskip*/false, /*foundnonskip*/true,
2812 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002813 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002814 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002815 SkipExcludedConditionalBlock(HashToken.getLocation(),
2816 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002817 /*Foundnonskip*/ false,
2818 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002819 }
2820}
2821
James Dennettf6333ac2012-06-22 05:46:07 +00002822/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002823///
2824void Preprocessor::HandleIfDirective(Token &IfToken,
Vedant Kumar3919a502017-09-11 20:47:42 +00002825 const Token &HashToken,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002826 bool ReadAnyTokensBeforeDirective) {
2827 ++NumIf;
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002828
2829 // Parse and evaluate the conditional expression.
2830 IdentifierInfo *IfNDefMacro = nullptr;
2831 const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
2832 const bool ConditionalTrue = DER.Conditional;
2833
2834 // If this condition is equivalent to #ifndef X, and if this is the first
2835 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002836 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002837 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002838 // FIXME: Pass in the location of the macro name, not the 'if' token.
2839 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002840 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002841 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002842 }
2843
2844 if (Callbacks)
2845 Callbacks->If(
2846 IfToken.getLocation(), DER.ExprRange,
2847 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
2848
2849 // Should we include the stuff contained by this directive?
2850 if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002851 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2852 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002853 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002854 /*foundnonskip*/false, /*foundelse*/false);
2855 } else if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002856 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002857 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002858 /*foundnonskip*/true, /*foundelse*/false);
2859 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002860 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002861 SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002862 /*Foundnonskip*/ false,
2863 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002864 }
2865}
2866
James Dennettf6333ac2012-06-22 05:46:07 +00002867/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002868///
2869void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2870 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002871
Chris Lattnerf64b3522008-03-09 01:54:53 +00002872 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002873 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002874
Chris Lattnerf64b3522008-03-09 01:54:53 +00002875 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002876 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002877 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002878 Diag(EndifToken, diag::err_pp_endif_without_if);
2879 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002880 }
Mike Stump11289f42009-09-09 15:08:12 +00002881
Chris Lattnerf64b3522008-03-09 01:54:53 +00002882 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002883 if (CurPPLexer->getConditionalStackDepth() == 0)
2884 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002885
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002886 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002887 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002888
2889 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002890 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002891}
2892
James Dennettf6333ac2012-06-22 05:46:07 +00002893/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002894///
Vedant Kumar3919a502017-09-11 20:47:42 +00002895void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002896 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002897
Chris Lattnerf64b3522008-03-09 01:54:53 +00002898 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002899 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002900
Chris Lattnerf64b3522008-03-09 01:54:53 +00002901 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002902 if (CurPPLexer->popConditionalLevel(CI)) {
2903 Diag(Result, diag::pp_err_else_without_if);
2904 return;
2905 }
Mike Stump11289f42009-09-09 15:08:12 +00002906
Chris Lattnerf64b3522008-03-09 01:54:53 +00002907 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002908 if (CurPPLexer->getConditionalStackDepth() == 0)
2909 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002910
2911 // If this is a #else with a #else before it, report the error.
2912 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002913
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002914 if (Callbacks)
2915 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2916
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002917 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002918 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2919 // the directive blocks.
2920 CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002921 /*foundnonskip*/false, /*foundelse*/true);
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002922 return;
2923 }
2924
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002925 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002926 SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
2927 /*Foundnonskip*/ true,
Vedant Kumar3919a502017-09-11 20:47:42 +00002928 /*FoundElse*/ true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002929}
2930
James Dennettf6333ac2012-06-22 05:46:07 +00002931/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002932///
Vedant Kumar3919a502017-09-11 20:47:42 +00002933void Preprocessor::HandleElifDirective(Token &ElifToken,
2934 const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002935 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002936
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002937 // #elif directive in a non-skipping conditional... start skipping.
2938 // We don't care what the condition is, because we will always skip it (since
2939 // the block immediately before it was included).
2940 SourceRange ConditionRange = DiscardUntilEndOfDirective();
2941
2942 PPConditionalInfo CI;
2943 if (CurPPLexer->popConditionalLevel(CI)) {
Chris Lattner907dfe92008-11-18 07:59:24 +00002944 Diag(ElifToken, diag::pp_err_elif_without_if);
2945 return;
2946 }
Mike Stump11289f42009-09-09 15:08:12 +00002947
Chris Lattnerf64b3522008-03-09 01:54:53 +00002948 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002949 if (CurPPLexer->getConditionalStackDepth() == 0)
2950 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002951
Chris Lattnerf64b3522008-03-09 01:54:53 +00002952 // If this is a #elif with a #else before it, report the error.
Chandler Carruthd92d70b2019-01-19 06:36:00 +00002953 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2954
2955 if (Callbacks)
2956 Callbacks->Elif(ElifToken.getLocation(), ConditionRange,
2957 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
2958
2959 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002960 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2961 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002962 CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002963 /*foundnonskip*/false, /*foundelse*/false);
2964 return;
2965 }
2966
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002967 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002968 SkipExcludedConditionalBlock(
2969 HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
2970 /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002971}