blob: 4ea0f485d31d5782cbf19bf6392e731216f866d6 [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00009///
10/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011/// Implements # directive processing for the Preprocessor.
James Dennettf6333ac2012-06-22 05:46:07 +000012///
Chris Lattnerf64b3522008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000015#include "clang/Basic/CharInfo.h"
Chris Lattner710bb872009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/Basic/IdentifierTable.h"
18#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/Module.h"
20#include "clang/Basic/SourceLocation.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000021#include "clang/Basic/SourceManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000022#include "clang/Basic/TokenKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Lex/CodeCompletionHandler.h"
24#include "clang/Lex/HeaderSearch.h"
25#include "clang/Lex/LexDiagnostic.h"
26#include "clang/Lex/LiteralSupport.h"
27#include "clang/Lex/MacroInfo.h"
28#include "clang/Lex/ModuleLoader.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000029#include "clang/Lex/ModuleMap.h"
30#include "clang/Lex/PPCallbacks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Lex/Pragma.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000032#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +000033#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000034#include "clang/Lex/PTHLexer.h"
35#include "clang/Lex/Token.h"
Faisal Vali6bf67912017-07-25 03:15:36 +000036#include "clang/Lex/VariadicMacroSupport.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000037#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/SmallString.h"
39#include "llvm/ADT/SmallVector.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000040#include "llvm/ADT/STLExtras.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000041#include "llvm/ADT/StringSwitch.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000042#include "llvm/ADT/StringRef.h"
43#include "llvm/Support/AlignOf.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000044#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaf6002232014-08-08 21:31:04 +000045#include "llvm/Support/Path.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include <algorithm>
47#include <cassert>
48#include <cstring>
49#include <new>
50#include <string>
51#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000052
Chris Lattnerf64b3522008-03-09 01:54:53 +000053using namespace clang;
54
55//===----------------------------------------------------------------------===//
56// Utility Methods for Preprocessor Directive Handling.
57//===----------------------------------------------------------------------===//
58
Richard Smith3f6dd7a2017-05-12 23:40:52 +000059MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
60 auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead};
Ted Kremenekc8456f82010-10-19 22:15:20 +000061 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000062 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000063}
64
Richard Smith50474bf2015-04-23 23:29:05 +000065DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
66 SourceLocation Loc) {
Richard Smith713369b2015-04-23 20:40:50 +000067 return new (BP) DefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000068}
69
70UndefMacroDirective *
Richard Smith50474bf2015-04-23 23:29:05 +000071Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
Richard Smith713369b2015-04-23 20:40:50 +000072 return new (BP) UndefMacroDirective(UndefLoc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000073}
74
75VisibilityMacroDirective *
76Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
77 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000078 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000079}
80
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000081/// Read and discard all tokens remaining on the current line until
Vedant Kumar403822d2017-09-16 06:26:51 +000082/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000083void Preprocessor::DiscardUntilEndOfDirective() {
84 Token Tmp;
85 do {
86 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000087 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000088 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000089}
90
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000091/// Enumerates possible cases of #define/#undef a reserved identifier.
Serge Pavlov07c0f042014-12-18 11:14:21 +000092enum MacroDiag {
93 MD_NoWarn, //> Not a reserved identifier
94 MD_KeywordDef, //> Macro hides keyword, enabled by default
95 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
96};
97
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000098/// Checks if the specified identifier is reserved in the specified
Serge Pavlov07c0f042014-12-18 11:14:21 +000099/// language.
100/// This function does not check if the identifier is a keyword.
101static bool isReservedId(StringRef Text, const LangOptions &Lang) {
102 // C++ [macro.names], C11 7.1.3:
103 // All identifiers that begin with an underscore and either an uppercase
104 // letter or another underscore are always reserved for any use.
105 if (Text.size() >= 2 && Text[0] == '_' &&
106 (isUppercase(Text[1]) || Text[1] == '_'))
107 return true;
108 // C++ [global.names]
109 // Each name that contains a double underscore ... is reserved to the
110 // implementation for any use.
111 if (Lang.CPlusPlus) {
112 if (Text.find("__") != StringRef::npos)
113 return true;
114 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000115 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000116}
117
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +0000118// The -fmodule-name option tells the compiler to textually include headers in
119// the specified module, meaning clang won't build the specified module. This is
120// useful in a number of situations, for instance, when building a library that
121// vends a module map, one might want to avoid hitting intermediate build
122// products containig the the module map or avoid finding the system installed
123// modulemap for that library.
124static bool isForModuleBuilding(Module *M, StringRef CurrentModule,
125 StringRef ModuleName) {
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +0000126 StringRef TopLevelName = M->getTopLevelModuleName();
127
128 // When building framework Foo, we wanna make sure that Foo *and* Foo_Private
129 // are textually included and no modules are built for both.
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +0000130 if (M->getTopLevelModule()->IsFramework && CurrentModule == ModuleName &&
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +0000131 !CurrentModule.endswith("_Private") && TopLevelName.endswith("_Private"))
132 TopLevelName = TopLevelName.drop_back(8);
133
134 return TopLevelName == CurrentModule;
135}
136
Serge Pavlov07c0f042014-12-18 11:14:21 +0000137static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
138 const LangOptions &Lang = PP.getLangOpts();
139 StringRef Text = II->getName();
140 if (isReservedId(Text, Lang))
141 return MD_ReservedMacro;
142 if (II->isKeyword(Lang))
143 return MD_KeywordDef;
144 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
145 return MD_KeywordDef;
146 return MD_NoWarn;
147}
148
149static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
150 const LangOptions &Lang = PP.getLangOpts();
151 StringRef Text = II->getName();
152 // Do not warn on keyword undef. It is generally harmless and widely used.
153 if (isReservedId(Text, Lang))
154 return MD_ReservedMacro;
155 return MD_NoWarn;
156}
157
Taewook Ohf42103c2016-06-13 20:40:21 +0000158// Return true if we want to issue a diagnostic by default if we
159// encounter this name in a #include with the wrong case. For now,
160// this includes the standard C and C++ headers, Posix headers,
161// and Boost headers. Improper case for these #includes is a
162// potential portability issue.
163static bool warnByDefaultOnWrongCase(StringRef Include) {
164 // If the first component of the path is "boost", treat this like a standard header
165 // for the purposes of diagnostics.
166 if (::llvm::sys::path::begin(Include)->equals_lower("boost"))
167 return true;
168
169 // "condition_variable" is the longest standard header name at 18 characters.
170 // If the include file name is longer than that, it can't be a standard header.
Taewook Oh755e4d22016-06-13 21:55:33 +0000171 static const size_t MaxStdHeaderNameLen = 18u;
Taewook Ohf42103c2016-06-13 20:40:21 +0000172 if (Include.size() > MaxStdHeaderNameLen)
173 return false;
174
175 // Lowercase and normalize the search string.
176 SmallString<32> LowerInclude{Include};
177 for (char &Ch : LowerInclude) {
178 // In the ASCII range?
George Burgess IV5d3bd932016-06-16 02:30:33 +0000179 if (static_cast<unsigned char>(Ch) > 0x7f)
Taewook Ohf42103c2016-06-13 20:40:21 +0000180 return false; // Can't be a standard header
181 // ASCII lowercase:
182 if (Ch >= 'A' && Ch <= 'Z')
183 Ch += 'a' - 'A';
184 // Normalize path separators for comparison purposes.
185 else if (::llvm::sys::path::is_separator(Ch))
186 Ch = '/';
187 }
188
189 // The standard C/C++ and Posix headers
190 return llvm::StringSwitch<bool>(LowerInclude)
191 // C library headers
192 .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
193 .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
194 .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
195 .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
196 .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
197 .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
198
199 // C++ headers for C library facilities
200 .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
201 .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
202 .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
203 .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
204 .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
205 .Case("cwctype", true)
206
207 // C++ library headers
208 .Cases("algorithm", "fstream", "list", "regex", "thread", true)
209 .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
210 .Cases("atomic", "future", "map", "set", "type_traits", true)
211 .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
212 .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
213 .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
214 .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
215 .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
216 .Cases("deque", "istream", "queue", "string", "valarray", true)
217 .Cases("exception", "iterator", "random", "strstream", "vector", true)
218 .Cases("forward_list", "limits", "ratio", "system_error", true)
219
220 // POSIX headers (which aren't also C headers)
221 .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
222 .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
223 .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
224 .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
225 .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
226 .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
227 .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
228 .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
229 .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
230 .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
231 .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
232 .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
233 .Default(false);
234}
235
Serge Pavlov07c0f042014-12-18 11:14:21 +0000236bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
237 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000238 // Missing macro name?
239 if (MacroNameTok.is(tok::eod))
240 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
241
242 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Olivier Goffart90f981b2017-07-14 09:23:40 +0000243 if (!II)
244 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000245
Olivier Goffart90f981b2017-07-14 09:23:40 +0000246 if (II->isCPlusPlusOperatorKeyword()) {
Alp Tokere03e9e12014-05-31 16:32:22 +0000247 // C++ 2.5p2: Alternative tokens behave the same as its primary token
248 // except for their spellings.
249 Diag(MacroNameTok, getLangOpts().MicrosoftExt
250 ? diag::ext_pp_operator_used_as_macro_name
251 : diag::err_pp_operator_used_as_macro_name)
252 << II << MacroNameTok.getKind();
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000253 // Allow #defining |and| and friends for Microsoft compatibility or
254 // recovery when legacy C headers are included in C++.
Alp Tokerb05e0b52014-05-21 06:13:51 +0000255 }
256
Serge Pavlovd024f522014-10-24 17:31:32 +0000257 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000258 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
259 return Diag(MacroNameTok, diag::err_defined_macro_name);
260 }
261
Richard Smith20e883e2015-04-29 23:20:19 +0000262 if (isDefineUndef == MU_Undef) {
263 auto *MI = getMacroInfo(II);
264 if (MI && MI->isBuiltinMacro()) {
265 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
266 // and C++ [cpp.predefined]p4], but allow it as an extension.
267 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
268 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000269 }
270
Serge Pavlov07c0f042014-12-18 11:14:21 +0000271 // If defining/undefining reserved identifier or a keyword, we need to issue
272 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000273 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000274 if (ShadowFlag)
275 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000276 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
Mehdi Amini99d1b292016-10-01 16:38:28 +0000277 (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000278 MacroDiag D = MD_NoWarn;
279 if (isDefineUndef == MU_Define) {
280 D = shouldWarnOnMacroDef(*this, II);
281 }
282 else if (isDefineUndef == MU_Undef)
283 D = shouldWarnOnMacroUndef(*this, II);
284 if (D == MD_KeywordDef) {
285 // We do not want to warn on some patterns widely used in configuration
286 // scripts. This requires analyzing next tokens, so do not issue warnings
287 // now, only inform caller.
288 if (ShadowFlag)
289 *ShadowFlag = true;
290 }
291 if (D == MD_ReservedMacro)
292 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000293 }
294
Alp Tokerb05e0b52014-05-21 06:13:51 +0000295 // Okay, we got a good identifier.
296 return false;
297}
298
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000299/// Lex and validate a macro name, which occurs after a
James Dennettf6333ac2012-06-22 05:46:07 +0000300/// \#define or \#undef.
301///
Serge Pavlovd024f522014-10-24 17:31:32 +0000302/// This sets the token kind to eod and discards the rest of the macro line if
303/// the macro name is invalid.
304///
305/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000306/// \param isDefineUndef Context in which macro is used.
307/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
308void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
309 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000310 // Read the token, don't allow macro expansion on it.
311 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000312
Douglas Gregor12785102010-08-24 20:21:13 +0000313 if (MacroNameTok.is(tok::code_completion)) {
314 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000315 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000316 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000317 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000318 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000319
Serge Pavlov07c0f042014-12-18 11:14:21 +0000320 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000321 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000322
323 // Invalid macro name, read and discard the rest of the line and set the
324 // token kind to tok::eod if necessary.
325 if (MacroNameTok.isNot(tok::eod)) {
326 MacroNameTok.setKind(tok::eod);
327 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000328 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329}
330
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000331/// Ensure that the next token is a tok::eod token.
James Dennettf6333ac2012-06-22 05:46:07 +0000332///
333/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000334/// true, then we consider macros that expand to zero tokens as being ok.
335void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000336 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000337 // Lex unexpanded tokens for most directives: macros might expand to zero
338 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
339 // #line) allow empty macros.
340 if (EnableMacros)
341 Lex(Tmp);
342 else
343 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000344
Chris Lattnerf64b3522008-03-09 01:54:53 +0000345 // There should be no tokens after the directive, but we allow them as an
346 // extension.
347 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
348 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000349
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000350 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000351 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000352 // or if this is a macro-style preprocessing directive, because it is more
353 // trouble than it is worth to insert /**/ and check that there is no /**/
354 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000355 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000356 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000357 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000358 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
359 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000360 DiscardUntilEndOfDirective();
361 }
362}
363
James Dennettf6333ac2012-06-22 05:46:07 +0000364/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
365/// decided that the subsequent tokens are in the \#if'd out portion of the
366/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000367/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000368/// this \#if directive, so \#else/\#elif blocks should never be entered.
369/// If ElseOk is true, then \#else directives are ok, if not, then we have
370/// already seen one so a \#else directive is a duplicate. When this returns,
371/// the caller can lex the first valid token.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000372void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
Vedant Kumar3919a502017-09-11 20:47:42 +0000373 SourceLocation IfTokenLoc,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000374 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000375 bool FoundElse,
376 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000377 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000378 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000379
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000380 if (PreambleConditionalStack.reachedEOFWhileSkipping())
381 PreambleConditionalStack.clearSkipInfo();
382 else
383 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
384 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000385
Ted Kremenek56572ab2008-12-12 18:34:08 +0000386 if (CurPTHLexer) {
387 PTHSkipExcludedConditionalBlock();
388 return;
389 }
Mike Stump11289f42009-09-09 15:08:12 +0000390
Chris Lattnerf64b3522008-03-09 01:54:53 +0000391 // Enter raw mode to disable identifier lookup (and thus macro expansion),
392 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000393 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000394 Token Tok;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000395 while (true) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000396 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000397
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000398 if (Tok.is(tok::code_completion)) {
399 if (CodeComplete)
400 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000401 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000402 continue;
403 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000404
Chris Lattnerf64b3522008-03-09 01:54:53 +0000405 // If this is the end of the buffer, we have an error.
406 if (Tok.is(tok::eof)) {
Ilya Biryukov8f738ac2017-09-12 08:35:57 +0000407 // We don't emit errors for unterminated conditionals here,
408 // Lexer::LexEndOfFile can do that propertly.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000409 // Just return and let the caller lex after this #include.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000410 if (PreambleConditionalStack.isRecording())
411 PreambleConditionalStack.SkipInfo.emplace(
412 HashTokenLoc, IfTokenLoc, FoundNonSkipPortion, FoundElse, ElseLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000413 break;
414 }
Mike Stump11289f42009-09-09 15:08:12 +0000415
Chris Lattnerf64b3522008-03-09 01:54:53 +0000416 // If this token is not a preprocessor directive, just skip it.
417 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
418 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattnerf64b3522008-03-09 01:54:53 +0000420 // We just parsed a # character at the start of a line, so we're in
421 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000422 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000423 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000424 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000425
Mike Stump11289f42009-09-09 15:08:12 +0000426
Chris Lattnerf64b3522008-03-09 01:54:53 +0000427 // Read the next token, the directive flavor.
428 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattnerf64b3522008-03-09 01:54:53 +0000430 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
431 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000432 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000433 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000434 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000435 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000436 continue;
437 }
438
439 // If the first letter isn't i or e, it isn't intesting to us. We know that
440 // this is safe in the face of spelling differences, because there is no way
441 // to spell an i/e in a strange way that is another letter. Skipping this
442 // allows us to avoid looking up the identifier info for #define/#undef and
443 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000444 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000445
Alp Toker2d57cea2014-05-17 04:53:25 +0000446 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000447 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000448 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000449 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000450 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000451 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000452 continue;
453 }
Mike Stump11289f42009-09-09 15:08:12 +0000454
Chris Lattnerf64b3522008-03-09 01:54:53 +0000455 // Get the identifier name without trigraphs or embedded newlines. Note
456 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
457 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000458 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000459 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000460 if (!Tok.needsCleaning() && RI.size() < 20) {
461 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000462 } else {
463 std::string DirectiveStr = getSpelling(Tok);
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000464 size_t IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000465 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000466 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000467 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000468 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000469 continue;
470 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000471 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000472 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000473 }
Mike Stump11289f42009-09-09 15:08:12 +0000474
Benjamin Kramer144884642009-12-31 13:32:38 +0000475 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000476 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000477 if (Sub.empty() || // "if"
478 Sub == "def" || // "ifdef"
479 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000480 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
481 // bother parsing the condition.
482 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000483 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000484 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000485 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000486 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000487 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000489 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000490 PPConditionalInfo CondInfo;
491 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000492 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000493 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000494 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattnerf64b3522008-03-09 01:54:53 +0000496 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000497 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000498 // Restore the value of LexingRawMode so that trailing comments
499 // are handled correctly, if we've reached the outermost block.
500 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000501 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000502 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000503 if (Callbacks)
504 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000505 break;
Richard Smithd0124572012-06-21 00:35:03 +0000506 } else {
507 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000508 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000509 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000510 // #else directive in a skipping conditional. If not in some other
511 // skipping conditional, and if #else hasn't already been seen, enter it
512 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000513 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000514
Chris Lattnerf64b3522008-03-09 01:54:53 +0000515 // If this is a #else with a #else before it, report the error.
516 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000517
Chris Lattnerf64b3522008-03-09 01:54:53 +0000518 // Note that we've seen a #else in this conditional.
519 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattnerf64b3522008-03-09 01:54:53 +0000521 // If the conditional is at the top level, and the #if block wasn't
522 // entered, enter the #else block now.
523 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
524 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000525 // Restore the value of LexingRawMode so that trailing comments
526 // are handled correctly.
527 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000528 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000529 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000530 if (Callbacks)
531 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000532 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000533 } else {
534 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000535 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000536 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000537 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000538
John Thompson17c35732013-12-04 20:19:30 +0000539 // If this is a #elif with a #else before it, report the error.
540 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
541
Chris Lattnerf64b3522008-03-09 01:54:53 +0000542 // If this is in a skipping block or if we're already handled this #if
543 // block, don't bother parsing the condition.
544 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
545 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000546 } else {
John Thompson17c35732013-12-04 20:19:30 +0000547 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000548 // Restore the value of LexingRawMode so that identifiers are
549 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000550 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
551 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000552 IdentifierInfo *IfNDefMacro = nullptr;
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +0000553 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro).Conditional;
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000554 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000555 if (Callbacks) {
556 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000557 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000558 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000559 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000560 }
561 // If this condition is true, enter it!
562 if (CondValue) {
563 CondInfo.FoundNonSkip = true;
564 break;
565 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000566 }
567 }
568 }
Mike Stump11289f42009-09-09 15:08:12 +0000569
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000570 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000571 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000572 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000573 }
574
575 // Finally, if we are out of the conditional (saw an #endif or ran off the end
576 // of the file, just stop skipping and return to lexing whatever came after
577 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000578 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000579
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000580 // The last skipped range isn't actually skipped yet if it's truncated
581 // by the end of the preamble; we'll resume parsing after the preamble.
582 if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
Vedant Kumar3919a502017-09-11 20:47:42 +0000583 Callbacks->SourceRangeSkipped(
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000584 SourceRange(HashTokenLoc, CurPPLexer->getSourceLocation()),
Vedant Kumar3919a502017-09-11 20:47:42 +0000585 Tok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000586}
587
Ted Kremenek56572ab2008-12-12 18:34:08 +0000588void Preprocessor::PTHSkipExcludedConditionalBlock() {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000589 while (true) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000590 assert(CurPTHLexer);
591 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000592
Ted Kremenek56572ab2008-12-12 18:34:08 +0000593 // Skip to the next '#else', '#elif', or #endif.
594 if (CurPTHLexer->SkipBlock()) {
595 // We have reached an #endif. Both the '#' and 'endif' tokens
596 // have been consumed by the PTHLexer. Just pop off the condition level.
597 PPConditionalInfo CondInfo;
598 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000599 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000600 assert(!InCond && "Can't be skipping if not in a conditional!");
601 break;
602 }
Mike Stump11289f42009-09-09 15:08:12 +0000603
Ted Kremenek56572ab2008-12-12 18:34:08 +0000604 // We have reached a '#else' or '#elif'. Lex the next token to get
605 // the directive flavor.
606 Token Tok;
607 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000608
Ted Kremenek56572ab2008-12-12 18:34:08 +0000609 // We can actually look up the IdentifierInfo here since we aren't in
610 // raw mode.
611 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
612
613 if (K == tok::pp_else) {
614 // #else: Enter the else condition. We aren't in a nested condition
615 // since we skip those. We're always in the one matching the last
616 // blocked we skipped.
617 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
618 // Note that we've seen a #else in this conditional.
619 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000620
Ted Kremenek56572ab2008-12-12 18:34:08 +0000621 // If the #if block wasn't entered then enter the #else block now.
622 if (!CondInfo.FoundNonSkip) {
623 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000624
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000625 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000626 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000627 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000628 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000629
Ted Kremenek56572ab2008-12-12 18:34:08 +0000630 break;
631 }
Mike Stump11289f42009-09-09 15:08:12 +0000632
Ted Kremenek56572ab2008-12-12 18:34:08 +0000633 // Otherwise skip this block.
634 continue;
635 }
Mike Stump11289f42009-09-09 15:08:12 +0000636
Ted Kremenek56572ab2008-12-12 18:34:08 +0000637 assert(K == tok::pp_elif);
638 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
639
640 // If this is a #elif with a #else before it, report the error.
641 if (CondInfo.FoundElse)
642 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000643
Ted Kremenek56572ab2008-12-12 18:34:08 +0000644 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000645 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000646 if (CondInfo.FoundNonSkip)
647 continue;
648
649 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000650 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000651 CurPTHLexer->ParsingPreprocessorDirective = true;
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +0000652 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro).Conditional;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000653 CurPTHLexer->ParsingPreprocessorDirective = false;
654
655 // If this condition is true, enter it!
656 if (ShouldEnter) {
657 CondInfo.FoundNonSkip = true;
658 break;
659 }
660
661 // Otherwise, skip this block and go to the next one.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000662 }
663}
664
Richard Smith2a553082015-04-23 22:58:06 +0000665Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000666 if (!SourceMgr.isInMainFile(Loc)) {
667 // Try to determine the module of the include directive.
668 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
669 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
670 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
671 // The include comes from an included file.
672 return HeaderInfo.getModuleMap()
673 .findModuleForHeader(EntryOfIncl)
674 .getModule();
675 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000676 }
Richard Smith7e82e012016-02-19 22:25:36 +0000677
678 // This is either in the main file or not in a file at all. It belongs
679 // to the current module, if there is one.
680 return getLangOpts().CurrentModule.empty()
681 ? nullptr
682 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000683}
684
Richard Smith4eb83932016-04-27 21:57:05 +0000685const FileEntry *
686Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000687 Module *M,
Richard Smith4eb83932016-04-27 21:57:05 +0000688 SourceLocation Loc) {
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000689 assert(M && "no module to include");
690
Richard Smith4eb83932016-04-27 21:57:05 +0000691 // If we have a module import syntax, we shouldn't include a header to
692 // make a particular module visible.
693 if (getLangOpts().ObjC2)
694 return nullptr;
695
Richard Smith4eb83932016-04-27 21:57:05 +0000696 Module *TopM = M->getTopLevelModule();
697 Module *IncM = getModuleForLocation(IncLoc);
698
699 // Walk up through the include stack, looking through textual headers of M
700 // until we hit a non-textual header that we can #include. (We assume textual
701 // headers of a module with non-textual headers aren't meant to be used to
702 // import entities from the module.)
703 auto &SM = getSourceManager();
704 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
705 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
706 auto *FE = SM.getFileEntryForID(ID);
Richard Smith040e1262017-06-02 01:55:39 +0000707 if (!FE)
708 break;
Richard Smith4eb83932016-04-27 21:57:05 +0000709
710 bool InTextualHeader = false;
711 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
712 if (!Header.getModule()->isSubModuleOf(TopM))
713 continue;
714
715 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
716 // If this is an accessible, non-textual header of M's top-level module
717 // that transitively includes the given location and makes the
718 // corresponding module visible, this is the thing to #include.
719 if (Header.isAccessibleFrom(IncM))
720 return FE;
721
722 // It's in a private header; we can't #include it.
723 // FIXME: If there's a public header in some module that re-exports it,
724 // then we could suggest including that, but it's not clear that's the
725 // expected way to make this entity visible.
726 continue;
727 }
728
729 InTextualHeader = true;
730 }
731
732 if (!InTextualHeader)
733 break;
734
735 Loc = SM.getIncludeLoc(ID);
736 }
737
738 return nullptr;
739}
740
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000741const FileEntry *Preprocessor::LookupFile(
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000742 SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
743 const DirectoryLookup *FromDir, const FileEntry *FromFile,
744 const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000745 SmallVectorImpl<char> *RelativePath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000746 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000747 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000748 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000749
Will Wilson0fafd342013-12-27 19:46:16 +0000750 // If the header lookup mechanism may be relative to the current inclusion
751 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000752 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
753 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000754 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000755 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000756 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000757 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000758
Chris Lattner022923a2009-02-04 19:45:07 +0000759 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000760 // predefines buffer or the module includes buffer. Any other file is not
761 // lexed with a normal lexer, so it won't be scanned for preprocessor
762 // directives.
763 //
764 // If we have the predefines buffer, resolve #include references (which come
765 // from the -include command line argument) from the current working
766 // directory instead of relative to the main file.
767 //
768 // If we have the module includes buffer, resolve #include references (which
769 // come from header declarations in the module map) relative to the module
770 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000771 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000772 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000773 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000774 BuildSystemModule = getCurrentModule()->IsSystem;
775 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000776 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000777 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
778 } else {
779 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
780 }
Will Wilson0fafd342013-12-27 19:46:16 +0000781
782 // MSVC searches the current include stack from top to bottom for
783 // headers included by quoted include directives.
784 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000785 if (LangOpts.MSVCCompat && !isAngled) {
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000786 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000787 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000788 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000789 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000790 }
Chris Lattner022923a2009-02-04 19:45:07 +0000791 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000794 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000795
796 if (FromFile) {
797 // We're supposed to start looking from after a particular file. Search
798 // the include path until we find that file or run out of files.
799 const DirectoryLookup *TmpCurDir = CurDir;
800 const DirectoryLookup *TmpFromDir = nullptr;
801 while (const FileEntry *FE = HeaderInfo.LookupFile(
802 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000803 Includers, SearchPath, RelativePath, RequestingModule,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000804 SuggestedModule, /*IsMapped=*/nullptr, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000805 // Keep looking as if this file did a #include_next.
806 TmpFromDir = TmpCurDir;
807 ++TmpFromDir;
808 if (FE == FromFile) {
809 // Found it.
810 FromDir = TmpFromDir;
811 CurDir = TmpCurDir;
812 break;
813 }
814 }
815 }
816
817 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000818 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000819 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000820 RelativePath, RequestingModule, SuggestedModule, IsMapped, SkipCache,
Manman Rene4a5d372016-05-17 02:15:12 +0000821 BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000822 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000823 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000824 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000825 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
826 Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000827 return FE;
828 }
Mike Stump11289f42009-09-09 15:08:12 +0000829
Will Wilson0fafd342013-12-27 19:46:16 +0000830 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000831 // Otherwise, see if this is a subframework header. If so, this is relative
832 // to one of the headers on the #include stack. Walk the list of the current
833 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000834 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000835 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000836 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000837 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000838 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000839 SuggestedModule))) {
840 if (SuggestedModule && !LangOpts.AsmPreprocessor)
841 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000842 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
843 Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000844 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000845 }
846 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000847 }
Mike Stump11289f42009-09-09 15:08:12 +0000848
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000849 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000850 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000851 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000852 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000853 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000854 RequestingModule, SuggestedModule))) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000855 if (SuggestedModule && !LangOpts.AsmPreprocessor)
856 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000857 RequestingModule, RequestingModuleIsModuleInterface,
858 FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000859 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000860 }
861 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000862 }
863 }
Mike Stump11289f42009-09-09 15:08:12 +0000864
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000865 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000866 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000867}
868
Chris Lattnerf64b3522008-03-09 01:54:53 +0000869//===----------------------------------------------------------------------===//
870// Preprocessor Directive Handling.
871//===----------------------------------------------------------------------===//
872
David Blaikied5321242012-06-06 18:52:13 +0000873class Preprocessor::ResetMacroExpansionHelper {
874public:
875 ResetMacroExpansionHelper(Preprocessor *pp)
876 : PP(pp), save(pp->DisableMacroExpansion) {
877 if (pp->MacroExpansionInDirectivesOverride)
878 pp->DisableMacroExpansion = false;
879 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000880
David Blaikied5321242012-06-06 18:52:13 +0000881 ~ResetMacroExpansionHelper() {
882 PP->DisableMacroExpansion = save;
883 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000884
David Blaikied5321242012-06-06 18:52:13 +0000885private:
886 Preprocessor *PP;
887 bool save;
888};
889
Erich Keane76675de2018-07-05 17:22:13 +0000890/// Process a directive while looking for the through header.
891/// Only #include (to check if it is the through header) and #define (to warn
892/// about macros that don't match the PCH) are handled. All other directives
893/// are completely discarded.
894void Preprocessor::HandleSkippedThroughHeaderDirective(Token &Result,
895 SourceLocation HashLoc) {
896 if (const IdentifierInfo *II = Result.getIdentifierInfo()) {
897 if (II->getPPKeywordID() == tok::pp_include)
898 return HandleIncludeDirective(HashLoc, Result);
899 if (II->getPPKeywordID() == tok::pp_define)
900 return HandleDefineDirective(Result,
901 /*ImmediatelyAfterHeaderGuard=*/false);
902 }
903 DiscardUntilEndOfDirective();
904}
905
Chris Lattnerf64b3522008-03-09 01:54:53 +0000906/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000907/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000908/// lexer/preprocessor state, and advances the lexer(s) so that the next token
909/// read is the correct one.
910void Preprocessor::HandleDirective(Token &Result) {
911 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000912
Chris Lattnerf64b3522008-03-09 01:54:53 +0000913 // We just parsed a # character at the start of a line, so we're in directive
914 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000915 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000916 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000917 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000918
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000919 bool ImmediatelyAfterTopLevelIfndef =
920 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
921 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
922
Chris Lattnerf64b3522008-03-09 01:54:53 +0000923 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000924
Chris Lattnerf64b3522008-03-09 01:54:53 +0000925 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000926 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000927 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000928 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000929
Chris Lattner2d17ab72009-03-18 21:00:25 +0000930 // Save the '#' token in case we need to return it later.
931 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000932
Chris Lattnerf64b3522008-03-09 01:54:53 +0000933 // Read the next token, the directive flavor. This isn't expanded due to
934 // C99 6.10.3p8.
935 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000936
Chris Lattnerf64b3522008-03-09 01:54:53 +0000937 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
938 // #define A(x) #x
939 // A(abc
940 // #warning blah
941 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000942 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
943 // not support this for #include-like directives, since that can result in
944 // terrible diagnostics, and does not work in GCC.
945 if (InMacroArgs) {
946 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
947 switch (II->getPPKeywordID()) {
948 case tok::pp_include:
949 case tok::pp_import:
950 case tok::pp_include_next:
951 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000952 case tok::pp_pragma:
953 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000954 DiscardUntilEndOfDirective();
955 return;
956 default:
957 break;
958 }
959 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000960 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000961 }
Mike Stump11289f42009-09-09 15:08:12 +0000962
David Blaikied5321242012-06-06 18:52:13 +0000963 // Temporarily enable macro expansion if set so
964 // and reset to previous state when returning from this function.
965 ResetMacroExpansionHelper helper(this);
966
Erich Keane76675de2018-07-05 17:22:13 +0000967 if (SkippingUntilPCHThroughHeader)
968 return HandleSkippedThroughHeaderDirective(Result, SavedHash.getLocation());
969
Chris Lattnerf64b3522008-03-09 01:54:53 +0000970 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000971 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000972 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000973 case tok::code_completion:
974 if (CodeComplete)
975 CodeComplete->CodeCompleteDirective(
976 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000977 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000978 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000979 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000980 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000981 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000982 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000983 default:
984 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000985 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000986
Chris Lattnerf64b3522008-03-09 01:54:53 +0000987 // Ask what the preprocessor keyword ID is.
988 switch (II->getPPKeywordID()) {
989 default: break;
990 // C99 6.10.1 - Conditional Inclusion.
991 case tok::pp_if:
Vedant Kumar3919a502017-09-11 20:47:42 +0000992 return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000993 case tok::pp_ifdef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000994 return HandleIfdefDirective(Result, SavedHash, false,
995 true /*not valid for miopt*/);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000996 case tok::pp_ifndef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000997 return HandleIfdefDirective(Result, SavedHash, true,
998 ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000999 case tok::pp_elif:
Vedant Kumar3919a502017-09-11 20:47:42 +00001000 return HandleElifDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001001 case tok::pp_else:
Vedant Kumar3919a502017-09-11 20:47:42 +00001002 return HandleElseDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001003 case tok::pp_endif:
1004 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001005
Chris Lattnerf64b3522008-03-09 01:54:53 +00001006 // C99 6.10.2 - Source File Inclusion.
1007 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001008 // Handle #include.
1009 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +00001010 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001011 // Handle -imacros.
Taewook Oh755e4d22016-06-13 21:55:33 +00001012 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00001013
Chris Lattnerf64b3522008-03-09 01:54:53 +00001014 // C99 6.10.3 - Macro Replacement.
1015 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001016 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001017 case tok::pp_undef:
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001018 return HandleUndefDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001019
1020 // C99 6.10.4 - Line Control.
1021 case tok::pp_line:
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001022 return HandleLineDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001023
Chris Lattnerf64b3522008-03-09 01:54:53 +00001024 // C99 6.10.5 - Error Directive.
1025 case tok::pp_error:
1026 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +00001027
Chris Lattnerf64b3522008-03-09 01:54:53 +00001028 // C99 6.10.6 - Pragma Directive.
1029 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +00001030 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +00001031
Chris Lattnerf64b3522008-03-09 01:54:53 +00001032 // GNU Extensions.
1033 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001034 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001035 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001036 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00001037
Chris Lattnerf64b3522008-03-09 01:54:53 +00001038 case tok::pp_warning:
1039 Diag(Result, diag::ext_pp_warning_directive);
1040 return HandleUserDiagnosticDirective(Result, true);
1041 case tok::pp_ident:
1042 return HandleIdentSCCSDirective(Result);
1043 case tok::pp_sccs:
1044 return HandleIdentSCCSDirective(Result);
1045 case tok::pp_assert:
1046 //isExtension = true; // FIXME: implement #assert
1047 break;
1048 case tok::pp_unassert:
1049 //isExtension = true; // FIXME: implement #unassert
1050 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001051
Douglas Gregor663b48f2012-01-03 19:48:16 +00001052 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001053 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001054 return HandleMacroPublicDirective(Result);
1055 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001056
Douglas Gregor663b48f2012-01-03 19:48:16 +00001057 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001058 if (getLangOpts().Modules)
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001059 return HandleMacroPrivateDirective();
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001060 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001061 }
1062 break;
1063 }
Mike Stump11289f42009-09-09 15:08:12 +00001064
Chris Lattner2d17ab72009-03-18 21:00:25 +00001065 // If this is a .S file, treat unknown # directives as non-preprocessor
1066 // directives. This is important because # may be a comment or introduce
1067 // various pseudo-ops. Just return the # token and push back the following
1068 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001069 if (getLangOpts().AsmPreprocessor) {
David Blaikie2eabcc92016-02-09 18:52:09 +00001070 auto Toks = llvm::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001071 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001072 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001073 Toks[1] = Result;
Taewook Oh755e4d22016-06-13 21:55:33 +00001074
Chris Lattner56f64c12011-01-06 05:01:51 +00001075 // If the second token is a hashhash token, then we need to translate it to
1076 // unknown so the token lexer doesn't try to perform token pasting.
1077 if (Result.is(tok::hashhash))
1078 Toks[1].setKind(tok::unknown);
Taewook Oh755e4d22016-06-13 21:55:33 +00001079
Chris Lattner2d17ab72009-03-18 21:00:25 +00001080 // Enter this token stream so that we re-lex the tokens. Make sure to
1081 // enable macro expansion, in case the token after the # is an identifier
1082 // that is expanded.
David Blaikie2eabcc92016-02-09 18:52:09 +00001083 EnterTokenStream(std::move(Toks), 2, false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001084 return;
1085 }
Mike Stump11289f42009-09-09 15:08:12 +00001086
Chris Lattnerf64b3522008-03-09 01:54:53 +00001087 // If we reached here, the preprocessing token is not valid!
1088 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001089
Chris Lattnerf64b3522008-03-09 01:54:53 +00001090 // Read the rest of the PP line.
1091 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001092
Chris Lattnerf64b3522008-03-09 01:54:53 +00001093 // Okay, we're done parsing the directive.
1094}
1095
Chris Lattner76e68962009-01-26 06:19:46 +00001096/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1097/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1098static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001099 unsigned DiagID, Preprocessor &PP,
1100 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001101 if (DigitTok.isNot(tok::numeric_constant)) {
1102 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001103
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001104 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001105 PP.DiscardUntilEndOfDirective();
1106 return true;
1107 }
Mike Stump11289f42009-09-09 15:08:12 +00001108
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001109 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001110 IntegerBuffer.resize(DigitTok.getLength());
1111 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001112 bool Invalid = false;
1113 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1114 if (Invalid)
1115 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001116
Chris Lattnerd66f1722009-04-18 18:35:15 +00001117 // Verify that we have a simple digit-sequence, and compute the value. This
1118 // is always a simple digit string computed in decimal, so we do this manually
1119 // here.
1120 Val = 0;
1121 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001122 // C++1y [lex.fcon]p1:
1123 // Optional separating single quotes in a digit-sequence are ignored
1124 if (DigitTokBegin[i] == '\'')
1125 continue;
1126
Jordan Rosea7d03842013-02-08 22:30:41 +00001127 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001128 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001129 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001130 PP.DiscardUntilEndOfDirective();
1131 return true;
1132 }
Mike Stump11289f42009-09-09 15:08:12 +00001133
Chris Lattnerd66f1722009-04-18 18:35:15 +00001134 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1135 if (NextVal < Val) { // overflow.
1136 PP.Diag(DigitTok, DiagID);
1137 PP.DiscardUntilEndOfDirective();
1138 return true;
1139 }
1140 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001141 }
Mike Stump11289f42009-09-09 15:08:12 +00001142
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001143 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001144 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1145 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001146
Chris Lattner76e68962009-01-26 06:19:46 +00001147 return false;
1148}
1149
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001150/// Handle a \#line directive: C99 6.10.4.
James Dennettf6333ac2012-06-22 05:46:07 +00001151///
1152/// The two acceptable forms are:
1153/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001154/// # line digit-sequence
1155/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001156/// \endverbatim
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001157void Preprocessor::HandleLineDirective() {
Chris Lattner100c65e2009-01-26 05:29:08 +00001158 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1159 // expanded.
1160 Token DigitTok;
1161 Lex(DigitTok);
1162
Chris Lattner100c65e2009-01-26 05:29:08 +00001163 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001164 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001165 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001166 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001167
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001168 if (LineNo == 0)
1169 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001170
Chris Lattner76e68962009-01-26 06:19:46 +00001171 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1172 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001173 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001174 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001175 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001176 if (LineNo >= LineLimit)
1177 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001178 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001179 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001180
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001181 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001182 Token StrTok;
1183 Lex(StrTok);
1184
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001185 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1186 // string followed by eod.
1187 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001188 ; // ok
1189 else if (StrTok.isNot(tok::string_literal)) {
1190 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001191 return DiscardUntilEndOfDirective();
1192 } else if (StrTok.hasUDSuffix()) {
1193 Diag(StrTok, diag::err_invalid_string_udl);
1194 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001195 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001196 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001197 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001198 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001199 if (Literal.hadError)
1200 return DiscardUntilEndOfDirective();
1201 if (Literal.Pascal) {
1202 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1203 return DiscardUntilEndOfDirective();
1204 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001205 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001206
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001207 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001208 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1209 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001210 }
Mike Stump11289f42009-09-09 15:08:12 +00001211
Reid Klecknereb00ee02017-05-22 21:42:58 +00001212 // Take the file kind of the file containing the #line directive. #line
1213 // directives are often used for generated sources from the same codebase, so
1214 // the new file should generally be classified the same way as the current
1215 // file. This is visible in GCC's pre-processed output, which rewrites #line
1216 // to GNU line markers.
1217 SrcMgr::CharacteristicKind FileKind =
1218 SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1219
1220 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1221 false, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattner839150e2009-03-27 17:13:49 +00001223 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001224 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Reid Klecknereb00ee02017-05-22 21:42:58 +00001225 PPCallbacks::RenameFile, FileKind);
Chris Lattner100c65e2009-01-26 05:29:08 +00001226}
1227
Chris Lattner76e68962009-01-26 06:19:46 +00001228/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1229/// marker directive.
1230static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
Reid Klecknereb00ee02017-05-22 21:42:58 +00001231 SrcMgr::CharacteristicKind &FileKind,
Chris Lattner76e68962009-01-26 06:19:46 +00001232 Preprocessor &PP) {
1233 unsigned FlagVal;
1234 Token FlagTok;
1235 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001236 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001237 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1238 return true;
1239
1240 if (FlagVal == 1) {
1241 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001242
Chris Lattner76e68962009-01-26 06:19:46 +00001243 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001244 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001245 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1246 return true;
1247 } else if (FlagVal == 2) {
1248 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001249
Chris Lattner1c967782009-02-04 06:25:26 +00001250 SourceManager &SM = PP.getSourceManager();
1251 // If we are leaving the current presumed file, check to make sure the
1252 // presumed include stack isn't empty!
1253 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001254 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001255 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001256 if (PLoc.isInvalid())
1257 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001258
Chris Lattner1c967782009-02-04 06:25:26 +00001259 // If there is no include loc (main file) or if the include loc is in a
1260 // different physical file, then we aren't in a "1" line marker flag region.
1261 SourceLocation IncLoc = PLoc.getIncludeLoc();
1262 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001263 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001264 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1265 PP.DiscardUntilEndOfDirective();
1266 return true;
1267 }
Mike Stump11289f42009-09-09 15:08:12 +00001268
Chris Lattner76e68962009-01-26 06:19:46 +00001269 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001270 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001271 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1272 return true;
1273 }
1274
1275 // We must have 3 if there are still flags.
1276 if (FlagVal != 3) {
1277 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001278 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001279 return true;
1280 }
Mike Stump11289f42009-09-09 15:08:12 +00001281
Reid Klecknereb00ee02017-05-22 21:42:58 +00001282 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001283
Chris Lattner76e68962009-01-26 06:19:46 +00001284 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001285 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001286 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001287 return true;
1288
1289 // We must have 4 if there is yet another flag.
1290 if (FlagVal != 4) {
1291 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001292 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001293 return true;
1294 }
Mike Stump11289f42009-09-09 15:08:12 +00001295
Reid Klecknereb00ee02017-05-22 21:42:58 +00001296 FileKind = SrcMgr::C_ExternCSystem;
Mike Stump11289f42009-09-09 15:08:12 +00001297
Chris Lattner76e68962009-01-26 06:19:46 +00001298 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001299 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001300
1301 // There are no more valid flags here.
1302 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001303 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001304 return true;
1305}
1306
1307/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1308/// one of the following forms:
1309///
1310/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001311/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001312/// # 42 "file" ('1' | '2')? '3' '4'?
1313///
1314void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1315 // Validate the number and convert it to an unsigned. GNU does not have a
1316 // line # limit other than it fit in 32-bits.
1317 unsigned LineNo;
1318 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001319 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001320 return;
Mike Stump11289f42009-09-09 15:08:12 +00001321
Chris Lattner76e68962009-01-26 06:19:46 +00001322 Token StrTok;
1323 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001324
Chris Lattner76e68962009-01-26 06:19:46 +00001325 bool IsFileEntry = false, IsFileExit = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001326 int FilenameID = -1;
Reid Klecknereb00ee02017-05-22 21:42:58 +00001327 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001328
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001329 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1330 // string followed by eod.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001331 if (StrTok.is(tok::eod)) {
1332 // Treat this like "#line NN", which doesn't change file characteristics.
1333 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1334 } else if (StrTok.isNot(tok::string_literal)) {
Chris Lattner76e68962009-01-26 06:19:46 +00001335 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001336 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001337 } else if (StrTok.hasUDSuffix()) {
1338 Diag(StrTok, diag::err_invalid_string_udl);
1339 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001340 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001341 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001342 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001343 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001344 if (Literal.hadError)
1345 return DiscardUntilEndOfDirective();
1346 if (Literal.Pascal) {
1347 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1348 return DiscardUntilEndOfDirective();
1349 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001350 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001351
Chris Lattner76e68962009-01-26 06:19:46 +00001352 // If a filename was present, read any flags that are present.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001353 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001354 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001355 }
Mike Stump11289f42009-09-09 15:08:12 +00001356
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001357 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001358 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1359 IsFileExit, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattner839150e2009-03-27 17:13:49 +00001361 // If the preprocessor has callbacks installed, notify them of the #line
1362 // change. This is used so that the line marker comes out in -E mode for
1363 // example.
1364 if (Callbacks) {
1365 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1366 if (IsFileEntry)
1367 Reason = PPCallbacks::EnterFile;
1368 else if (IsFileExit)
1369 Reason = PPCallbacks::ExitFile;
Mike Stump11289f42009-09-09 15:08:12 +00001370
Chris Lattnerc745cec2010-04-14 04:28:50 +00001371 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001372 }
Chris Lattner76e68962009-01-26 06:19:46 +00001373}
1374
Chris Lattner38d7fd22009-01-26 05:30:54 +00001375/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1376///
Mike Stump11289f42009-09-09 15:08:12 +00001377void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001378 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001379 // PTH doesn't emit #warning or #error directives.
1380 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001381 return CurPTHLexer->DiscardToEndOfLine();
1382
Chris Lattnerf64b3522008-03-09 01:54:53 +00001383 // Read the rest of the line raw. We do this because we don't want macros
1384 // to be expanded and we don't require that the tokens be valid preprocessing
1385 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001386 // collapse multiple consecutive white space between tokens, but this isn't
Chris Lattnerf64b3522008-03-09 01:54:53 +00001387 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001388 SmallString<128> Message;
1389 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001390
1391 // Find the first non-whitespace character, so that we can make the
1392 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001393 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001394
Chris Lattner100c65e2009-01-26 05:29:08 +00001395 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001396 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001397 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001398 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001399}
1400
1401/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1402///
1403void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1404 // Yes, this directive is an extension.
1405 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001406
Chris Lattnerf64b3522008-03-09 01:54:53 +00001407 // Read the string argument.
1408 Token StrTok;
1409 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001410
Chris Lattnerf64b3522008-03-09 01:54:53 +00001411 // If the token kind isn't a string, it's a malformed directive.
1412 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001413 StrTok.isNot(tok::wide_string_literal)) {
1414 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001415 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001416 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001417 return;
1418 }
Mike Stump11289f42009-09-09 15:08:12 +00001419
Richard Smithd67aea22012-03-06 03:21:47 +00001420 if (StrTok.hasUDSuffix()) {
1421 Diag(StrTok, diag::err_invalid_string_udl);
1422 return DiscardUntilEndOfDirective();
1423 }
1424
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001425 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001426 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001427
Douglas Gregordc970f02010-03-16 22:30:13 +00001428 if (Callbacks) {
1429 bool Invalid = false;
1430 std::string Str = getSpelling(StrTok, &Invalid);
1431 if (!Invalid)
1432 Callbacks->Ident(Tok.getLocation(), Str);
1433 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001434}
1435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001436/// Handle a #public directive.
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001437void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001438 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001439 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001440
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001441 // Error reading macro name? If so, diagnostic already issued.
1442 if (MacroNameTok.is(tok::eod))
1443 return;
1444
Douglas Gregor663b48f2012-01-03 19:48:16 +00001445 // Check to see if this is the last token on the #__public_macro line.
1446 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001447
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001448 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001449 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001450 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001451
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001452 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001453 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001454 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001455 return;
1456 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001457
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001458 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001459 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1460 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001461}
1462
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001463/// Handle a #private directive.
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001464void Preprocessor::HandleMacroPrivateDirective() {
Douglas Gregorebf00492011-10-17 15:32:29 +00001465 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001466 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001467
Douglas Gregorebf00492011-10-17 15:32:29 +00001468 // Error reading macro name? If so, diagnostic already issued.
1469 if (MacroNameTok.is(tok::eod))
1470 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001471
Douglas Gregor663b48f2012-01-03 19:48:16 +00001472 // Check to see if this is the last token on the #__private_macro line.
1473 CheckEndOfDirective("__private_macro");
Taewook Oh755e4d22016-06-13 21:55:33 +00001474
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001475 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001476 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001477 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001478
Douglas Gregorebf00492011-10-17 15:32:29 +00001479 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001480 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001481 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001482 return;
1483 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001484
Douglas Gregorebf00492011-10-17 15:32:29 +00001485 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001486 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1487 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001488}
1489
Chris Lattnerf64b3522008-03-09 01:54:53 +00001490//===----------------------------------------------------------------------===//
1491// Preprocessor Include Directive Handling.
1492//===----------------------------------------------------------------------===//
1493
1494/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001495/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001496/// true if the input filename was in <>'s or false if it were in ""'s. The
1497/// caller is expected to provide a buffer that is large enough to hold the
1498/// spelling of the filename, but is also expected to handle the case when
1499/// this method decides to use a different buffer.
1500bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001501 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001502 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001503 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001504
Chris Lattnerf64b3522008-03-09 01:54:53 +00001505 // Make sure the filename is <x> or "x".
1506 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001507 if (Buffer[0] == '<') {
1508 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001509 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001510 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001511 return true;
1512 }
1513 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001514 } else if (Buffer[0] == '"') {
1515 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001516 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001517 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001518 return true;
1519 }
1520 isAngled = false;
1521 } else {
1522 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001523 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001524 return true;
1525 }
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattnerf64b3522008-03-09 01:54:53 +00001527 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001528 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001529 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001530 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001531 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001532 }
Mike Stump11289f42009-09-09 15:08:12 +00001533
Chris Lattnerf64b3522008-03-09 01:54:53 +00001534 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001535 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001536 return isAngled;
1537}
1538
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001539// Handle cases where the \#include name is expanded from a macro
James Dennett4a4f72d2013-11-27 01:27:40 +00001540// as multiple tokens, which need to be glued together.
1541//
1542// This occurs for code like:
1543// \code
1544// \#define FOO <a/b.h>
1545// \#include FOO
1546// \endcode
1547// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1548//
1549// This code concatenates and consumes tokens up to the '>' token. It returns
1550// false if the > was found, otherwise it returns true if it finds and consumes
1551// the EOD marker.
1552bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001553 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001554 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001555
John Thompsonb5353522009-10-30 13:49:06 +00001556 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001557 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001558 End = CurTok.getLocation();
Taewook Oh755e4d22016-06-13 21:55:33 +00001559
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001560 // FIXME: Provide code completion for #includes.
1561 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001562 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001563 Lex(CurTok);
1564 continue;
1565 }
1566
Chris Lattnerf64b3522008-03-09 01:54:53 +00001567 // Append the spelling of this token to the buffer. If there was a space
1568 // before it, add it now.
1569 if (CurTok.hasLeadingSpace())
1570 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001571
Chris Lattnerf64b3522008-03-09 01:54:53 +00001572 // Get the spelling of the token, directly into FilenameBuffer if possible.
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001573 size_t PreAppendSize = FilenameBuffer.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001574 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001575
Chris Lattnerf64b3522008-03-09 01:54:53 +00001576 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001577 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001578
Chris Lattnerf64b3522008-03-09 01:54:53 +00001579 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1580 if (BufPtr != &FilenameBuffer[PreAppendSize])
1581 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001582
Chris Lattnerf64b3522008-03-09 01:54:53 +00001583 // Resize FilenameBuffer to the correct size.
1584 if (CurTok.getLength() != ActualLen)
1585 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001586
Chris Lattnerf64b3522008-03-09 01:54:53 +00001587 // If we found the '>' marker, return success.
1588 if (CurTok.is(tok::greater))
1589 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001590
John Thompsonb5353522009-10-30 13:49:06 +00001591 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001592 }
1593
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001594 // If we hit the eod marker, emit an error and return true so that the caller
1595 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001596 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001597 return true;
1598}
1599
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001600/// Push a token onto the token stream containing an annotation.
Richard Smithc51c38b2017-04-29 00:34:47 +00001601void Preprocessor::EnterAnnotationToken(SourceRange Range,
1602 tok::TokenKind Kind,
1603 void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001604 // FIXME: Produce this as the current token directly, rather than
1605 // allocating a new token for it.
David Blaikie2eabcc92016-02-09 18:52:09 +00001606 auto Tok = llvm::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001607 Tok[0].startToken();
1608 Tok[0].setKind(Kind);
Richard Smithc51c38b2017-04-29 00:34:47 +00001609 Tok[0].setLocation(Range.getBegin());
1610 Tok[0].setAnnotationEndLoc(Range.getEnd());
Richard Smith34f30512013-11-23 04:06:09 +00001611 Tok[0].setAnnotationValue(AnnotationVal);
Richard Smithc51c38b2017-04-29 00:34:47 +00001612 EnterTokenStream(std::move(Tok), 1, true);
Richard Smith34f30512013-11-23 04:06:09 +00001613}
1614
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001615/// Produce a diagnostic informing the user that a #include or similar
Richard Smith63b6fce2015-05-18 04:45:41 +00001616/// was implicitly treated as a module import.
1617static void diagnoseAutoModuleImport(
1618 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1619 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1620 SourceLocation PathEnd) {
1621 assert(PP.getLangOpts().ObjC2 && "no import syntax available");
1622
1623 SmallString<128> PathString;
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001624 for (size_t I = 0, N = Path.size(); I != N; ++I) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001625 if (I)
1626 PathString += '.';
1627 PathString += Path[I].first->getName();
1628 }
1629 int IncludeKind = 0;
Taewook Oh755e4d22016-06-13 21:55:33 +00001630
Richard Smith63b6fce2015-05-18 04:45:41 +00001631 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1632 case tok::pp_include:
1633 IncludeKind = 0;
1634 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001635
Richard Smith63b6fce2015-05-18 04:45:41 +00001636 case tok::pp_import:
1637 IncludeKind = 1;
Taewook Oh755e4d22016-06-13 21:55:33 +00001638 break;
1639
Richard Smith63b6fce2015-05-18 04:45:41 +00001640 case tok::pp_include_next:
1641 IncludeKind = 2;
1642 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001643
Richard Smith63b6fce2015-05-18 04:45:41 +00001644 case tok::pp___include_macros:
1645 IncludeKind = 3;
1646 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001647
Richard Smith63b6fce2015-05-18 04:45:41 +00001648 default:
1649 llvm_unreachable("unknown include directive kind");
1650 }
1651
1652 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1653 /*IsTokenRange=*/false);
1654 PP.Diag(HashLoc, diag::warn_auto_module_import)
1655 << IncludeKind << PathString
1656 << FixItHint::CreateReplacement(ReplaceRange,
1657 ("@import " + PathString + ";").str());
1658}
1659
Taewook Ohf42103c2016-06-13 20:40:21 +00001660// Given a vector of path components and a string containing the real
1661// path to the file, build a properly-cased replacement in the vector,
1662// and return true if the replacement should be suggested.
1663static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1664 StringRef RealPathName) {
1665 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1666 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1667 int Cnt = 0;
1668 bool SuggestReplacement = false;
1669 // Below is a best-effort to handle ".." in paths. It is admittedly
1670 // not 100% correct in the presence of symlinks.
1671 for (auto &Component : llvm::reverse(Components)) {
1672 if ("." == Component) {
1673 } else if (".." == Component) {
1674 ++Cnt;
1675 } else if (Cnt) {
1676 --Cnt;
1677 } else if (RealPathComponentIter != RealPathComponentEnd) {
1678 if (Component != *RealPathComponentIter) {
1679 // If these path components differ by more than just case, then we
1680 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1681 // noisy false positives.
1682 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1683 if (!SuggestReplacement)
1684 break;
1685 Component = *RealPathComponentIter;
1686 }
1687 ++RealPathComponentIter;
1688 }
1689 }
1690 return SuggestReplacement;
1691}
1692
Richard Smith27e5aa02017-06-05 18:57:56 +00001693bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
1694 const TargetInfo &TargetInfo,
1695 DiagnosticsEngine &Diags, Module *M) {
1696 Module::Requirement Requirement;
1697 Module::UnresolvedHeaderDirective MissingHeader;
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00001698 Module *ShadowingModule = nullptr;
1699 if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
1700 ShadowingModule))
Richard Smith27e5aa02017-06-05 18:57:56 +00001701 return false;
1702
1703 if (MissingHeader.FileNameLoc.isValid()) {
1704 Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1705 << MissingHeader.IsUmbrella << MissingHeader.FileName;
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00001706 } else if (ShadowingModule) {
1707 Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name;
1708 Diags.Report(ShadowingModule->DefinitionLoc,
1709 diag::note_previous_definition);
Richard Smith27e5aa02017-06-05 18:57:56 +00001710 } else {
1711 // FIXME: Track the location at which the requirement was specified, and
1712 // use it here.
1713 Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
1714 << M->getFullModuleName() << Requirement.second << Requirement.first;
1715 }
1716 return true;
1717}
1718
James Dennettf6333ac2012-06-22 05:46:07 +00001719/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1720/// the file to be included from the lexer, then include it! This is a common
1721/// routine with functionality shared between \#include, \#include_next and
1722/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001723/// specifies the file to start searching from.
Taewook Oh755e4d22016-06-13 21:55:33 +00001724void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001725 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001726 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001727 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001728 bool isImport) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001729 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001730 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001731
Chris Lattnerf64b3522008-03-09 01:54:53 +00001732 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001733 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001734 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001735 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001736 SourceLocation CharEnd; // the end of this directive, in characters
Taewook Oh755e4d22016-06-13 21:55:33 +00001737
Chris Lattnerf64b3522008-03-09 01:54:53 +00001738 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001739 case tok::eod:
1740 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001741 return;
Mike Stump11289f42009-09-09 15:08:12 +00001742
Chris Lattnerf64b3522008-03-09 01:54:53 +00001743 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001744 case tok::string_literal:
1745 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001746 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001747 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001748 break;
Mike Stump11289f42009-09-09 15:08:12 +00001749
Chris Lattnerf64b3522008-03-09 01:54:53 +00001750 case tok::less:
1751 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1752 // case, glue the tokens together into FilenameBuffer and interpret those.
1753 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001754 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001755 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001756 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001757 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001758 break;
1759 default:
1760 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1761 DiscardUntilEndOfDirective();
1762 return;
1763 }
Mike Stump11289f42009-09-09 15:08:12 +00001764
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001765 CharSourceRange FilenameRange
1766 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001767 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001768 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001769 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001770 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1771 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001772 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001773 DiscardUntilEndOfDirective();
1774 return;
1775 }
Mike Stump11289f42009-09-09 15:08:12 +00001776
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001777 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001778 // we allow macros that expand to nothing after the filename, because this
1779 // falls into the category of "#include pp-tokens new-line" specified in
1780 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001781 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001782
1783 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001784 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1785 Diag(FilenameTok, diag::err_pp_include_too_deep);
1786 return;
1787 }
Mike Stump11289f42009-09-09 15:08:12 +00001788
John McCall32f5fe12011-09-30 05:12:12 +00001789 // Complain about attempts to #include files in an audit pragma.
1790 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1791 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1792 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1793
1794 // Immediately leave the pragma.
1795 PragmaARCCFCodeAuditedLoc = SourceLocation();
1796 }
1797
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001798 // Complain about attempts to #include files in an assume-nonnull pragma.
1799 if (PragmaAssumeNonNullLoc.isValid()) {
1800 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1801 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1802
1803 // Immediately leave the pragma.
1804 PragmaAssumeNonNullLoc = SourceLocation();
1805 }
1806
Aaron Ballman611306e2012-03-02 22:51:54 +00001807 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001808 // Map the filename with the brackets still attached. If the name doesn't
1809 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001810 // spelling for.
1811 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1812 if (!NewName.empty())
1813 Filename = NewName;
1814 }
1815
Chris Lattnerf64b3522008-03-09 01:54:53 +00001816 // Search include directories.
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001817 bool IsMapped = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001818 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001819 SmallString<1024> SearchPath;
1820 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001821 // We get the raw path only if we have 'Callbacks' to which we later pass
1822 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001823 ModuleMap::KnownHeader SuggestedModule;
1824 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001825 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001826 if (LangOpts.MSVCCompat) {
1827 NormalizedPath = Filename.str();
Nico Weber1865df42018-04-27 19:11:14 +00001828#ifndef _WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001829 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001830#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001831 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001832 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001833 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001834 isAngled, LookupFrom, LookupFromFile, CurDir,
1835 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001836 &SuggestedModule, &IsMapped);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001837
Richard Smithdbbc5232015-05-14 02:25:44 +00001838 if (!File) {
1839 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001840 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001841 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001842 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1843 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1844 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001845 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001846 HeaderInfo.AddSearchPath(DL, isAngled);
Taewook Oh755e4d22016-06-13 21:55:33 +00001847
Douglas Gregor11729f02011-11-30 18:12:06 +00001848 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001849 File = LookupFile(
1850 FilenameLoc,
1851 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1852 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001853 &SuggestedModule, &IsMapped, /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001854 }
1855 }
1856 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001857
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001858 if (!SuppressIncludeNotFoundError) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001859 // If the file could not be located and it was included via angle
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001860 // brackets, we can attempt a lookup as though it were a quoted path to
1861 // provide the user with a possible fixit.
1862 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001863 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001864 FilenameLoc,
1865 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1866 LookupFrom, LookupFromFile, CurDir,
1867 Callbacks ? &SearchPath : nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001868 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001869 if (File) {
1870 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001871 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1872 Filename <<
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001873 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1874 }
1875 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001876
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001877 // If the file is still not found, just go with the vanilla diagnostic
1878 if (!File)
Erik Verbruggen45449542016-10-25 10:13:10 +00001879 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename
1880 << FilenameRange;
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001881 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001882 }
1883
Erich Keane76675de2018-07-05 17:22:13 +00001884 if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
1885 if (isPCHThroughHeader(File))
1886 SkippingUntilPCHThroughHeader = false;
1887 return;
1888 }
1889
Richard Smith63b6fce2015-05-18 04:45:41 +00001890 // Should we enter the source file? Set to false if either the source file is
1891 // known to have no effect beyond its effect on module visibility -- that is,
1892 // if it's got an include guard that is already defined or is a modular header
1893 // we've imported or already built.
1894 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001895
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001896 if (PPOpts->SingleFileParseMode)
1897 ShouldEnter = false;
1898
Richard Smith63b6fce2015-05-18 04:45:41 +00001899 // Determine whether we should try to import the module for this #include, if
1900 // there is one. Don't do so if precompiled module support is disabled or we
1901 // are processing this module textually (because we're building the module).
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001902 if (ShouldEnter && File && SuggestedModule && getLangOpts().Modules &&
Bruno Cardoso Lopes5bccc522018-02-16 00:12:57 +00001903 !isForModuleBuilding(SuggestedModule.getModule(),
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00001904 getLangOpts().CurrentModule,
1905 getLangOpts().ModuleName)) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001906 // If this include corresponds to a module but that module is
1907 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001908 // FIXME: Remove this; loadModule does the same check (but produces
1909 // slightly worse diagnostics).
Richard Smith27e5aa02017-06-05 18:57:56 +00001910 if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
1911 SuggestedModule.getModule())) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001912 Diag(FilenameTok.getLocation(),
1913 diag::note_implicit_top_level_module_import_here)
Richard Smith27e5aa02017-06-05 18:57:56 +00001914 << SuggestedModule.getModule()->getTopLevelModuleName();
Sean Silva8b7c0392015-08-17 16:39:30 +00001915 return;
1916 }
1917
Douglas Gregor71944202011-11-30 00:36:36 +00001918 // Compute the module access path corresponding to this module.
1919 // FIXME: Should we have a second loadModule() overload to avoid this
1920 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001921 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001922 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001923 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1924 FilenameTok.getLocation()));
1925 std::reverse(Path.begin(), Path.end());
1926
Douglas Gregor41e115a2011-11-30 18:02:36 +00001927 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001928 // We only do this in Objective-C, where we have a module-import syntax.
1929 if (getLangOpts().ObjC2)
1930 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001931
Richard Smith10434f32015-05-02 02:08:26 +00001932 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001933 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001934 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1935 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001936 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1937 IncludeTok.getLocation(), Path, Module::Hidden,
1938 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001939 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001940 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001941
Richard Smith63b6fce2015-05-18 04:45:41 +00001942 if (Imported)
1943 ShouldEnter = false;
1944 else if (Imported.isMissingExpected()) {
1945 // We failed to find a submodule that we assumed would exist (because it
1946 // was in the directory of an umbrella header, for instance), but no
Richard Smitha114c462016-12-06 00:40:17 +00001947 // actual module containing it exists (because the umbrella header is
Richard Smith63b6fce2015-05-18 04:45:41 +00001948 // incomplete). Treat this as a textual inclusion.
1949 SuggestedModule = ModuleMap::KnownHeader();
Richard Smitha114c462016-12-06 00:40:17 +00001950 } else if (Imported.isConfigMismatch()) {
1951 // On a configuration mismatch, enter the header textually. We still know
1952 // that it's part of the corresponding module.
Richard Smith63b6fce2015-05-18 04:45:41 +00001953 } else {
1954 // We hit an error processing the import. Bail out.
1955 if (hadModuleLoaderFatalFailure()) {
1956 // With a fatal failure in the module loader, we abort parsing.
1957 Token &Result = IncludeTok;
1958 if (CurLexer) {
1959 Result.startToken();
1960 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1961 CurLexer->cutOffLexing();
1962 } else {
1963 assert(CurPTHLexer && "#include but no current lexer set!");
1964 CurPTHLexer->getEOF(Result);
1965 }
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001966 }
1967 return;
1968 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001969 }
1970
Richard Smithc5247e62017-05-30 02:03:19 +00001971 // The #included file will be considered to be a system header if either it is
1972 // in a system include directory, or if the #includer is a system include
1973 // header.
1974 SrcMgr::CharacteristicKind FileCharacter =
1975 SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
1976 if (File)
1977 FileCharacter = std::max(HeaderInfo.getFileDirFlavor(File), FileCharacter);
1978
1979 // Ask HeaderInfo if we should enter this #include file. If not, #including
1980 // this file will have no effect.
1981 bool SkipHeader = false;
1982 if (ShouldEnter && File &&
1983 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
1984 getLangOpts().Modules,
1985 SuggestedModule.getModule())) {
1986 ShouldEnter = false;
1987 SkipHeader = true;
1988 }
1989
Richard Smith63b6fce2015-05-18 04:45:41 +00001990 if (Callbacks) {
1991 // Notify the callback object that we've seen an inclusion directive.
1992 Callbacks->InclusionDirective(
1993 HashLoc, IncludeTok,
1994 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1995 FilenameRange, File, SearchPath, RelativePath,
Julie Hockett96fbe582018-05-10 19:05:36 +00001996 ShouldEnter ? nullptr : SuggestedModule.getModule(), FileCharacter);
Richard Smithc5247e62017-05-30 02:03:19 +00001997 if (SkipHeader && !SuggestedModule.getModule())
1998 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Douglas Gregor97eec242011-09-15 22:00:41 +00001999 }
Richard Smith63b6fce2015-05-18 04:45:41 +00002000
2001 if (!File)
2002 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00002003
Richard Smith54ef4c32015-05-19 19:58:11 +00002004 // FIXME: If we have a suggested module, and we've already visited this file,
2005 // don't bother entering it again. We know it has no further effect.
2006
Taewook Ohf42103c2016-06-13 20:40:21 +00002007 // Issue a diagnostic if the name of the file on disk has a different case
2008 // than the one we're about to open.
2009 const bool CheckIncludePathPortability =
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00002010 !IsMapped && File && !File->tryGetRealPathName().empty();
Taewook Ohf42103c2016-06-13 20:40:21 +00002011
2012 if (CheckIncludePathPortability) {
2013 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
2014 StringRef RealPathName = File->tryGetRealPathName();
2015 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
2016 llvm::sys::path::end(Name));
2017
2018 if (trySimplifyPath(Components, RealPathName)) {
2019 SmallString<128> Path;
2020 Path.reserve(Name.size()+2);
2021 Path.push_back(isAngled ? '<' : '"');
Taewook Ohcc89bac2017-02-21 22:30:55 +00002022 bool isLeadingSeparator = llvm::sys::path::is_absolute(Name);
Taewook Ohf42103c2016-06-13 20:40:21 +00002023 for (auto Component : Components) {
Taewook Ohcc89bac2017-02-21 22:30:55 +00002024 if (isLeadingSeparator)
2025 isLeadingSeparator = false;
2026 else
2027 Path.append(Component);
Taewook Ohf42103c2016-06-13 20:40:21 +00002028 // Append the separator the user used, or the close quote
2029 Path.push_back(
2030 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
2031 (isAngled ? '>' : '"'));
2032 }
Taewook Ohf42103c2016-06-13 20:40:21 +00002033 // For user files and known standard headers, by default we issue a diagnostic.
2034 // For other system headers, we don't. They can be controlled separately.
2035 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
2036 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
2037 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Reid Kleckner273895b2017-02-14 18:38:40 +00002038 Diag(FilenameTok, DiagId) << Path <<
2039 FixItHint::CreateReplacement(Range, Path);
Taewook Ohf42103c2016-06-13 20:40:21 +00002040 }
2041 }
2042
Richard Smith63b6fce2015-05-18 04:45:41 +00002043 // If we don't need to enter the file, stop now.
2044 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00002045 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00002046 if (auto *M = SuggestedModule.getModule()) {
Manman Renffd3e9d2017-01-09 19:20:18 +00002047 // When building a pch, -fmodule-name tells the compiler to textually
2048 // include headers in the specified module. But it is possible that
2049 // ShouldEnter is false because we are skipping the header. In that
2050 // case, We are not importing the specified module.
2051 if (SkipHeader && getLangOpts().CompilingPCH &&
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00002052 isForModuleBuilding(M, getLangOpts().CurrentModule,
2053 getLangOpts().ModuleName))
Manman Renffd3e9d2017-01-09 19:20:18 +00002054 return;
2055
Richard Smitha0aafa32015-05-18 03:52:30 +00002056 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00002057
2058 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
2059 tok::pp___include_macros)
Richard Smithc51c38b2017-04-29 00:34:47 +00002060 EnterAnnotationToken(SourceRange(HashLoc, End),
2061 tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00002062 }
Chris Lattner72286d62010-04-19 20:44:31 +00002063 return;
2064 }
2065
Chris Lattnerf64b3522008-03-09 01:54:53 +00002066 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002067 SourceLocation IncludePos = End;
2068 // If the filename string was the result of macro expansions, set the include
2069 // position on the file where it will be included and after the expansions.
2070 if (IncludePos.isMacroID())
Richard Smithb5f81712018-04-30 05:25:48 +00002071 IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002072 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002073 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002074
Richard Smith34f30512013-11-23 04:06:09 +00002075 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002076 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
2077 return;
Richard Smith34f30512013-11-23 04:06:09 +00002078
Richard Smitha0aafa32015-05-18 03:52:30 +00002079 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002080 if (auto *M = SuggestedModule.getModule()) {
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00002081 if (M->getTopLevelModule()->ShadowingModule) {
2082 // We are building a submodule that belongs to a shadowed module. This
2083 // means we find header files in the shadowed module.
2084 Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule)
2085 << M->getFullModuleName();
2086 Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc,
2087 diag::note_previous_definition);
2088 return;
2089 }
Manman Renffd3e9d2017-01-09 19:20:18 +00002090 // When building a pch, -fmodule-name tells the compiler to textually
2091 // include headers in the specified module. We are not building the
2092 // specified module.
2093 if (getLangOpts().CompilingPCH &&
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00002094 isForModuleBuilding(M, getLangOpts().CurrentModule,
2095 getLangOpts().ModuleName))
Manman Renffd3e9d2017-01-09 19:20:18 +00002096 return;
2097
Richard Smithd1386302017-05-04 00:29:54 +00002098 assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2099 CurLexerSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002100
Richard Smitha0aafa32015-05-18 03:52:30 +00002101 // Let the macro handling code know that any future macros are within
2102 // the new submodule.
Richard Smithd1386302017-05-04 00:29:54 +00002103 EnterSubmodule(M, HashLoc, /*ForPragma*/false);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002104
Richard Smitha0aafa32015-05-18 03:52:30 +00002105 // Let the parser know that any future declarations are within the new
2106 // submodule.
2107 // FIXME: There's no point doing this if we're handling a #__include_macros
2108 // directive.
Richard Smithc51c38b2017-04-29 00:34:47 +00002109 EnterAnnotationToken(SourceRange(HashLoc, End), tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00002110 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002111}
2112
James Dennettf6333ac2012-06-22 05:46:07 +00002113/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002114///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002115void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2116 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002117 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattnerf64b3522008-03-09 01:54:53 +00002119 // #include_next is like #include, except that we start searching after
2120 // the current found directory. If we can't do this, issue a
2121 // diagnostic.
2122 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002123 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00002124 if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2125 // If the main file is a header, then it's either for PCH/AST generation,
2126 // or libclang opened it. Either way, handle it as a normal include below
2127 // and do not complain about include_next.
2128 } else if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002129 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002130 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smithd1386302017-05-04 00:29:54 +00002131 } else if (CurLexerSubmodule) {
Richard Smith25d50752014-10-20 00:15:49 +00002132 // Start looking up in the directory *after* the one in which the current
2133 // file would be found, if any.
2134 assert(CurPPLexer && "#include_next directive in macro?");
2135 LookupFromFile = CurPPLexer->getFileEntry();
2136 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002137 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002138 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2139 } else {
2140 // Start looking up in the next directory.
2141 ++Lookup;
2142 }
Mike Stump11289f42009-09-09 15:08:12 +00002143
Richard Smith25d50752014-10-20 00:15:49 +00002144 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2145 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002146}
2147
James Dennettf6333ac2012-06-22 05:46:07 +00002148/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002149void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2150 // The Microsoft #import directive takes a type library and generates header
2151 // files from it, and includes those. This is beyond the scope of what clang
2152 // does, so we ignore it and error out. However, #import can optionally have
2153 // trailing attributes that span multiple lines. We're going to eat those
2154 // so we can continue processing from there.
2155 Diag(Tok, diag::err_pp_import_directive_ms );
2156
Taewook Oh755e4d22016-06-13 21:55:33 +00002157 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002158 // directive can be split over multiple lines using the backslash character.
2159 DiscardUntilEndOfDirective();
2160}
2161
James Dennettf6333ac2012-06-22 05:46:07 +00002162/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002163///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002164void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2165 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00002166 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002167 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002168 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002169 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002170 }
Richard Smith25d50752014-10-20 00:15:49 +00002171 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002172}
2173
Chris Lattner58a1eb02009-04-08 18:46:40 +00002174/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2175/// pseudo directive in the predefines buffer. This handles it by sucking all
2176/// tokens through the preprocessor and discarding them (only keeping the side
2177/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002178void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2179 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002180 // This directive should only occur in the predefines buffer. If not, emit an
2181 // error and reject it.
2182 SourceLocation Loc = IncludeMacrosTok.getLocation();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002183 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002184 Diag(IncludeMacrosTok.getLocation(),
2185 diag::pp_include_macros_out_of_predefines);
2186 DiscardUntilEndOfDirective();
2187 return;
2188 }
Mike Stump11289f42009-09-09 15:08:12 +00002189
Chris Lattnere01d82b2009-04-08 20:53:24 +00002190 // Treat this as a normal #include for checking purposes. If this is
2191 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002192 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002193
Chris Lattnere01d82b2009-04-08 20:53:24 +00002194 Token TmpTok;
2195 do {
2196 Lex(TmpTok);
2197 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2198 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002199}
2200
Chris Lattnerf64b3522008-03-09 01:54:53 +00002201//===----------------------------------------------------------------------===//
2202// Preprocessor Macro Directive Handling.
2203//===----------------------------------------------------------------------===//
2204
Faisal Valie8f430a2017-09-29 02:43:22 +00002205/// ReadMacroParameterList - The ( starting a parameter list of a macro
2206/// definition has just been read. Lex the rest of the parameters and the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002207/// closing ), updating MI with what we learn. Return true if an error occurs
Faisal Valie8f430a2017-09-29 02:43:22 +00002208/// parsing the param list.
Faisal Valiac506d72017-07-17 17:18:43 +00002209bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
Faisal Vali33df3912017-09-29 02:17:31 +00002210 SmallVector<IdentifierInfo*, 32> Parameters;
Mike Stump11289f42009-09-09 15:08:12 +00002211
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002212 while (true) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002213 LexUnexpandedToken(Tok);
2214 switch (Tok.getKind()) {
2215 case tok::r_paren:
Faisal Valie8f430a2017-09-29 02:43:22 +00002216 // Found the end of the parameter list.
Faisal Vali33df3912017-09-29 02:17:31 +00002217 if (Parameters.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002218 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002219 // Otherwise we have #define FOO(A,)
2220 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2221 return true;
2222 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002223 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002224 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002225 diag::warn_cxx98_compat_variadic_macro :
2226 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002227
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002228 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2229 if (LangOpts.OpenCL) {
2230 Diag(Tok, diag::err_pp_opencl_variadic_macros);
2231 return true;
2232 }
2233
Chris Lattnerf64b3522008-03-09 01:54:53 +00002234 // Lex the token after the identifier.
2235 LexUnexpandedToken(Tok);
2236 if (Tok.isNot(tok::r_paren)) {
2237 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2238 return true;
2239 }
Faisal Valie8f430a2017-09-29 02:43:22 +00002240 // Add the __VA_ARGS__ identifier as a parameter.
Faisal Vali33df3912017-09-29 02:17:31 +00002241 Parameters.push_back(Ident__VA_ARGS__);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002242 MI->setIsC99Varargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002243 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002244 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002245 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002246 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2247 return true;
2248 default:
2249 // Handle keywords and identifiers here to accept things like
2250 // #define Foo(for) for.
2251 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002252 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002253 // #define X(1
2254 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2255 return true;
2256 }
2257
Faisal Valie8f430a2017-09-29 02:43:22 +00002258 // If this is already used as a parameter, it is used multiple times (e.g.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002259 // #define X(A,A.
Faisal Vali33df3912017-09-29 02:17:31 +00002260 if (std::find(Parameters.begin(), Parameters.end(), II) !=
2261 Parameters.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002262 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002263 return true;
2264 }
Mike Stump11289f42009-09-09 15:08:12 +00002265
Faisal Valie8f430a2017-09-29 02:43:22 +00002266 // Add the parameter to the macro info.
Faisal Vali33df3912017-09-29 02:17:31 +00002267 Parameters.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattnerf64b3522008-03-09 01:54:53 +00002269 // Lex the token after the identifier.
2270 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002271
Chris Lattnerf64b3522008-03-09 01:54:53 +00002272 switch (Tok.getKind()) {
2273 default: // #define X(A B
2274 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2275 return true;
2276 case tok::r_paren: // #define X(A)
Faisal Vali33df3912017-09-29 02:17:31 +00002277 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002278 return false;
2279 case tok::comma: // #define X(A,
2280 break;
2281 case tok::ellipsis: // #define X(A... -> GCC extension
2282 // Diagnose extension.
2283 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002284
Chris Lattnerf64b3522008-03-09 01:54:53 +00002285 // Lex the token after the identifier.
2286 LexUnexpandedToken(Tok);
2287 if (Tok.isNot(tok::r_paren)) {
2288 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2289 return true;
2290 }
Mike Stump11289f42009-09-09 15:08:12 +00002291
Chris Lattnerf64b3522008-03-09 01:54:53 +00002292 MI->setIsGNUVarargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002293 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002294 return false;
2295 }
2296 }
2297 }
2298}
2299
Serge Pavlov07c0f042014-12-18 11:14:21 +00002300static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2301 const LangOptions &LOptions) {
2302 if (MI->getNumTokens() == 1) {
2303 const Token &Value = MI->getReplacementToken(0);
2304
2305 // Macro that is identity, like '#define inline inline' is a valid pattern.
2306 if (MacroName.getKind() == Value.getKind())
2307 return true;
2308
2309 // Macro that maps a keyword to the same keyword decorated with leading/
2310 // trailing underscores is a valid pattern:
2311 // #define inline __inline
2312 // #define inline __inline__
2313 // #define inline _inline (in MS compatibility mode)
2314 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2315 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2316 if (!II->isKeyword(LOptions))
2317 return false;
2318 StringRef ValueText = II->getName();
2319 StringRef TrimmedValue = ValueText;
2320 if (!ValueText.startswith("__")) {
2321 if (ValueText.startswith("_"))
2322 TrimmedValue = TrimmedValue.drop_front(1);
2323 else
2324 return false;
2325 } else {
2326 TrimmedValue = TrimmedValue.drop_front(2);
2327 if (TrimmedValue.endswith("__"))
2328 TrimmedValue = TrimmedValue.drop_back(2);
2329 }
2330 return TrimmedValue.equals(MacroText);
2331 } else {
2332 return false;
2333 }
2334 }
2335
2336 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002337 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2338 tok::kw_const) &&
2339 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002340}
2341
Faisal Valiac506d72017-07-17 17:18:43 +00002342// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2343// entire line) of the macro's tokens and adds them to MacroInfo, and while
2344// doing so performs certain validity checks including (but not limited to):
2345// - # (stringization) is followed by a macro parameter
2346//
2347// Returns a nullptr if an invalid sequence of tokens is encountered or returns
2348// a pointer to a MacroInfo object.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002349
Faisal Valiac506d72017-07-17 17:18:43 +00002350MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2351 const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002352
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002353 Token LastTok = MacroNameTok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002354 // Create the new macro.
Faisal Valiac506d72017-07-17 17:18:43 +00002355 MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002356
Chris Lattnerf64b3522008-03-09 01:54:53 +00002357 Token Tok;
2358 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002359
Faisal Vali6bf67912017-07-25 03:15:36 +00002360 // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2361 // within their appropriate context.
2362 VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2363
Chris Lattnerf64b3522008-03-09 01:54:53 +00002364 // If this is a function-like macro definition, parse the argument list,
2365 // marking each of the identifiers as being used as macro arguments. Also,
2366 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002367 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002368 if (ImmediatelyAfterHeaderGuard) {
2369 // Save this macro information since it may part of a header guard.
2370 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2371 MacroNameTok.getLocation());
2372 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002373 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002374 } else if (Tok.hasLeadingSpace()) {
2375 // This is a normal token with leading space. Clear the leading space
2376 // marker on the first token to get proper expansion.
2377 Tok.clearFlag(Token::LeadingSpace);
2378 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002379 // This is a function-like macro definition. Read the argument list.
2380 MI->setIsFunctionLike();
Faisal Valiac506d72017-07-17 17:18:43 +00002381 if (ReadMacroParameterList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002382 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002383 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002384 DiscardUntilEndOfDirective();
Faisal Valiac506d72017-07-17 17:18:43 +00002385 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002386 }
2387
Faisal Vali6bf67912017-07-25 03:15:36 +00002388 // If this is a definition of an ISO C/C++ variadic function-like macro (not
2389 // using the GNU named varargs extension) inform our variadic scope guard
2390 // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2391 // allowed only within the definition of a variadic macro.
Mike Stump11289f42009-09-09 15:08:12 +00002392
Faisal Vali6bf67912017-07-25 03:15:36 +00002393 if (MI->isC99Varargs()) {
2394 VariadicMacroScopeGuard.enterScope();
2395 }
Mike Stump11289f42009-09-09 15:08:12 +00002396
Chris Lattnerf64b3522008-03-09 01:54:53 +00002397 // Read the first token after the arg list for down below.
2398 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002399 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002400 // C99 requires whitespace between the macro definition and the body. Emit
2401 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002402 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002403 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002404 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2405 // first character of a replacement list is not a character required by
2406 // subclause 5.2.1, then there shall be white-space separation between the
2407 // identifier and the replacement list.". 5.2.1 lists this set:
2408 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2409 // is irrelevant here.
2410 bool isInvalid = false;
2411 if (Tok.is(tok::at)) // @ is not in the list above.
2412 isInvalid = true;
2413 else if (Tok.is(tok::unknown)) {
2414 // If we have an unknown token, it is something strange like "`". Since
2415 // all of valid characters would have lexed into a single character
2416 // token of some sort, we know this is not a valid case.
2417 isInvalid = true;
2418 }
2419 if (isInvalid)
2420 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2421 else
2422 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002423 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002424
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002425 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002426 LastTok = Tok;
2427
Chris Lattnerf64b3522008-03-09 01:54:53 +00002428 // Read the rest of the macro body.
2429 if (MI->isObjectLike()) {
2430 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002431 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002432 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002433 MI->AddTokenToBody(Tok);
2434 // Get the next token of the macro.
2435 LexUnexpandedToken(Tok);
2436 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002437 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002438 // Otherwise, read the body of a function-like macro. While we are at it,
2439 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2440 // parameters in function-like macro expansions.
Faisal Vali18268422017-10-15 01:26:26 +00002441
2442 VAOptDefinitionContext VAOCtx(*this);
2443
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002444 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002445 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002446
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002447 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002448 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002449
Faisal Vali18268422017-10-15 01:26:26 +00002450 if (VAOCtx.isVAOptToken(Tok)) {
2451 // If we're already within a VAOPT, emit an error.
2452 if (VAOCtx.isInVAOpt()) {
2453 Diag(Tok, diag::err_pp_vaopt_nested_use);
2454 return nullptr;
2455 }
2456 // Ensure VAOPT is followed by a '(' .
2457 LexUnexpandedToken(Tok);
2458 if (Tok.isNot(tok::l_paren)) {
2459 Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
2460 return nullptr;
2461 }
2462 MI->AddTokenToBody(Tok);
2463 VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
2464 LexUnexpandedToken(Tok);
2465 if (Tok.is(tok::hashhash)) {
2466 Diag(Tok, diag::err_vaopt_paste_at_start);
2467 return nullptr;
2468 }
2469 continue;
2470 } else if (VAOCtx.isInVAOpt()) {
2471 if (Tok.is(tok::r_paren)) {
2472 if (VAOCtx.sawClosingParen()) {
2473 const unsigned NumTokens = MI->getNumTokens();
2474 assert(NumTokens >= 3 && "Must have seen at least __VA_OPT__( "
2475 "and a subsequent tok::r_paren");
2476 if (MI->getReplacementToken(NumTokens - 2).is(tok::hashhash)) {
2477 Diag(Tok, diag::err_vaopt_paste_at_end);
2478 return nullptr;
2479 }
2480 }
2481 } else if (Tok.is(tok::l_paren)) {
2482 VAOCtx.sawOpeningParen(Tok.getLocation());
2483 }
2484 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002485 // Get the next token of the macro.
2486 LexUnexpandedToken(Tok);
2487 continue;
2488 }
Mike Stump11289f42009-09-09 15:08:12 +00002489
Richard Smith701a3522013-07-09 01:00:29 +00002490 // If we're in -traditional mode, then we should ignore stringification
2491 // and token pasting. Mark the tokens as unknown so as not to confuse
2492 // things.
2493 if (getLangOpts().TraditionalCPP) {
2494 Tok.setKind(tok::unknown);
2495 MI->AddTokenToBody(Tok);
2496
2497 // Get the next token of the macro.
2498 LexUnexpandedToken(Tok);
2499 continue;
2500 }
2501
Eli Friedman14d3c792012-11-14 02:18:46 +00002502 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002503 // If we see token pasting, check if it looks like the gcc comma
2504 // pasting extension. We'll use this information to suppress
2505 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002506
Eli Friedman14d3c792012-11-14 02:18:46 +00002507 // Get the next token of the macro.
2508 LexUnexpandedToken(Tok);
2509
2510 if (Tok.is(tok::eod)) {
2511 MI->AddTokenToBody(LastTok);
2512 break;
2513 }
2514
2515 unsigned NumTokens = MI->getNumTokens();
2516 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2517 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2518 MI->setHasCommaPasting();
2519
David Majnemer76faf1f2013-11-05 09:30:17 +00002520 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002521 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002522 continue;
2523 }
2524
Faisal Vali18268422017-10-15 01:26:26 +00002525 // Our Token is a stringization operator.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002526 // Get the next token of the macro.
2527 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002528
Faisal Vali18268422017-10-15 01:26:26 +00002529 // Check for a valid macro arg identifier or __VA_OPT__.
2530 if (!VAOCtx.isVAOptToken(Tok) &&
2531 (Tok.getIdentifierInfo() == nullptr ||
2532 MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002533
2534 // If this is assembler-with-cpp mode, we accept random gibberish after
2535 // the '#' because '#' is often a comment character. However, change
2536 // the kind of the token to tok::unknown so that the preprocessor isn't
2537 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002538 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002539 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002540 MI->AddTokenToBody(LastTok);
2541 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002542 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002543 Diag(Tok, diag::err_pp_stringize_not_parameter)
2544 << LastTok.is(tok::hashat);
Faisal Valiac506d72017-07-17 17:18:43 +00002545 return nullptr;
Chris Lattner83bd8282009-05-25 17:16:10 +00002546 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002547 }
Mike Stump11289f42009-09-09 15:08:12 +00002548
Chris Lattner83bd8282009-05-25 17:16:10 +00002549 // Things look ok, add the '#' and param name tokens to the macro.
2550 MI->AddTokenToBody(LastTok);
Mike Stump11289f42009-09-09 15:08:12 +00002551
Faisal Vali18268422017-10-15 01:26:26 +00002552 // If the token following '#' is VAOPT, let the next iteration handle it
2553 // and check it for correctness, otherwise add the token and prime the
2554 // loop with the next one.
2555 if (!VAOCtx.isVAOptToken(Tok)) {
2556 MI->AddTokenToBody(Tok);
2557 LastTok = Tok;
2558
2559 // Get the next token of the macro.
2560 LexUnexpandedToken(Tok);
2561 }
2562 }
2563 if (VAOCtx.isInVAOpt()) {
2564 assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
2565 Diag(Tok, diag::err_pp_expected_after)
2566 << LastTok.getKind() << tok::r_paren;
2567 Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
2568 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002569 }
2570 }
Faisal Valiac506d72017-07-17 17:18:43 +00002571 MI->setDefinitionEndLoc(LastTok.getLocation());
Faisal Valiac506d72017-07-17 17:18:43 +00002572 return MI;
2573}
2574/// HandleDefineDirective - Implements \#define. This consumes the entire macro
2575/// line then lets the caller lex the next real token.
2576void Preprocessor::HandleDefineDirective(
2577 Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2578 ++NumDefined;
2579
2580 Token MacroNameTok;
2581 bool MacroShadowsKeyword;
2582 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2583
2584 // Error reading macro name? If so, diagnostic already issued.
2585 if (MacroNameTok.is(tok::eod))
2586 return;
2587
2588 // If we are supposed to keep comments in #defines, reenable comment saving
2589 // mode.
2590 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2591
2592 MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2593 MacroNameTok, ImmediatelyAfterHeaderGuard);
2594
2595 if (!MI) return;
Mike Stump11289f42009-09-09 15:08:12 +00002596
Serge Pavlov07c0f042014-12-18 11:14:21 +00002597 if (MacroShadowsKeyword &&
2598 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2599 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
Faisal Valiac506d72017-07-17 17:18:43 +00002600 }
Chris Lattner57540c52011-04-15 05:22:18 +00002601 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002602 // replacement list.
2603 unsigned NumTokens = MI->getNumTokens();
2604 if (NumTokens != 0) {
2605 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2606 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002607 return;
2608 }
2609 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2610 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002611 return;
2612 }
2613 }
Mike Stump11289f42009-09-09 15:08:12 +00002614
Erich Keane76675de2018-07-05 17:22:13 +00002615 // When skipping just warn about macros that do not match.
2616 if (SkippingUntilPCHThroughHeader) {
2617 const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
2618 if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
2619 /*Syntactic=*/LangOpts.MicrosoftExt))
2620 Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
2621 << MacroNameTok.getIdentifierInfo();
2622 return;
2623 }
Mike Stump11289f42009-09-09 15:08:12 +00002624
Chris Lattnerf64b3522008-03-09 01:54:53 +00002625 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002626 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002627 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002628 // In Objective-C, ignore attempts to directly redefine the builtin
2629 // definitions of the ownership qualifiers. It's still possible to
2630 // #undef them.
2631 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2632 return II->isStr("__strong") ||
2633 II->isStr("__weak") ||
2634 II->isStr("__unsafe_unretained") ||
2635 II->isStr("__autoreleasing");
2636 };
2637 if (getLangOpts().ObjC1 &&
2638 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2639 == getPredefinesFileID() &&
2640 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2641 // Warn if it changes the tokens.
2642 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2643 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2644 !MI->isIdenticalTo(*OtherMI, *this,
2645 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2646 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2647 }
2648 assert(!OtherMI->isWarnIfUnused());
2649 return;
2650 }
2651
Chris Lattner5244f342009-01-16 19:50:11 +00002652 // It is very common for system headers to have tons of macro redefinitions
2653 // and for warnings to be disabled in system headers. If this is the case,
2654 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002655 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002656 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002657 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002658 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002659
Taewook Oh755e4d22016-06-13 21:55:33 +00002660 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002661 // C++ [cpp.predefined]p4, but allow it as an extension.
2662 if (OtherMI->isBuiltinMacro())
2663 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002664 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002665 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002666 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002667 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002668 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2669 << MacroNameTok.getIdentifierInfo();
2670 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2671 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002672 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002673 if (OtherMI->isWarnIfUnused())
2674 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002675 }
Mike Stump11289f42009-09-09 15:08:12 +00002676
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002677 DefMacroDirective *MD =
2678 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002679
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002680 assert(!MI->isUsed());
2681 // If we need warning for not using the macro, add its location in the
2682 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002683 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002684 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002685 MI->setIsWarnIfUnused(true);
2686 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2687 }
2688
Chris Lattner928e9092009-04-12 01:39:54 +00002689 // If the callbacks want to know, tell them about the macro definition.
2690 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002691 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002692}
2693
James Dennettf6333ac2012-06-22 05:46:07 +00002694/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002695///
Erik Verbruggen4bddef92016-10-26 08:52:41 +00002696void Preprocessor::HandleUndefDirective() {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002697 ++NumUndefined;
2698
2699 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002700 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002701
Chris Lattnerf64b3522008-03-09 01:54:53 +00002702 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002703 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002704 return;
Mike Stump11289f42009-09-09 15:08:12 +00002705
Chris Lattnerf64b3522008-03-09 01:54:53 +00002706 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002707 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002708
Richard Smith20e883e2015-04-29 23:20:19 +00002709 // Okay, we have a valid identifier to undef.
2710 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002711 auto MD = getMacroDefinition(II);
Vedant Kumar349a6242017-04-26 21:05:44 +00002712 UndefMacroDirective *Undef = nullptr;
2713
2714 // If the macro is not defined, this is a noop undef.
2715 if (const MacroInfo *MI = MD.getMacroInfo()) {
2716 if (!MI->isUsed() && MI->isWarnIfUnused())
2717 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2718
2719 if (MI->isWarnIfUnused())
2720 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2721
2722 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
2723 }
Mike Stump11289f42009-09-09 15:08:12 +00002724
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002725 // If the callbacks want to know, tell them about the macro #undef.
2726 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002727 if (Callbacks)
Vedant Kumar349a6242017-04-26 21:05:44 +00002728 Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002729
Vedant Kumar349a6242017-04-26 21:05:44 +00002730 if (Undef)
2731 appendMacroDirective(II, Undef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002732}
2733
Chris Lattnerf64b3522008-03-09 01:54:53 +00002734//===----------------------------------------------------------------------===//
2735// Preprocessor Conditional Directive Handling.
2736//===----------------------------------------------------------------------===//
2737
James Dennettf6333ac2012-06-22 05:46:07 +00002738/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2739/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2740/// true if any tokens have been returned or pp-directives activated before this
2741/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002742///
Vedant Kumar3919a502017-09-11 20:47:42 +00002743void Preprocessor::HandleIfdefDirective(Token &Result,
2744 const Token &HashToken,
2745 bool isIfndef,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002746 bool ReadAnyTokensBeforeDirective) {
2747 ++NumIf;
2748 Token DirectiveTok = Result;
2749
2750 Token MacroNameTok;
2751 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002752
Chris Lattnerf64b3522008-03-09 01:54:53 +00002753 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002754 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002755 // Skip code until we get to #endif. This helps with recovery by not
2756 // emitting an error when the #endif is reached.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002757 SkipExcludedConditionalBlock(HashToken.getLocation(),
2758 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002759 /*Foundnonskip*/ false, /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002760 return;
2761 }
Mike Stump11289f42009-09-09 15:08:12 +00002762
Chris Lattnerf64b3522008-03-09 01:54:53 +00002763 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002764 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002765
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002766 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002767 auto MD = getMacroDefinition(MII);
2768 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002769
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002770 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002771 // If the start of a top-level #ifdef and if the macro is not defined,
2772 // inform MIOpt that this might be the start of a proper include guard.
2773 // Otherwise it is some other form of unknown conditional which we can't
2774 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002775 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002776 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002777 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002778 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002779 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002780 }
2781
Chris Lattnerf64b3522008-03-09 01:54:53 +00002782 // If there is a macro, process it.
2783 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002784 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002785
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002786 if (Callbacks) {
2787 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002788 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002789 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002790 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002791 }
2792
Chris Lattnerf64b3522008-03-09 01:54:53 +00002793 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002794 if (PPOpts->SingleFileParseMode && !MI) {
2795 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2796 // the directive blocks.
2797 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002798 /*wasskip*/false, /*foundnonskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002799 /*foundelse*/false);
2800 } else if (!MI == isIfndef) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002801 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002802 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2803 /*wasskip*/false, /*foundnonskip*/true,
2804 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002805 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002806 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002807 SkipExcludedConditionalBlock(HashToken.getLocation(),
2808 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002809 /*Foundnonskip*/ false,
2810 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002811 }
2812}
2813
James Dennettf6333ac2012-06-22 05:46:07 +00002814/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002815///
2816void Preprocessor::HandleIfDirective(Token &IfToken,
Vedant Kumar3919a502017-09-11 20:47:42 +00002817 const Token &HashToken,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002818 bool ReadAnyTokensBeforeDirective) {
2819 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002820
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002821 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002822 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002823 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002824 const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
2825 const bool ConditionalTrue = DER.Conditional;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002826 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002827
2828 // If this condition is equivalent to #ifndef X, and if this is the first
2829 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002830 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002831 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002832 // FIXME: Pass in the location of the macro name, not the 'if' token.
2833 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002834 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002835 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002836 }
2837
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002838 if (Callbacks)
2839 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002840 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002841 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002842
Chris Lattnerf64b3522008-03-09 01:54:53 +00002843 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002844 if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
2845 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2846 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002847 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002848 /*foundnonskip*/false, /*foundelse*/false);
2849 } else if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002850 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002851 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002852 /*foundnonskip*/true, /*foundelse*/false);
2853 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002854 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002855 SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002856 /*Foundnonskip*/ false,
2857 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002858 }
2859}
2860
James Dennettf6333ac2012-06-22 05:46:07 +00002861/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002862///
2863void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2864 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002865
Chris Lattnerf64b3522008-03-09 01:54:53 +00002866 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002867 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002868
Chris Lattnerf64b3522008-03-09 01:54:53 +00002869 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002870 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002871 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002872 Diag(EndifToken, diag::err_pp_endif_without_if);
2873 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002874 }
Mike Stump11289f42009-09-09 15:08:12 +00002875
Chris Lattnerf64b3522008-03-09 01:54:53 +00002876 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002877 if (CurPPLexer->getConditionalStackDepth() == 0)
2878 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002879
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002880 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002881 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002882
2883 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002884 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002885}
2886
James Dennettf6333ac2012-06-22 05:46:07 +00002887/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002888///
Vedant Kumar3919a502017-09-11 20:47:42 +00002889void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002890 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002891
Chris Lattnerf64b3522008-03-09 01:54:53 +00002892 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002893 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002894
Chris Lattnerf64b3522008-03-09 01:54:53 +00002895 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002896 if (CurPPLexer->popConditionalLevel(CI)) {
2897 Diag(Result, diag::pp_err_else_without_if);
2898 return;
2899 }
Mike Stump11289f42009-09-09 15:08:12 +00002900
Chris Lattnerf64b3522008-03-09 01:54:53 +00002901 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002902 if (CurPPLexer->getConditionalStackDepth() == 0)
2903 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002904
2905 // If this is a #else with a #else before it, report the error.
2906 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002907
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002908 if (Callbacks)
2909 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2910
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002911 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002912 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2913 // the directive blocks.
2914 CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002915 /*foundnonskip*/false, /*foundelse*/true);
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002916 return;
2917 }
2918
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002919 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002920 SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
2921 /*Foundnonskip*/ true,
Vedant Kumar3919a502017-09-11 20:47:42 +00002922 /*FoundElse*/ true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002923}
2924
James Dennettf6333ac2012-06-22 05:46:07 +00002925/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002926///
Vedant Kumar3919a502017-09-11 20:47:42 +00002927void Preprocessor::HandleElifDirective(Token &ElifToken,
2928 const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002929 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002930
Chris Lattnerf64b3522008-03-09 01:54:53 +00002931 // #elif directive in a non-skipping conditional... start skipping.
2932 // We don't care what the condition is, because we will always skip it (since
2933 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002934 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002935 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002936 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002937
2938 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002939 if (CurPPLexer->popConditionalLevel(CI)) {
2940 Diag(ElifToken, diag::pp_err_elif_without_if);
2941 return;
2942 }
Mike Stump11289f42009-09-09 15:08:12 +00002943
Chris Lattnerf64b3522008-03-09 01:54:53 +00002944 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002945 if (CurPPLexer->getConditionalStackDepth() == 0)
2946 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002947
Chris Lattnerf64b3522008-03-09 01:54:53 +00002948 // If this is a #elif with a #else before it, report the error.
2949 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Taewook Oh755e4d22016-06-13 21:55:33 +00002950
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002951 if (Callbacks)
2952 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002953 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002954 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002955
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002956 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002957 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2958 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002959 CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002960 /*foundnonskip*/false, /*foundelse*/false);
2961 return;
2962 }
2963
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002964 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002965 SkipExcludedConditionalBlock(
2966 HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
2967 /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002968}