blob: 405d19bb28532565385644cc3b5580cca42b0914 [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
11/// \brief Implements # directive processing for the Preprocessor.
12///
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
James Dennettf6333ac2012-06-22 05:46:07 +000081/// \brief 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
Serge Pavlov07c0f042014-12-18 11:14:21 +000091/// \brief Enumerates possible cases of #define/#undef a reserved identifier.
92enum 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
98/// \brief Checks if the specified identifier is reserved in the specified
99/// 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
Serge Pavlov07c0f042014-12-18 11:14:21 +0000118static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
119 const LangOptions &Lang = PP.getLangOpts();
120 StringRef Text = II->getName();
121 if (isReservedId(Text, Lang))
122 return MD_ReservedMacro;
123 if (II->isKeyword(Lang))
124 return MD_KeywordDef;
125 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
126 return MD_KeywordDef;
127 return MD_NoWarn;
128}
129
130static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
131 const LangOptions &Lang = PP.getLangOpts();
132 StringRef Text = II->getName();
133 // Do not warn on keyword undef. It is generally harmless and widely used.
134 if (isReservedId(Text, Lang))
135 return MD_ReservedMacro;
136 return MD_NoWarn;
137}
138
Taewook Ohf42103c2016-06-13 20:40:21 +0000139// Return true if we want to issue a diagnostic by default if we
140// encounter this name in a #include with the wrong case. For now,
141// this includes the standard C and C++ headers, Posix headers,
142// and Boost headers. Improper case for these #includes is a
143// potential portability issue.
144static bool warnByDefaultOnWrongCase(StringRef Include) {
145 // If the first component of the path is "boost", treat this like a standard header
146 // for the purposes of diagnostics.
147 if (::llvm::sys::path::begin(Include)->equals_lower("boost"))
148 return true;
149
150 // "condition_variable" is the longest standard header name at 18 characters.
151 // If the include file name is longer than that, it can't be a standard header.
Taewook Oh755e4d22016-06-13 21:55:33 +0000152 static const size_t MaxStdHeaderNameLen = 18u;
Taewook Ohf42103c2016-06-13 20:40:21 +0000153 if (Include.size() > MaxStdHeaderNameLen)
154 return false;
155
156 // Lowercase and normalize the search string.
157 SmallString<32> LowerInclude{Include};
158 for (char &Ch : LowerInclude) {
159 // In the ASCII range?
George Burgess IV5d3bd932016-06-16 02:30:33 +0000160 if (static_cast<unsigned char>(Ch) > 0x7f)
Taewook Ohf42103c2016-06-13 20:40:21 +0000161 return false; // Can't be a standard header
162 // ASCII lowercase:
163 if (Ch >= 'A' && Ch <= 'Z')
164 Ch += 'a' - 'A';
165 // Normalize path separators for comparison purposes.
166 else if (::llvm::sys::path::is_separator(Ch))
167 Ch = '/';
168 }
169
170 // The standard C/C++ and Posix headers
171 return llvm::StringSwitch<bool>(LowerInclude)
172 // C library headers
173 .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
174 .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
175 .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
176 .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
177 .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
178 .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
179
180 // C++ headers for C library facilities
181 .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
182 .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
183 .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
184 .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
185 .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
186 .Case("cwctype", true)
187
188 // C++ library headers
189 .Cases("algorithm", "fstream", "list", "regex", "thread", true)
190 .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
191 .Cases("atomic", "future", "map", "set", "type_traits", true)
192 .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
193 .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
194 .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
195 .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
196 .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
197 .Cases("deque", "istream", "queue", "string", "valarray", true)
198 .Cases("exception", "iterator", "random", "strstream", "vector", true)
199 .Cases("forward_list", "limits", "ratio", "system_error", true)
200
201 // POSIX headers (which aren't also C headers)
202 .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
203 .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
204 .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
205 .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
206 .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
207 .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
208 .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
209 .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
210 .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
211 .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
212 .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
213 .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
214 .Default(false);
215}
216
Serge Pavlov07c0f042014-12-18 11:14:21 +0000217bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
218 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000219 // Missing macro name?
220 if (MacroNameTok.is(tok::eod))
221 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
222
223 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Olivier Goffart90f981b2017-07-14 09:23:40 +0000224 if (!II)
225 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000226
Olivier Goffart90f981b2017-07-14 09:23:40 +0000227 if (II->isCPlusPlusOperatorKeyword()) {
Alp Tokere03e9e12014-05-31 16:32:22 +0000228 // C++ 2.5p2: Alternative tokens behave the same as its primary token
229 // except for their spellings.
230 Diag(MacroNameTok, getLangOpts().MicrosoftExt
231 ? diag::ext_pp_operator_used_as_macro_name
232 : diag::err_pp_operator_used_as_macro_name)
233 << II << MacroNameTok.getKind();
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000234 // Allow #defining |and| and friends for Microsoft compatibility or
235 // recovery when legacy C headers are included in C++.
Alp Tokerb05e0b52014-05-21 06:13:51 +0000236 }
237
Serge Pavlovd024f522014-10-24 17:31:32 +0000238 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000239 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
240 return Diag(MacroNameTok, diag::err_defined_macro_name);
241 }
242
Richard Smith20e883e2015-04-29 23:20:19 +0000243 if (isDefineUndef == MU_Undef) {
244 auto *MI = getMacroInfo(II);
245 if (MI && MI->isBuiltinMacro()) {
246 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
247 // and C++ [cpp.predefined]p4], but allow it as an extension.
248 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
249 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000250 }
251
Serge Pavlov07c0f042014-12-18 11:14:21 +0000252 // If defining/undefining reserved identifier or a keyword, we need to issue
253 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000254 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000255 if (ShadowFlag)
256 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000257 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
Mehdi Amini99d1b292016-10-01 16:38:28 +0000258 (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000259 MacroDiag D = MD_NoWarn;
260 if (isDefineUndef == MU_Define) {
261 D = shouldWarnOnMacroDef(*this, II);
262 }
263 else if (isDefineUndef == MU_Undef)
264 D = shouldWarnOnMacroUndef(*this, II);
265 if (D == MD_KeywordDef) {
266 // We do not want to warn on some patterns widely used in configuration
267 // scripts. This requires analyzing next tokens, so do not issue warnings
268 // now, only inform caller.
269 if (ShadowFlag)
270 *ShadowFlag = true;
271 }
272 if (D == MD_ReservedMacro)
273 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000274 }
275
Alp Tokerb05e0b52014-05-21 06:13:51 +0000276 // Okay, we got a good identifier.
277 return false;
278}
279
James Dennettf6333ac2012-06-22 05:46:07 +0000280/// \brief Lex and validate a macro name, which occurs after a
281/// \#define or \#undef.
282///
Serge Pavlovd024f522014-10-24 17:31:32 +0000283/// This sets the token kind to eod and discards the rest of the macro line if
284/// the macro name is invalid.
285///
286/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000287/// \param isDefineUndef Context in which macro is used.
288/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
289void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
290 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000291 // Read the token, don't allow macro expansion on it.
292 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000293
Douglas Gregor12785102010-08-24 20:21:13 +0000294 if (MacroNameTok.is(tok::code_completion)) {
295 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000296 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000297 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000298 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000299 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000300
Serge Pavlov07c0f042014-12-18 11:14:21 +0000301 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000302 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000303
304 // Invalid macro name, read and discard the rest of the line and set the
305 // token kind to tok::eod if necessary.
306 if (MacroNameTok.isNot(tok::eod)) {
307 MacroNameTok.setKind(tok::eod);
308 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000309 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000310}
311
James Dennettf6333ac2012-06-22 05:46:07 +0000312/// \brief Ensure that the next token is a tok::eod token.
313///
314/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000315/// true, then we consider macros that expand to zero tokens as being ok.
316void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000317 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000318 // Lex unexpanded tokens for most directives: macros might expand to zero
319 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
320 // #line) allow empty macros.
321 if (EnableMacros)
322 Lex(Tmp);
323 else
324 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattnerf64b3522008-03-09 01:54:53 +0000326 // There should be no tokens after the directive, but we allow them as an
327 // extension.
328 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
329 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000330
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000331 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000332 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000333 // or if this is a macro-style preprocessing directive, because it is more
334 // trouble than it is worth to insert /**/ and check that there is no /**/
335 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000336 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000337 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000338 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000339 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
340 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000341 DiscardUntilEndOfDirective();
342 }
343}
344
James Dennettf6333ac2012-06-22 05:46:07 +0000345/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
346/// decided that the subsequent tokens are in the \#if'd out portion of the
347/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000348/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000349/// this \#if directive, so \#else/\#elif blocks should never be entered.
350/// If ElseOk is true, then \#else directives are ok, if not, then we have
351/// already seen one so a \#else directive is a duplicate. When this returns,
352/// the caller can lex the first valid token.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000353void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
Vedant Kumar3919a502017-09-11 20:47:42 +0000354 SourceLocation IfTokenLoc,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000355 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000356 bool FoundElse,
357 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000358 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000359 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000360
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000361 if (PreambleConditionalStack.reachedEOFWhileSkipping())
362 PreambleConditionalStack.clearSkipInfo();
363 else
364 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
365 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000366
Ted Kremenek56572ab2008-12-12 18:34:08 +0000367 if (CurPTHLexer) {
368 PTHSkipExcludedConditionalBlock();
369 return;
370 }
Mike Stump11289f42009-09-09 15:08:12 +0000371
Chris Lattnerf64b3522008-03-09 01:54:53 +0000372 // Enter raw mode to disable identifier lookup (and thus macro expansion),
373 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000374 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000375 Token Tok;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000376 while (true) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000377 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000378
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000379 if (Tok.is(tok::code_completion)) {
380 if (CodeComplete)
381 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000382 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000383 continue;
384 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000385
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 // If this is the end of the buffer, we have an error.
387 if (Tok.is(tok::eof)) {
Ilya Biryukov8f738ac2017-09-12 08:35:57 +0000388 // We don't emit errors for unterminated conditionals here,
389 // Lexer::LexEndOfFile can do that propertly.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000390 // Just return and let the caller lex after this #include.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000391 if (PreambleConditionalStack.isRecording())
392 PreambleConditionalStack.SkipInfo.emplace(
393 HashTokenLoc, IfTokenLoc, FoundNonSkipPortion, FoundElse, ElseLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000394 break;
395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattnerf64b3522008-03-09 01:54:53 +0000397 // If this token is not a preprocessor directive, just skip it.
398 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
399 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattnerf64b3522008-03-09 01:54:53 +0000401 // We just parsed a # character at the start of a line, so we're in
402 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000403 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000404 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000405 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000406
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattnerf64b3522008-03-09 01:54:53 +0000408 // Read the next token, the directive flavor.
409 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000410
Chris Lattnerf64b3522008-03-09 01:54:53 +0000411 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
412 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000413 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000414 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000415 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000416 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000417 continue;
418 }
419
420 // If the first letter isn't i or e, it isn't intesting to us. We know that
421 // this is safe in the face of spelling differences, because there is no way
422 // to spell an i/e in a strange way that is another letter. Skipping this
423 // allows us to avoid looking up the identifier info for #define/#undef and
424 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000425 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000426
Alp Toker2d57cea2014-05-17 04:53:25 +0000427 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000428 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000429 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000430 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000431 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000432 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000433 continue;
434 }
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattnerf64b3522008-03-09 01:54:53 +0000436 // Get the identifier name without trigraphs or embedded newlines. Note
437 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
438 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000439 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000440 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000441 if (!Tok.needsCleaning() && RI.size() < 20) {
442 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000443 } else {
444 std::string DirectiveStr = getSpelling(Tok);
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000445 size_t IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000446 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000447 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000448 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000449 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000450 continue;
451 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000452 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000453 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000454 }
Mike Stump11289f42009-09-09 15:08:12 +0000455
Benjamin Kramer144884642009-12-31 13:32:38 +0000456 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000457 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000458 if (Sub.empty() || // "if"
459 Sub == "def" || // "ifdef"
460 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000461 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
462 // bother parsing the condition.
463 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000464 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000465 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000466 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000467 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000468 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000469 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000470 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000471 PPConditionalInfo CondInfo;
472 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000473 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000474 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000475 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000476
Chris Lattnerf64b3522008-03-09 01:54:53 +0000477 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000478 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000479 // Restore the value of LexingRawMode so that trailing comments
480 // are handled correctly, if we've reached the outermost block.
481 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000482 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000483 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000484 if (Callbacks)
485 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000486 break;
Richard Smithd0124572012-06-21 00:35:03 +0000487 } else {
488 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000489 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000490 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000491 // #else directive in a skipping conditional. If not in some other
492 // skipping conditional, and if #else hasn't already been seen, enter it
493 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000494 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattnerf64b3522008-03-09 01:54:53 +0000496 // If this is a #else with a #else before it, report the error.
497 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattnerf64b3522008-03-09 01:54:53 +0000499 // Note that we've seen a #else in this conditional.
500 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000501
Chris Lattnerf64b3522008-03-09 01:54:53 +0000502 // If the conditional is at the top level, and the #if block wasn't
503 // entered, enter the #else block now.
504 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
505 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000506 // Restore the value of LexingRawMode so that trailing comments
507 // are handled correctly.
508 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000509 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000510 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000511 if (Callbacks)
512 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000513 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000514 } else {
515 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000516 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000517 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000518 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000519
John Thompson17c35732013-12-04 20:19:30 +0000520 // If this is a #elif with a #else before it, report the error.
521 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
522
Chris Lattnerf64b3522008-03-09 01:54:53 +0000523 // If this is in a skipping block or if we're already handled this #if
524 // block, don't bother parsing the condition.
525 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
526 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000527 } else {
John Thompson17c35732013-12-04 20:19:30 +0000528 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000529 // Restore the value of LexingRawMode so that identifiers are
530 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000531 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
532 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000533 IdentifierInfo *IfNDefMacro = nullptr;
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +0000534 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro).Conditional;
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000535 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000536 if (Callbacks) {
537 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000538 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000539 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000540 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000541 }
542 // If this condition is true, enter it!
543 if (CondValue) {
544 CondInfo.FoundNonSkip = true;
545 break;
546 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000547 }
548 }
549 }
Mike Stump11289f42009-09-09 15:08:12 +0000550
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000551 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000552 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000553 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000554 }
555
556 // Finally, if we are out of the conditional (saw an #endif or ran off the end
557 // of the file, just stop skipping and return to lexing whatever came after
558 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000559 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000560
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000561 // The last skipped range isn't actually skipped yet if it's truncated
562 // by the end of the preamble; we'll resume parsing after the preamble.
563 if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
Vedant Kumar3919a502017-09-11 20:47:42 +0000564 Callbacks->SourceRangeSkipped(
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000565 SourceRange(HashTokenLoc, CurPPLexer->getSourceLocation()),
Vedant Kumar3919a502017-09-11 20:47:42 +0000566 Tok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000567}
568
Ted Kremenek56572ab2008-12-12 18:34:08 +0000569void Preprocessor::PTHSkipExcludedConditionalBlock() {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000570 while (true) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000571 assert(CurPTHLexer);
572 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000573
Ted Kremenek56572ab2008-12-12 18:34:08 +0000574 // Skip to the next '#else', '#elif', or #endif.
575 if (CurPTHLexer->SkipBlock()) {
576 // We have reached an #endif. Both the '#' and 'endif' tokens
577 // have been consumed by the PTHLexer. Just pop off the condition level.
578 PPConditionalInfo CondInfo;
579 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000580 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000581 assert(!InCond && "Can't be skipping if not in a conditional!");
582 break;
583 }
Mike Stump11289f42009-09-09 15:08:12 +0000584
Ted Kremenek56572ab2008-12-12 18:34:08 +0000585 // We have reached a '#else' or '#elif'. Lex the next token to get
586 // the directive flavor.
587 Token Tok;
588 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000589
Ted Kremenek56572ab2008-12-12 18:34:08 +0000590 // We can actually look up the IdentifierInfo here since we aren't in
591 // raw mode.
592 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
593
594 if (K == tok::pp_else) {
595 // #else: Enter the else condition. We aren't in a nested condition
596 // since we skip those. We're always in the one matching the last
597 // blocked we skipped.
598 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
599 // Note that we've seen a #else in this conditional.
600 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000601
Ted Kremenek56572ab2008-12-12 18:34:08 +0000602 // If the #if block wasn't entered then enter the #else block now.
603 if (!CondInfo.FoundNonSkip) {
604 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000605
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000606 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000607 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000608 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000609 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000610
Ted Kremenek56572ab2008-12-12 18:34:08 +0000611 break;
612 }
Mike Stump11289f42009-09-09 15:08:12 +0000613
Ted Kremenek56572ab2008-12-12 18:34:08 +0000614 // Otherwise skip this block.
615 continue;
616 }
Mike Stump11289f42009-09-09 15:08:12 +0000617
Ted Kremenek56572ab2008-12-12 18:34:08 +0000618 assert(K == tok::pp_elif);
619 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
620
621 // If this is a #elif with a #else before it, report the error.
622 if (CondInfo.FoundElse)
623 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000624
Ted Kremenek56572ab2008-12-12 18:34:08 +0000625 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000626 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000627 if (CondInfo.FoundNonSkip)
628 continue;
629
630 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000631 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000632 CurPTHLexer->ParsingPreprocessorDirective = true;
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +0000633 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro).Conditional;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000634 CurPTHLexer->ParsingPreprocessorDirective = false;
635
636 // If this condition is true, enter it!
637 if (ShouldEnter) {
638 CondInfo.FoundNonSkip = true;
639 break;
640 }
641
642 // Otherwise, skip this block and go to the next one.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000643 }
644}
645
Richard Smith2a553082015-04-23 22:58:06 +0000646Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000647 if (!SourceMgr.isInMainFile(Loc)) {
648 // Try to determine the module of the include directive.
649 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
650 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
651 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
652 // The include comes from an included file.
653 return HeaderInfo.getModuleMap()
654 .findModuleForHeader(EntryOfIncl)
655 .getModule();
656 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000657 }
Richard Smith7e82e012016-02-19 22:25:36 +0000658
659 // This is either in the main file or not in a file at all. It belongs
660 // to the current module, if there is one.
661 return getLangOpts().CurrentModule.empty()
662 ? nullptr
663 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000664}
665
Richard Smith4eb83932016-04-27 21:57:05 +0000666const FileEntry *
667Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000668 Module *M,
Richard Smith4eb83932016-04-27 21:57:05 +0000669 SourceLocation Loc) {
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000670 assert(M && "no module to include");
671
Richard Smith4eb83932016-04-27 21:57:05 +0000672 // If we have a module import syntax, we shouldn't include a header to
673 // make a particular module visible.
674 if (getLangOpts().ObjC2)
675 return nullptr;
676
Richard Smith4eb83932016-04-27 21:57:05 +0000677 Module *TopM = M->getTopLevelModule();
678 Module *IncM = getModuleForLocation(IncLoc);
679
680 // Walk up through the include stack, looking through textual headers of M
681 // until we hit a non-textual header that we can #include. (We assume textual
682 // headers of a module with non-textual headers aren't meant to be used to
683 // import entities from the module.)
684 auto &SM = getSourceManager();
685 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
686 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
687 auto *FE = SM.getFileEntryForID(ID);
Richard Smith040e1262017-06-02 01:55:39 +0000688 if (!FE)
689 break;
Richard Smith4eb83932016-04-27 21:57:05 +0000690
691 bool InTextualHeader = false;
692 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
693 if (!Header.getModule()->isSubModuleOf(TopM))
694 continue;
695
696 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
697 // If this is an accessible, non-textual header of M's top-level module
698 // that transitively includes the given location and makes the
699 // corresponding module visible, this is the thing to #include.
700 if (Header.isAccessibleFrom(IncM))
701 return FE;
702
703 // It's in a private header; we can't #include it.
704 // FIXME: If there's a public header in some module that re-exports it,
705 // then we could suggest including that, but it's not clear that's the
706 // expected way to make this entity visible.
707 continue;
708 }
709
710 InTextualHeader = true;
711 }
712
713 if (!InTextualHeader)
714 break;
715
716 Loc = SM.getIncludeLoc(ID);
717 }
718
719 return nullptr;
720}
721
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000722const FileEntry *Preprocessor::LookupFile(
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000723 SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
724 const DirectoryLookup *FromDir, const FileEntry *FromFile,
725 const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000726 SmallVectorImpl<char> *RelativePath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000727 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000728 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000729 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000730
Will Wilson0fafd342013-12-27 19:46:16 +0000731 // If the header lookup mechanism may be relative to the current inclusion
732 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000733 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
734 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000735 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000736 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000737 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000738 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000739
Chris Lattner022923a2009-02-04 19:45:07 +0000740 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000741 // predefines buffer or the module includes buffer. Any other file is not
742 // lexed with a normal lexer, so it won't be scanned for preprocessor
743 // directives.
744 //
745 // If we have the predefines buffer, resolve #include references (which come
746 // from the -include command line argument) from the current working
747 // directory instead of relative to the main file.
748 //
749 // If we have the module includes buffer, resolve #include references (which
750 // come from header declarations in the module map) relative to the module
751 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000752 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000753 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000754 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000755 BuildSystemModule = getCurrentModule()->IsSystem;
756 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000757 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000758 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
759 } else {
760 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
761 }
Will Wilson0fafd342013-12-27 19:46:16 +0000762
763 // MSVC searches the current include stack from top to bottom for
764 // headers included by quoted include directives.
765 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000766 if (LangOpts.MSVCCompat && !isAngled) {
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000767 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000768 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000769 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000770 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000771 }
Chris Lattner022923a2009-02-04 19:45:07 +0000772 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000773 }
Mike Stump11289f42009-09-09 15:08:12 +0000774
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000775 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000776
777 if (FromFile) {
778 // We're supposed to start looking from after a particular file. Search
779 // the include path until we find that file or run out of files.
780 const DirectoryLookup *TmpCurDir = CurDir;
781 const DirectoryLookup *TmpFromDir = nullptr;
782 while (const FileEntry *FE = HeaderInfo.LookupFile(
783 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000784 Includers, SearchPath, RelativePath, RequestingModule,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000785 SuggestedModule, /*IsMapped=*/nullptr, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000786 // Keep looking as if this file did a #include_next.
787 TmpFromDir = TmpCurDir;
788 ++TmpFromDir;
789 if (FE == FromFile) {
790 // Found it.
791 FromDir = TmpFromDir;
792 CurDir = TmpCurDir;
793 break;
794 }
795 }
796 }
797
798 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000799 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000800 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000801 RelativePath, RequestingModule, SuggestedModule, IsMapped, SkipCache,
Manman Rene4a5d372016-05-17 02:15:12 +0000802 BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000803 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000804 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000805 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000806 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
807 Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000808 return FE;
809 }
Mike Stump11289f42009-09-09 15:08:12 +0000810
Will Wilson0fafd342013-12-27 19:46:16 +0000811 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000812 // Otherwise, see if this is a subframework header. If so, this is relative
813 // to one of the headers on the #include stack. Walk the list of the current
814 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000815 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000816 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000817 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000818 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000819 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000820 SuggestedModule))) {
821 if (SuggestedModule && !LangOpts.AsmPreprocessor)
822 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000823 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
824 Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000825 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000826 }
827 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000828 }
Mike Stump11289f42009-09-09 15:08:12 +0000829
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000830 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000831 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000832 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000833 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000834 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000835 RequestingModule, SuggestedModule))) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000836 if (SuggestedModule && !LangOpts.AsmPreprocessor)
837 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000838 RequestingModule, RequestingModuleIsModuleInterface,
839 FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000840 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000841 }
842 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000843 }
844 }
Mike Stump11289f42009-09-09 15:08:12 +0000845
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000846 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000847 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000848}
849
Chris Lattnerf64b3522008-03-09 01:54:53 +0000850//===----------------------------------------------------------------------===//
851// Preprocessor Directive Handling.
852//===----------------------------------------------------------------------===//
853
David Blaikied5321242012-06-06 18:52:13 +0000854class Preprocessor::ResetMacroExpansionHelper {
855public:
856 ResetMacroExpansionHelper(Preprocessor *pp)
857 : PP(pp), save(pp->DisableMacroExpansion) {
858 if (pp->MacroExpansionInDirectivesOverride)
859 pp->DisableMacroExpansion = false;
860 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000861
David Blaikied5321242012-06-06 18:52:13 +0000862 ~ResetMacroExpansionHelper() {
863 PP->DisableMacroExpansion = save;
864 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000865
David Blaikied5321242012-06-06 18:52:13 +0000866private:
867 Preprocessor *PP;
868 bool save;
869};
870
Chris Lattnerf64b3522008-03-09 01:54:53 +0000871/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000872/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000873/// lexer/preprocessor state, and advances the lexer(s) so that the next token
874/// read is the correct one.
875void Preprocessor::HandleDirective(Token &Result) {
876 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000877
Chris Lattnerf64b3522008-03-09 01:54:53 +0000878 // We just parsed a # character at the start of a line, so we're in directive
879 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000880 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000881 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000882 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000883
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000884 bool ImmediatelyAfterTopLevelIfndef =
885 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
886 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
887
Chris Lattnerf64b3522008-03-09 01:54:53 +0000888 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000889
Chris Lattnerf64b3522008-03-09 01:54:53 +0000890 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000891 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000892 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000893 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000894
Chris Lattner2d17ab72009-03-18 21:00:25 +0000895 // Save the '#' token in case we need to return it later.
896 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000897
Chris Lattnerf64b3522008-03-09 01:54:53 +0000898 // Read the next token, the directive flavor. This isn't expanded due to
899 // C99 6.10.3p8.
900 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000901
Chris Lattnerf64b3522008-03-09 01:54:53 +0000902 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
903 // #define A(x) #x
904 // A(abc
905 // #warning blah
906 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000907 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
908 // not support this for #include-like directives, since that can result in
909 // terrible diagnostics, and does not work in GCC.
910 if (InMacroArgs) {
911 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
912 switch (II->getPPKeywordID()) {
913 case tok::pp_include:
914 case tok::pp_import:
915 case tok::pp_include_next:
916 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000917 case tok::pp_pragma:
918 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000919 DiscardUntilEndOfDirective();
920 return;
921 default:
922 break;
923 }
924 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000925 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000926 }
Mike Stump11289f42009-09-09 15:08:12 +0000927
David Blaikied5321242012-06-06 18:52:13 +0000928 // Temporarily enable macro expansion if set so
929 // and reset to previous state when returning from this function.
930 ResetMacroExpansionHelper helper(this);
931
Chris Lattnerf64b3522008-03-09 01:54:53 +0000932 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000933 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000934 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000935 case tok::code_completion:
936 if (CodeComplete)
937 CodeComplete->CodeCompleteDirective(
938 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000939 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000940 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000941 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000942 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000943 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000944 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000945 default:
946 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000947 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000948
Chris Lattnerf64b3522008-03-09 01:54:53 +0000949 // Ask what the preprocessor keyword ID is.
950 switch (II->getPPKeywordID()) {
951 default: break;
952 // C99 6.10.1 - Conditional Inclusion.
953 case tok::pp_if:
Vedant Kumar3919a502017-09-11 20:47:42 +0000954 return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000955 case tok::pp_ifdef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000956 return HandleIfdefDirective(Result, SavedHash, false,
957 true /*not valid for miopt*/);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000958 case tok::pp_ifndef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000959 return HandleIfdefDirective(Result, SavedHash, true,
960 ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000961 case tok::pp_elif:
Vedant Kumar3919a502017-09-11 20:47:42 +0000962 return HandleElifDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000963 case tok::pp_else:
Vedant Kumar3919a502017-09-11 20:47:42 +0000964 return HandleElseDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000965 case tok::pp_endif:
966 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Chris Lattnerf64b3522008-03-09 01:54:53 +0000968 // C99 6.10.2 - Source File Inclusion.
969 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000970 // Handle #include.
971 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000972 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000973 // Handle -imacros.
Taewook Oh755e4d22016-06-13 21:55:33 +0000974 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Chris Lattnerf64b3522008-03-09 01:54:53 +0000976 // C99 6.10.3 - Macro Replacement.
977 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000978 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000979 case tok::pp_undef:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000980 return HandleUndefDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000981
982 // C99 6.10.4 - Line Control.
983 case tok::pp_line:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000984 return HandleLineDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattnerf64b3522008-03-09 01:54:53 +0000986 // C99 6.10.5 - Error Directive.
987 case tok::pp_error:
988 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000989
Chris Lattnerf64b3522008-03-09 01:54:53 +0000990 // C99 6.10.6 - Pragma Directive.
991 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000992 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000993
Chris Lattnerf64b3522008-03-09 01:54:53 +0000994 // GNU Extensions.
995 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000996 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000997 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000998 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000999
Chris Lattnerf64b3522008-03-09 01:54:53 +00001000 case tok::pp_warning:
1001 Diag(Result, diag::ext_pp_warning_directive);
1002 return HandleUserDiagnosticDirective(Result, true);
1003 case tok::pp_ident:
1004 return HandleIdentSCCSDirective(Result);
1005 case tok::pp_sccs:
1006 return HandleIdentSCCSDirective(Result);
1007 case tok::pp_assert:
1008 //isExtension = true; // FIXME: implement #assert
1009 break;
1010 case tok::pp_unassert:
1011 //isExtension = true; // FIXME: implement #unassert
1012 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001013
Douglas Gregor663b48f2012-01-03 19:48:16 +00001014 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001015 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001016 return HandleMacroPublicDirective(Result);
1017 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001018
Douglas Gregor663b48f2012-01-03 19:48:16 +00001019 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001020 if (getLangOpts().Modules)
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001021 return HandleMacroPrivateDirective();
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001022 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001023 }
1024 break;
1025 }
Mike Stump11289f42009-09-09 15:08:12 +00001026
Chris Lattner2d17ab72009-03-18 21:00:25 +00001027 // If this is a .S file, treat unknown # directives as non-preprocessor
1028 // directives. This is important because # may be a comment or introduce
1029 // various pseudo-ops. Just return the # token and push back the following
1030 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001031 if (getLangOpts().AsmPreprocessor) {
David Blaikie2eabcc92016-02-09 18:52:09 +00001032 auto Toks = llvm::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001033 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001034 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001035 Toks[1] = Result;
Taewook Oh755e4d22016-06-13 21:55:33 +00001036
Chris Lattner56f64c12011-01-06 05:01:51 +00001037 // If the second token is a hashhash token, then we need to translate it to
1038 // unknown so the token lexer doesn't try to perform token pasting.
1039 if (Result.is(tok::hashhash))
1040 Toks[1].setKind(tok::unknown);
Taewook Oh755e4d22016-06-13 21:55:33 +00001041
Chris Lattner2d17ab72009-03-18 21:00:25 +00001042 // Enter this token stream so that we re-lex the tokens. Make sure to
1043 // enable macro expansion, in case the token after the # is an identifier
1044 // that is expanded.
David Blaikie2eabcc92016-02-09 18:52:09 +00001045 EnterTokenStream(std::move(Toks), 2, false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001046 return;
1047 }
Mike Stump11289f42009-09-09 15:08:12 +00001048
Chris Lattnerf64b3522008-03-09 01:54:53 +00001049 // If we reached here, the preprocessing token is not valid!
1050 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001051
Chris Lattnerf64b3522008-03-09 01:54:53 +00001052 // Read the rest of the PP line.
1053 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001054
Chris Lattnerf64b3522008-03-09 01:54:53 +00001055 // Okay, we're done parsing the directive.
1056}
1057
Chris Lattner76e68962009-01-26 06:19:46 +00001058/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1059/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1060static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001061 unsigned DiagID, Preprocessor &PP,
1062 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001063 if (DigitTok.isNot(tok::numeric_constant)) {
1064 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001065
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001066 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001067 PP.DiscardUntilEndOfDirective();
1068 return true;
1069 }
Mike Stump11289f42009-09-09 15:08:12 +00001070
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001071 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001072 IntegerBuffer.resize(DigitTok.getLength());
1073 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001074 bool Invalid = false;
1075 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1076 if (Invalid)
1077 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001078
Chris Lattnerd66f1722009-04-18 18:35:15 +00001079 // Verify that we have a simple digit-sequence, and compute the value. This
1080 // is always a simple digit string computed in decimal, so we do this manually
1081 // here.
1082 Val = 0;
1083 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001084 // C++1y [lex.fcon]p1:
1085 // Optional separating single quotes in a digit-sequence are ignored
1086 if (DigitTokBegin[i] == '\'')
1087 continue;
1088
Jordan Rosea7d03842013-02-08 22:30:41 +00001089 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001090 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001091 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001092 PP.DiscardUntilEndOfDirective();
1093 return true;
1094 }
Mike Stump11289f42009-09-09 15:08:12 +00001095
Chris Lattnerd66f1722009-04-18 18:35:15 +00001096 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1097 if (NextVal < Val) { // overflow.
1098 PP.Diag(DigitTok, DiagID);
1099 PP.DiscardUntilEndOfDirective();
1100 return true;
1101 }
1102 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001103 }
Mike Stump11289f42009-09-09 15:08:12 +00001104
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001105 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001106 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1107 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001108
Chris Lattner76e68962009-01-26 06:19:46 +00001109 return false;
1110}
1111
James Dennettf6333ac2012-06-22 05:46:07 +00001112/// \brief Handle a \#line directive: C99 6.10.4.
1113///
1114/// The two acceptable forms are:
1115/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001116/// # line digit-sequence
1117/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001118/// \endverbatim
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001119void Preprocessor::HandleLineDirective() {
Chris Lattner100c65e2009-01-26 05:29:08 +00001120 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1121 // expanded.
1122 Token DigitTok;
1123 Lex(DigitTok);
1124
Chris Lattner100c65e2009-01-26 05:29:08 +00001125 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001126 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001127 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001128 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001129
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001130 if (LineNo == 0)
1131 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001132
Chris Lattner76e68962009-01-26 06:19:46 +00001133 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1134 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001135 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001136 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001137 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001138 if (LineNo >= LineLimit)
1139 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001140 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001141 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001142
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001143 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001144 Token StrTok;
1145 Lex(StrTok);
1146
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001147 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1148 // string followed by eod.
1149 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001150 ; // ok
1151 else if (StrTok.isNot(tok::string_literal)) {
1152 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001153 return DiscardUntilEndOfDirective();
1154 } else if (StrTok.hasUDSuffix()) {
1155 Diag(StrTok, diag::err_invalid_string_udl);
1156 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001157 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001158 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001159 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001160 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001161 if (Literal.hadError)
1162 return DiscardUntilEndOfDirective();
1163 if (Literal.Pascal) {
1164 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1165 return DiscardUntilEndOfDirective();
1166 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001167 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001168
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001169 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001170 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1171 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001172 }
Mike Stump11289f42009-09-09 15:08:12 +00001173
Reid Klecknereb00ee02017-05-22 21:42:58 +00001174 // Take the file kind of the file containing the #line directive. #line
1175 // directives are often used for generated sources from the same codebase, so
1176 // the new file should generally be classified the same way as the current
1177 // file. This is visible in GCC's pre-processed output, which rewrites #line
1178 // to GNU line markers.
1179 SrcMgr::CharacteristicKind FileKind =
1180 SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1181
1182 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1183 false, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001184
Chris Lattner839150e2009-03-27 17:13:49 +00001185 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001186 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Reid Klecknereb00ee02017-05-22 21:42:58 +00001187 PPCallbacks::RenameFile, FileKind);
Chris Lattner100c65e2009-01-26 05:29:08 +00001188}
1189
Chris Lattner76e68962009-01-26 06:19:46 +00001190/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1191/// marker directive.
1192static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
Reid Klecknereb00ee02017-05-22 21:42:58 +00001193 SrcMgr::CharacteristicKind &FileKind,
Chris Lattner76e68962009-01-26 06:19:46 +00001194 Preprocessor &PP) {
1195 unsigned FlagVal;
1196 Token FlagTok;
1197 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001198 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001199 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1200 return true;
1201
1202 if (FlagVal == 1) {
1203 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001204
Chris Lattner76e68962009-01-26 06:19:46 +00001205 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001206 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001207 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1208 return true;
1209 } else if (FlagVal == 2) {
1210 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001211
Chris Lattner1c967782009-02-04 06:25:26 +00001212 SourceManager &SM = PP.getSourceManager();
1213 // If we are leaving the current presumed file, check to make sure the
1214 // presumed include stack isn't empty!
1215 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001216 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001217 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001218 if (PLoc.isInvalid())
1219 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001220
Chris Lattner1c967782009-02-04 06:25:26 +00001221 // If there is no include loc (main file) or if the include loc is in a
1222 // different physical file, then we aren't in a "1" line marker flag region.
1223 SourceLocation IncLoc = PLoc.getIncludeLoc();
1224 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001225 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001226 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1227 PP.DiscardUntilEndOfDirective();
1228 return true;
1229 }
Mike Stump11289f42009-09-09 15:08:12 +00001230
Chris Lattner76e68962009-01-26 06:19:46 +00001231 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001232 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001233 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1234 return true;
1235 }
1236
1237 // We must have 3 if there are still flags.
1238 if (FlagVal != 3) {
1239 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001240 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001241 return true;
1242 }
Mike Stump11289f42009-09-09 15:08:12 +00001243
Reid Klecknereb00ee02017-05-22 21:42:58 +00001244 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001245
Chris Lattner76e68962009-01-26 06:19:46 +00001246 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001247 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001248 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001249 return true;
1250
1251 // We must have 4 if there is yet another flag.
1252 if (FlagVal != 4) {
1253 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001254 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001255 return true;
1256 }
Mike Stump11289f42009-09-09 15:08:12 +00001257
Reid Klecknereb00ee02017-05-22 21:42:58 +00001258 FileKind = SrcMgr::C_ExternCSystem;
Mike Stump11289f42009-09-09 15:08:12 +00001259
Chris Lattner76e68962009-01-26 06:19:46 +00001260 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001261 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001262
1263 // There are no more valid flags here.
1264 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001265 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001266 return true;
1267}
1268
1269/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1270/// one of the following forms:
1271///
1272/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001273/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001274/// # 42 "file" ('1' | '2')? '3' '4'?
1275///
1276void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1277 // Validate the number and convert it to an unsigned. GNU does not have a
1278 // line # limit other than it fit in 32-bits.
1279 unsigned LineNo;
1280 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001281 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001282 return;
Mike Stump11289f42009-09-09 15:08:12 +00001283
Chris Lattner76e68962009-01-26 06:19:46 +00001284 Token StrTok;
1285 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001286
Chris Lattner76e68962009-01-26 06:19:46 +00001287 bool IsFileEntry = false, IsFileExit = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001288 int FilenameID = -1;
Reid Klecknereb00ee02017-05-22 21:42:58 +00001289 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001290
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001291 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1292 // string followed by eod.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001293 if (StrTok.is(tok::eod)) {
1294 // Treat this like "#line NN", which doesn't change file characteristics.
1295 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1296 } else if (StrTok.isNot(tok::string_literal)) {
Chris Lattner76e68962009-01-26 06:19:46 +00001297 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001298 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001299 } else if (StrTok.hasUDSuffix()) {
1300 Diag(StrTok, diag::err_invalid_string_udl);
1301 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001302 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001303 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001304 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001305 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001306 if (Literal.hadError)
1307 return DiscardUntilEndOfDirective();
1308 if (Literal.Pascal) {
1309 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1310 return DiscardUntilEndOfDirective();
1311 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001312 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001313
Chris Lattner76e68962009-01-26 06:19:46 +00001314 // If a filename was present, read any flags that are present.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001315 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001316 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001319 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001320 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1321 IsFileExit, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattner839150e2009-03-27 17:13:49 +00001323 // If the preprocessor has callbacks installed, notify them of the #line
1324 // change. This is used so that the line marker comes out in -E mode for
1325 // example.
1326 if (Callbacks) {
1327 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1328 if (IsFileEntry)
1329 Reason = PPCallbacks::EnterFile;
1330 else if (IsFileExit)
1331 Reason = PPCallbacks::ExitFile;
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattnerc745cec2010-04-14 04:28:50 +00001333 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001334 }
Chris Lattner76e68962009-01-26 06:19:46 +00001335}
1336
Chris Lattner38d7fd22009-01-26 05:30:54 +00001337/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1338///
Mike Stump11289f42009-09-09 15:08:12 +00001339void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001340 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001341 // PTH doesn't emit #warning or #error directives.
1342 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001343 return CurPTHLexer->DiscardToEndOfLine();
1344
Chris Lattnerf64b3522008-03-09 01:54:53 +00001345 // Read the rest of the line raw. We do this because we don't want macros
1346 // to be expanded and we don't require that the tokens be valid preprocessing
1347 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1348 // collapse multiple consequtive white space between tokens, but this isn't
1349 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001350 SmallString<128> Message;
1351 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001352
1353 // Find the first non-whitespace character, so that we can make the
1354 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001355 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001356
Chris Lattner100c65e2009-01-26 05:29:08 +00001357 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001358 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001359 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001360 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001361}
1362
1363/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1364///
1365void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1366 // Yes, this directive is an extension.
1367 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattnerf64b3522008-03-09 01:54:53 +00001369 // Read the string argument.
1370 Token StrTok;
1371 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001372
Chris Lattnerf64b3522008-03-09 01:54:53 +00001373 // If the token kind isn't a string, it's a malformed directive.
1374 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001375 StrTok.isNot(tok::wide_string_literal)) {
1376 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001377 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001378 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001379 return;
1380 }
Mike Stump11289f42009-09-09 15:08:12 +00001381
Richard Smithd67aea22012-03-06 03:21:47 +00001382 if (StrTok.hasUDSuffix()) {
1383 Diag(StrTok, diag::err_invalid_string_udl);
1384 return DiscardUntilEndOfDirective();
1385 }
1386
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001387 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001388 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001389
Douglas Gregordc970f02010-03-16 22:30:13 +00001390 if (Callbacks) {
1391 bool Invalid = false;
1392 std::string Str = getSpelling(StrTok, &Invalid);
1393 if (!Invalid)
1394 Callbacks->Ident(Tok.getLocation(), Str);
1395 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001396}
1397
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001398/// \brief Handle a #public directive.
1399void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001400 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001401 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001402
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001403 // Error reading macro name? If so, diagnostic already issued.
1404 if (MacroNameTok.is(tok::eod))
1405 return;
1406
Douglas Gregor663b48f2012-01-03 19:48:16 +00001407 // Check to see if this is the last token on the #__public_macro line.
1408 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001409
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001410 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001411 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001412 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001413
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001414 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001415 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001416 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001417 return;
1418 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001419
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001420 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001421 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1422 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001423}
1424
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001425/// \brief Handle a #private directive.
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001426void Preprocessor::HandleMacroPrivateDirective() {
Douglas Gregorebf00492011-10-17 15:32:29 +00001427 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001428 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001429
Douglas Gregorebf00492011-10-17 15:32:29 +00001430 // Error reading macro name? If so, diagnostic already issued.
1431 if (MacroNameTok.is(tok::eod))
1432 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001433
Douglas Gregor663b48f2012-01-03 19:48:16 +00001434 // Check to see if this is the last token on the #__private_macro line.
1435 CheckEndOfDirective("__private_macro");
Taewook Oh755e4d22016-06-13 21:55:33 +00001436
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001437 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001438 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001439 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001440
Douglas Gregorebf00492011-10-17 15:32:29 +00001441 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001442 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001443 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001444 return;
1445 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001446
Douglas Gregorebf00492011-10-17 15:32:29 +00001447 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001448 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1449 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001450}
1451
Chris Lattnerf64b3522008-03-09 01:54:53 +00001452//===----------------------------------------------------------------------===//
1453// Preprocessor Include Directive Handling.
1454//===----------------------------------------------------------------------===//
1455
1456/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001457/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001458/// true if the input filename was in <>'s or false if it were in ""'s. The
1459/// caller is expected to provide a buffer that is large enough to hold the
1460/// spelling of the filename, but is also expected to handle the case when
1461/// this method decides to use a different buffer.
1462bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001463 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001464 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001465 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001466
Chris Lattnerf64b3522008-03-09 01:54:53 +00001467 // Make sure the filename is <x> or "x".
1468 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001469 if (Buffer[0] == '<') {
1470 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001471 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001472 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001473 return true;
1474 }
1475 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001476 } else if (Buffer[0] == '"') {
1477 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001478 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001479 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001480 return true;
1481 }
1482 isAngled = false;
1483 } else {
1484 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001485 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001486 return true;
1487 }
Mike Stump11289f42009-09-09 15:08:12 +00001488
Chris Lattnerf64b3522008-03-09 01:54:53 +00001489 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001490 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001491 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001492 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001493 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001494 }
Mike Stump11289f42009-09-09 15:08:12 +00001495
Chris Lattnerf64b3522008-03-09 01:54:53 +00001496 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001497 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001498 return isAngled;
1499}
1500
James Dennett4a4f72d2013-11-27 01:27:40 +00001501// \brief Handle cases where the \#include name is expanded from a macro
1502// as multiple tokens, which need to be glued together.
1503//
1504// This occurs for code like:
1505// \code
1506// \#define FOO <a/b.h>
1507// \#include FOO
1508// \endcode
1509// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1510//
1511// This code concatenates and consumes tokens up to the '>' token. It returns
1512// false if the > was found, otherwise it returns true if it finds and consumes
1513// the EOD marker.
1514bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001515 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001516 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001517
John Thompsonb5353522009-10-30 13:49:06 +00001518 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001519 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001520 End = CurTok.getLocation();
Taewook Oh755e4d22016-06-13 21:55:33 +00001521
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001522 // FIXME: Provide code completion for #includes.
1523 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001524 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001525 Lex(CurTok);
1526 continue;
1527 }
1528
Chris Lattnerf64b3522008-03-09 01:54:53 +00001529 // Append the spelling of this token to the buffer. If there was a space
1530 // before it, add it now.
1531 if (CurTok.hasLeadingSpace())
1532 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001533
Chris Lattnerf64b3522008-03-09 01:54:53 +00001534 // Get the spelling of the token, directly into FilenameBuffer if possible.
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001535 size_t PreAppendSize = FilenameBuffer.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001536 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001537
Chris Lattnerf64b3522008-03-09 01:54:53 +00001538 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001539 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001540
Chris Lattnerf64b3522008-03-09 01:54:53 +00001541 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1542 if (BufPtr != &FilenameBuffer[PreAppendSize])
1543 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001544
Chris Lattnerf64b3522008-03-09 01:54:53 +00001545 // Resize FilenameBuffer to the correct size.
1546 if (CurTok.getLength() != ActualLen)
1547 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001548
Chris Lattnerf64b3522008-03-09 01:54:53 +00001549 // If we found the '>' marker, return success.
1550 if (CurTok.is(tok::greater))
1551 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001552
John Thompsonb5353522009-10-30 13:49:06 +00001553 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001554 }
1555
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001556 // If we hit the eod marker, emit an error and return true so that the caller
1557 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001558 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001559 return true;
1560}
1561
Richard Smith34f30512013-11-23 04:06:09 +00001562/// \brief Push a token onto the token stream containing an annotation.
Richard Smithc51c38b2017-04-29 00:34:47 +00001563void Preprocessor::EnterAnnotationToken(SourceRange Range,
1564 tok::TokenKind Kind,
1565 void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001566 // FIXME: Produce this as the current token directly, rather than
1567 // allocating a new token for it.
David Blaikie2eabcc92016-02-09 18:52:09 +00001568 auto Tok = llvm::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001569 Tok[0].startToken();
1570 Tok[0].setKind(Kind);
Richard Smithc51c38b2017-04-29 00:34:47 +00001571 Tok[0].setLocation(Range.getBegin());
1572 Tok[0].setAnnotationEndLoc(Range.getEnd());
Richard Smith34f30512013-11-23 04:06:09 +00001573 Tok[0].setAnnotationValue(AnnotationVal);
Richard Smithc51c38b2017-04-29 00:34:47 +00001574 EnterTokenStream(std::move(Tok), 1, true);
Richard Smith34f30512013-11-23 04:06:09 +00001575}
1576
Richard Smith63b6fce2015-05-18 04:45:41 +00001577/// \brief Produce a diagnostic informing the user that a #include or similar
1578/// was implicitly treated as a module import.
1579static void diagnoseAutoModuleImport(
1580 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1581 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1582 SourceLocation PathEnd) {
1583 assert(PP.getLangOpts().ObjC2 && "no import syntax available");
1584
1585 SmallString<128> PathString;
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001586 for (size_t I = 0, N = Path.size(); I != N; ++I) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001587 if (I)
1588 PathString += '.';
1589 PathString += Path[I].first->getName();
1590 }
1591 int IncludeKind = 0;
Taewook Oh755e4d22016-06-13 21:55:33 +00001592
Richard Smith63b6fce2015-05-18 04:45:41 +00001593 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1594 case tok::pp_include:
1595 IncludeKind = 0;
1596 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001597
Richard Smith63b6fce2015-05-18 04:45:41 +00001598 case tok::pp_import:
1599 IncludeKind = 1;
Taewook Oh755e4d22016-06-13 21:55:33 +00001600 break;
1601
Richard Smith63b6fce2015-05-18 04:45:41 +00001602 case tok::pp_include_next:
1603 IncludeKind = 2;
1604 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001605
Richard Smith63b6fce2015-05-18 04:45:41 +00001606 case tok::pp___include_macros:
1607 IncludeKind = 3;
1608 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001609
Richard Smith63b6fce2015-05-18 04:45:41 +00001610 default:
1611 llvm_unreachable("unknown include directive kind");
1612 }
1613
1614 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1615 /*IsTokenRange=*/false);
1616 PP.Diag(HashLoc, diag::warn_auto_module_import)
1617 << IncludeKind << PathString
1618 << FixItHint::CreateReplacement(ReplaceRange,
1619 ("@import " + PathString + ";").str());
1620}
1621
Taewook Ohf42103c2016-06-13 20:40:21 +00001622// Given a vector of path components and a string containing the real
1623// path to the file, build a properly-cased replacement in the vector,
1624// and return true if the replacement should be suggested.
1625static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1626 StringRef RealPathName) {
1627 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1628 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1629 int Cnt = 0;
1630 bool SuggestReplacement = false;
1631 // Below is a best-effort to handle ".." in paths. It is admittedly
1632 // not 100% correct in the presence of symlinks.
1633 for (auto &Component : llvm::reverse(Components)) {
1634 if ("." == Component) {
1635 } else if (".." == Component) {
1636 ++Cnt;
1637 } else if (Cnt) {
1638 --Cnt;
1639 } else if (RealPathComponentIter != RealPathComponentEnd) {
1640 if (Component != *RealPathComponentIter) {
1641 // If these path components differ by more than just case, then we
1642 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1643 // noisy false positives.
1644 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1645 if (!SuggestReplacement)
1646 break;
1647 Component = *RealPathComponentIter;
1648 }
1649 ++RealPathComponentIter;
1650 }
1651 }
1652 return SuggestReplacement;
1653}
1654
Richard Smith27e5aa02017-06-05 18:57:56 +00001655bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
1656 const TargetInfo &TargetInfo,
1657 DiagnosticsEngine &Diags, Module *M) {
1658 Module::Requirement Requirement;
1659 Module::UnresolvedHeaderDirective MissingHeader;
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00001660 Module *ShadowingModule = nullptr;
1661 if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
1662 ShadowingModule))
Richard Smith27e5aa02017-06-05 18:57:56 +00001663 return false;
1664
1665 if (MissingHeader.FileNameLoc.isValid()) {
1666 Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1667 << MissingHeader.IsUmbrella << MissingHeader.FileName;
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00001668 } else if (ShadowingModule) {
1669 Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name;
1670 Diags.Report(ShadowingModule->DefinitionLoc,
1671 diag::note_previous_definition);
Richard Smith27e5aa02017-06-05 18:57:56 +00001672 } else {
1673 // FIXME: Track the location at which the requirement was specified, and
1674 // use it here.
1675 Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
1676 << M->getFullModuleName() << Requirement.second << Requirement.first;
1677 }
1678 return true;
1679}
1680
James Dennettf6333ac2012-06-22 05:46:07 +00001681/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1682/// the file to be included from the lexer, then include it! This is a common
1683/// routine with functionality shared between \#include, \#include_next and
1684/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001685/// specifies the file to start searching from.
Taewook Oh755e4d22016-06-13 21:55:33 +00001686void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001687 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001688 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001689 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001690 bool isImport) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001691 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001692 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001693
Chris Lattnerf64b3522008-03-09 01:54:53 +00001694 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001695 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001696 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001697 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001698 SourceLocation CharEnd; // the end of this directive, in characters
Taewook Oh755e4d22016-06-13 21:55:33 +00001699
Chris Lattnerf64b3522008-03-09 01:54:53 +00001700 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001701 case tok::eod:
1702 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001703 return;
Mike Stump11289f42009-09-09 15:08:12 +00001704
Chris Lattnerf64b3522008-03-09 01:54:53 +00001705 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001706 case tok::string_literal:
1707 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001708 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001709 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001710 break;
Mike Stump11289f42009-09-09 15:08:12 +00001711
Chris Lattnerf64b3522008-03-09 01:54:53 +00001712 case tok::less:
1713 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1714 // case, glue the tokens together into FilenameBuffer and interpret those.
1715 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001716 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001717 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001718 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001719 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001720 break;
1721 default:
1722 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1723 DiscardUntilEndOfDirective();
1724 return;
1725 }
Mike Stump11289f42009-09-09 15:08:12 +00001726
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001727 CharSourceRange FilenameRange
1728 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001729 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001730 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001731 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001732 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1733 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001734 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001735 DiscardUntilEndOfDirective();
1736 return;
1737 }
Mike Stump11289f42009-09-09 15:08:12 +00001738
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001739 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001740 // we allow macros that expand to nothing after the filename, because this
1741 // falls into the category of "#include pp-tokens new-line" specified in
1742 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001743 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001744
1745 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001746 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1747 Diag(FilenameTok, diag::err_pp_include_too_deep);
1748 return;
1749 }
Mike Stump11289f42009-09-09 15:08:12 +00001750
John McCall32f5fe12011-09-30 05:12:12 +00001751 // Complain about attempts to #include files in an audit pragma.
1752 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1753 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1754 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1755
1756 // Immediately leave the pragma.
1757 PragmaARCCFCodeAuditedLoc = SourceLocation();
1758 }
1759
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001760 // Complain about attempts to #include files in an assume-nonnull pragma.
1761 if (PragmaAssumeNonNullLoc.isValid()) {
1762 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1763 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1764
1765 // Immediately leave the pragma.
1766 PragmaAssumeNonNullLoc = SourceLocation();
1767 }
1768
Aaron Ballman611306e2012-03-02 22:51:54 +00001769 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001770 // Map the filename with the brackets still attached. If the name doesn't
1771 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001772 // spelling for.
1773 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1774 if (!NewName.empty())
1775 Filename = NewName;
1776 }
1777
Chris Lattnerf64b3522008-03-09 01:54:53 +00001778 // Search include directories.
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001779 bool IsMapped = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001780 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001781 SmallString<1024> SearchPath;
1782 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001783 // We get the raw path only if we have 'Callbacks' to which we later pass
1784 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001785 ModuleMap::KnownHeader SuggestedModule;
1786 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001787 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001788 if (LangOpts.MSVCCompat) {
1789 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001790#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001791 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001792#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001793 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001794 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001795 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001796 isAngled, LookupFrom, LookupFromFile, CurDir,
1797 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001798 &SuggestedModule, &IsMapped);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001799
Richard Smithdbbc5232015-05-14 02:25:44 +00001800 if (!File) {
1801 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001802 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001803 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001804 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1805 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1806 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001807 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001808 HeaderInfo.AddSearchPath(DL, isAngled);
Taewook Oh755e4d22016-06-13 21:55:33 +00001809
Douglas Gregor11729f02011-11-30 18:12:06 +00001810 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001811 File = LookupFile(
1812 FilenameLoc,
1813 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1814 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001815 &SuggestedModule, &IsMapped, /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001816 }
1817 }
1818 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001819
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001820 if (!SuppressIncludeNotFoundError) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001821 // If the file could not be located and it was included via angle
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001822 // brackets, we can attempt a lookup as though it were a quoted path to
1823 // provide the user with a possible fixit.
1824 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001825 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001826 FilenameLoc,
1827 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1828 LookupFrom, LookupFromFile, CurDir,
1829 Callbacks ? &SearchPath : nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001830 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001831 if (File) {
1832 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001833 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1834 Filename <<
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001835 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1836 }
1837 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001838
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001839 // If the file is still not found, just go with the vanilla diagnostic
1840 if (!File)
Erik Verbruggen45449542016-10-25 10:13:10 +00001841 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename
1842 << FilenameRange;
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001843 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001844 }
1845
Richard Smith63b6fce2015-05-18 04:45:41 +00001846 // Should we enter the source file? Set to false if either the source file is
1847 // known to have no effect beyond its effect on module visibility -- that is,
1848 // if it's got an include guard that is already defined or is a modular header
1849 // we've imported or already built.
1850 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001851
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001852 if (PPOpts->SingleFileParseMode)
1853 ShouldEnter = false;
1854
Richard Smith63b6fce2015-05-18 04:45:41 +00001855 // Determine whether we should try to import the module for this #include, if
1856 // there is one. Don't do so if precompiled module support is disabled or we
1857 // are processing this module textually (because we're building the module).
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001858 if (ShouldEnter && File && SuggestedModule && getLangOpts().Modules &&
Richard Smith63b6fce2015-05-18 04:45:41 +00001859 SuggestedModule.getModule()->getTopLevelModuleName() !=
Richard Smith7e82e012016-02-19 22:25:36 +00001860 getLangOpts().CurrentModule) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001861 // If this include corresponds to a module but that module is
1862 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001863 // FIXME: Remove this; loadModule does the same check (but produces
1864 // slightly worse diagnostics).
Richard Smith27e5aa02017-06-05 18:57:56 +00001865 if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
1866 SuggestedModule.getModule())) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001867 Diag(FilenameTok.getLocation(),
1868 diag::note_implicit_top_level_module_import_here)
Richard Smith27e5aa02017-06-05 18:57:56 +00001869 << SuggestedModule.getModule()->getTopLevelModuleName();
Sean Silva8b7c0392015-08-17 16:39:30 +00001870 return;
1871 }
1872
Douglas Gregor71944202011-11-30 00:36:36 +00001873 // Compute the module access path corresponding to this module.
1874 // FIXME: Should we have a second loadModule() overload to avoid this
1875 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001876 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001877 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001878 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1879 FilenameTok.getLocation()));
1880 std::reverse(Path.begin(), Path.end());
1881
Douglas Gregor41e115a2011-11-30 18:02:36 +00001882 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001883 // We only do this in Objective-C, where we have a module-import syntax.
1884 if (getLangOpts().ObjC2)
1885 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001886
Richard Smith10434f32015-05-02 02:08:26 +00001887 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001888 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001889 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1890 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001891 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1892 IncludeTok.getLocation(), Path, Module::Hidden,
1893 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001894 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001895 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001896
Richard Smith63b6fce2015-05-18 04:45:41 +00001897 if (Imported)
1898 ShouldEnter = false;
1899 else if (Imported.isMissingExpected()) {
1900 // We failed to find a submodule that we assumed would exist (because it
1901 // was in the directory of an umbrella header, for instance), but no
Richard Smitha114c462016-12-06 00:40:17 +00001902 // actual module containing it exists (because the umbrella header is
Richard Smith63b6fce2015-05-18 04:45:41 +00001903 // incomplete). Treat this as a textual inclusion.
1904 SuggestedModule = ModuleMap::KnownHeader();
Richard Smitha114c462016-12-06 00:40:17 +00001905 } else if (Imported.isConfigMismatch()) {
1906 // On a configuration mismatch, enter the header textually. We still know
1907 // that it's part of the corresponding module.
Richard Smith63b6fce2015-05-18 04:45:41 +00001908 } else {
1909 // We hit an error processing the import. Bail out.
1910 if (hadModuleLoaderFatalFailure()) {
1911 // With a fatal failure in the module loader, we abort parsing.
1912 Token &Result = IncludeTok;
1913 if (CurLexer) {
1914 Result.startToken();
1915 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1916 CurLexer->cutOffLexing();
1917 } else {
1918 assert(CurPTHLexer && "#include but no current lexer set!");
1919 CurPTHLexer->getEOF(Result);
1920 }
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001921 }
1922 return;
1923 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001924 }
1925
Richard Smithc5247e62017-05-30 02:03:19 +00001926 // The #included file will be considered to be a system header if either it is
1927 // in a system include directory, or if the #includer is a system include
1928 // header.
1929 SrcMgr::CharacteristicKind FileCharacter =
1930 SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
1931 if (File)
1932 FileCharacter = std::max(HeaderInfo.getFileDirFlavor(File), FileCharacter);
1933
1934 // Ask HeaderInfo if we should enter this #include file. If not, #including
1935 // this file will have no effect.
1936 bool SkipHeader = false;
1937 if (ShouldEnter && File &&
1938 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
1939 getLangOpts().Modules,
1940 SuggestedModule.getModule())) {
1941 ShouldEnter = false;
1942 SkipHeader = true;
1943 }
1944
Richard Smith63b6fce2015-05-18 04:45:41 +00001945 if (Callbacks) {
1946 // Notify the callback object that we've seen an inclusion directive.
1947 Callbacks->InclusionDirective(
1948 HashLoc, IncludeTok,
1949 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1950 FilenameRange, File, SearchPath, RelativePath,
1951 ShouldEnter ? nullptr : SuggestedModule.getModule());
Richard Smithc5247e62017-05-30 02:03:19 +00001952 if (SkipHeader && !SuggestedModule.getModule())
1953 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Douglas Gregor97eec242011-09-15 22:00:41 +00001954 }
Richard Smith63b6fce2015-05-18 04:45:41 +00001955
1956 if (!File)
1957 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001958
Richard Smith54ef4c32015-05-19 19:58:11 +00001959 // FIXME: If we have a suggested module, and we've already visited this file,
1960 // don't bother entering it again. We know it has no further effect.
1961
Taewook Ohf42103c2016-06-13 20:40:21 +00001962 // Issue a diagnostic if the name of the file on disk has a different case
1963 // than the one we're about to open.
1964 const bool CheckIncludePathPortability =
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001965 !IsMapped && File && !File->tryGetRealPathName().empty();
Taewook Ohf42103c2016-06-13 20:40:21 +00001966
1967 if (CheckIncludePathPortability) {
1968 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
1969 StringRef RealPathName = File->tryGetRealPathName();
1970 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
1971 llvm::sys::path::end(Name));
1972
1973 if (trySimplifyPath(Components, RealPathName)) {
1974 SmallString<128> Path;
1975 Path.reserve(Name.size()+2);
1976 Path.push_back(isAngled ? '<' : '"');
Taewook Ohcc89bac2017-02-21 22:30:55 +00001977 bool isLeadingSeparator = llvm::sys::path::is_absolute(Name);
Taewook Ohf42103c2016-06-13 20:40:21 +00001978 for (auto Component : Components) {
Taewook Ohcc89bac2017-02-21 22:30:55 +00001979 if (isLeadingSeparator)
1980 isLeadingSeparator = false;
1981 else
1982 Path.append(Component);
Taewook Ohf42103c2016-06-13 20:40:21 +00001983 // Append the separator the user used, or the close quote
1984 Path.push_back(
1985 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
1986 (isAngled ? '>' : '"'));
1987 }
Taewook Ohf42103c2016-06-13 20:40:21 +00001988 // For user files and known standard headers, by default we issue a diagnostic.
1989 // For other system headers, we don't. They can be controlled separately.
1990 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
1991 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
1992 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Reid Kleckner273895b2017-02-14 18:38:40 +00001993 Diag(FilenameTok, DiagId) << Path <<
1994 FixItHint::CreateReplacement(Range, Path);
Taewook Ohf42103c2016-06-13 20:40:21 +00001995 }
1996 }
1997
Richard Smith63b6fce2015-05-18 04:45:41 +00001998 // If we don't need to enter the file, stop now.
1999 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00002000 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00002001 if (auto *M = SuggestedModule.getModule()) {
Manman Renffd3e9d2017-01-09 19:20:18 +00002002 // When building a pch, -fmodule-name tells the compiler to textually
2003 // include headers in the specified module. But it is possible that
2004 // ShouldEnter is false because we are skipping the header. In that
2005 // case, We are not importing the specified module.
2006 if (SkipHeader && getLangOpts().CompilingPCH &&
2007 M->getTopLevelModuleName() == getLangOpts().CurrentModule)
2008 return;
2009
Richard Smitha0aafa32015-05-18 03:52:30 +00002010 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00002011
2012 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
2013 tok::pp___include_macros)
Richard Smithc51c38b2017-04-29 00:34:47 +00002014 EnterAnnotationToken(SourceRange(HashLoc, End),
2015 tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00002016 }
Chris Lattner72286d62010-04-19 20:44:31 +00002017 return;
2018 }
2019
Chris Lattnerf64b3522008-03-09 01:54:53 +00002020 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002021 SourceLocation IncludePos = End;
2022 // If the filename string was the result of macro expansions, set the include
2023 // position on the file where it will be included and after the expansions.
2024 if (IncludePos.isMacroID())
2025 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
2026 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002027 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002028
Richard Smith34f30512013-11-23 04:06:09 +00002029 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002030 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
2031 return;
Richard Smith34f30512013-11-23 04:06:09 +00002032
Richard Smitha0aafa32015-05-18 03:52:30 +00002033 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002034 if (auto *M = SuggestedModule.getModule()) {
Bruno Cardoso Lopes8587dfd2018-01-05 02:33:18 +00002035 if (M->getTopLevelModule()->ShadowingModule) {
2036 // We are building a submodule that belongs to a shadowed module. This
2037 // means we find header files in the shadowed module.
2038 Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule)
2039 << M->getFullModuleName();
2040 Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc,
2041 diag::note_previous_definition);
2042 return;
2043 }
Manman Renffd3e9d2017-01-09 19:20:18 +00002044 // When building a pch, -fmodule-name tells the compiler to textually
2045 // include headers in the specified module. We are not building the
2046 // specified module.
2047 if (getLangOpts().CompilingPCH &&
2048 M->getTopLevelModuleName() == getLangOpts().CurrentModule)
2049 return;
2050
Richard Smithd1386302017-05-04 00:29:54 +00002051 assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2052 CurLexerSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002053
Richard Smitha0aafa32015-05-18 03:52:30 +00002054 // Let the macro handling code know that any future macros are within
2055 // the new submodule.
Richard Smithd1386302017-05-04 00:29:54 +00002056 EnterSubmodule(M, HashLoc, /*ForPragma*/false);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002057
Richard Smitha0aafa32015-05-18 03:52:30 +00002058 // Let the parser know that any future declarations are within the new
2059 // submodule.
2060 // FIXME: There's no point doing this if we're handling a #__include_macros
2061 // directive.
Richard Smithc51c38b2017-04-29 00:34:47 +00002062 EnterAnnotationToken(SourceRange(HashLoc, End), tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00002063 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002064}
2065
James Dennettf6333ac2012-06-22 05:46:07 +00002066/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002067///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002068void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2069 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002070 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002071
Chris Lattnerf64b3522008-03-09 01:54:53 +00002072 // #include_next is like #include, except that we start searching after
2073 // the current found directory. If we can't do this, issue a
2074 // diagnostic.
2075 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002076 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00002077 if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2078 // If the main file is a header, then it's either for PCH/AST generation,
2079 // or libclang opened it. Either way, handle it as a normal include below
2080 // and do not complain about include_next.
2081 } else if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002082 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002083 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smithd1386302017-05-04 00:29:54 +00002084 } else if (CurLexerSubmodule) {
Richard Smith25d50752014-10-20 00:15:49 +00002085 // Start looking up in the directory *after* the one in which the current
2086 // file would be found, if any.
2087 assert(CurPPLexer && "#include_next directive in macro?");
2088 LookupFromFile = CurPPLexer->getFileEntry();
2089 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002090 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002091 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2092 } else {
2093 // Start looking up in the next directory.
2094 ++Lookup;
2095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
Richard Smith25d50752014-10-20 00:15:49 +00002097 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2098 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002099}
2100
James Dennettf6333ac2012-06-22 05:46:07 +00002101/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002102void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2103 // The Microsoft #import directive takes a type library and generates header
2104 // files from it, and includes those. This is beyond the scope of what clang
2105 // does, so we ignore it and error out. However, #import can optionally have
2106 // trailing attributes that span multiple lines. We're going to eat those
2107 // so we can continue processing from there.
2108 Diag(Tok, diag::err_pp_import_directive_ms );
2109
Taewook Oh755e4d22016-06-13 21:55:33 +00002110 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002111 // directive can be split over multiple lines using the backslash character.
2112 DiscardUntilEndOfDirective();
2113}
2114
James Dennettf6333ac2012-06-22 05:46:07 +00002115/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002116///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002117void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2118 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00002119 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002120 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002121 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002122 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002123 }
Richard Smith25d50752014-10-20 00:15:49 +00002124 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002125}
2126
Chris Lattner58a1eb02009-04-08 18:46:40 +00002127/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2128/// pseudo directive in the predefines buffer. This handles it by sucking all
2129/// tokens through the preprocessor and discarding them (only keeping the side
2130/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002131void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2132 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002133 // This directive should only occur in the predefines buffer. If not, emit an
2134 // error and reject it.
2135 SourceLocation Loc = IncludeMacrosTok.getLocation();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002136 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002137 Diag(IncludeMacrosTok.getLocation(),
2138 diag::pp_include_macros_out_of_predefines);
2139 DiscardUntilEndOfDirective();
2140 return;
2141 }
Mike Stump11289f42009-09-09 15:08:12 +00002142
Chris Lattnere01d82b2009-04-08 20:53:24 +00002143 // Treat this as a normal #include for checking purposes. If this is
2144 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002145 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002146
Chris Lattnere01d82b2009-04-08 20:53:24 +00002147 Token TmpTok;
2148 do {
2149 Lex(TmpTok);
2150 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2151 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002152}
2153
Chris Lattnerf64b3522008-03-09 01:54:53 +00002154//===----------------------------------------------------------------------===//
2155// Preprocessor Macro Directive Handling.
2156//===----------------------------------------------------------------------===//
2157
Faisal Valie8f430a2017-09-29 02:43:22 +00002158/// ReadMacroParameterList - The ( starting a parameter list of a macro
2159/// definition has just been read. Lex the rest of the parameters and the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002160/// closing ), updating MI with what we learn. Return true if an error occurs
Faisal Valie8f430a2017-09-29 02:43:22 +00002161/// parsing the param list.
Faisal Valiac506d72017-07-17 17:18:43 +00002162bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
Faisal Vali33df3912017-09-29 02:17:31 +00002163 SmallVector<IdentifierInfo*, 32> Parameters;
Mike Stump11289f42009-09-09 15:08:12 +00002164
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002165 while (true) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002166 LexUnexpandedToken(Tok);
2167 switch (Tok.getKind()) {
2168 case tok::r_paren:
Faisal Valie8f430a2017-09-29 02:43:22 +00002169 // Found the end of the parameter list.
Faisal Vali33df3912017-09-29 02:17:31 +00002170 if (Parameters.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002171 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002172 // Otherwise we have #define FOO(A,)
2173 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2174 return true;
2175 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002176 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002177 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002178 diag::warn_cxx98_compat_variadic_macro :
2179 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002180
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002181 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2182 if (LangOpts.OpenCL) {
2183 Diag(Tok, diag::err_pp_opencl_variadic_macros);
2184 return true;
2185 }
2186
Chris Lattnerf64b3522008-03-09 01:54:53 +00002187 // Lex the token after the identifier.
2188 LexUnexpandedToken(Tok);
2189 if (Tok.isNot(tok::r_paren)) {
2190 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2191 return true;
2192 }
Faisal Valie8f430a2017-09-29 02:43:22 +00002193 // Add the __VA_ARGS__ identifier as a parameter.
Faisal Vali33df3912017-09-29 02:17:31 +00002194 Parameters.push_back(Ident__VA_ARGS__);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002195 MI->setIsC99Varargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002196 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002197 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002198 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002199 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2200 return true;
2201 default:
2202 // Handle keywords and identifiers here to accept things like
2203 // #define Foo(for) for.
2204 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002205 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002206 // #define X(1
2207 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2208 return true;
2209 }
2210
Faisal Valie8f430a2017-09-29 02:43:22 +00002211 // If this is already used as a parameter, it is used multiple times (e.g.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002212 // #define X(A,A.
Faisal Vali33df3912017-09-29 02:17:31 +00002213 if (std::find(Parameters.begin(), Parameters.end(), II) !=
2214 Parameters.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002215 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002216 return true;
2217 }
Mike Stump11289f42009-09-09 15:08:12 +00002218
Faisal Valie8f430a2017-09-29 02:43:22 +00002219 // Add the parameter to the macro info.
Faisal Vali33df3912017-09-29 02:17:31 +00002220 Parameters.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002221
Chris Lattnerf64b3522008-03-09 01:54:53 +00002222 // Lex the token after the identifier.
2223 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002224
Chris Lattnerf64b3522008-03-09 01:54:53 +00002225 switch (Tok.getKind()) {
2226 default: // #define X(A B
2227 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2228 return true;
2229 case tok::r_paren: // #define X(A)
Faisal Vali33df3912017-09-29 02:17:31 +00002230 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002231 return false;
2232 case tok::comma: // #define X(A,
2233 break;
2234 case tok::ellipsis: // #define X(A... -> GCC extension
2235 // Diagnose extension.
2236 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002237
Chris Lattnerf64b3522008-03-09 01:54:53 +00002238 // Lex the token after the identifier.
2239 LexUnexpandedToken(Tok);
2240 if (Tok.isNot(tok::r_paren)) {
2241 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2242 return true;
2243 }
Mike Stump11289f42009-09-09 15:08:12 +00002244
Chris Lattnerf64b3522008-03-09 01:54:53 +00002245 MI->setIsGNUVarargs();
Faisal Vali33df3912017-09-29 02:17:31 +00002246 MI->setParameterList(Parameters, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002247 return false;
2248 }
2249 }
2250 }
2251}
2252
Serge Pavlov07c0f042014-12-18 11:14:21 +00002253static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2254 const LangOptions &LOptions) {
2255 if (MI->getNumTokens() == 1) {
2256 const Token &Value = MI->getReplacementToken(0);
2257
2258 // Macro that is identity, like '#define inline inline' is a valid pattern.
2259 if (MacroName.getKind() == Value.getKind())
2260 return true;
2261
2262 // Macro that maps a keyword to the same keyword decorated with leading/
2263 // trailing underscores is a valid pattern:
2264 // #define inline __inline
2265 // #define inline __inline__
2266 // #define inline _inline (in MS compatibility mode)
2267 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2268 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2269 if (!II->isKeyword(LOptions))
2270 return false;
2271 StringRef ValueText = II->getName();
2272 StringRef TrimmedValue = ValueText;
2273 if (!ValueText.startswith("__")) {
2274 if (ValueText.startswith("_"))
2275 TrimmedValue = TrimmedValue.drop_front(1);
2276 else
2277 return false;
2278 } else {
2279 TrimmedValue = TrimmedValue.drop_front(2);
2280 if (TrimmedValue.endswith("__"))
2281 TrimmedValue = TrimmedValue.drop_back(2);
2282 }
2283 return TrimmedValue.equals(MacroText);
2284 } else {
2285 return false;
2286 }
2287 }
2288
2289 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002290 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2291 tok::kw_const) &&
2292 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002293}
2294
Faisal Valiac506d72017-07-17 17:18:43 +00002295// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2296// entire line) of the macro's tokens and adds them to MacroInfo, and while
2297// doing so performs certain validity checks including (but not limited to):
2298// - # (stringization) is followed by a macro parameter
2299//
2300// Returns a nullptr if an invalid sequence of tokens is encountered or returns
2301// a pointer to a MacroInfo object.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002302
Faisal Valiac506d72017-07-17 17:18:43 +00002303MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2304 const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002305
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002306 Token LastTok = MacroNameTok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002307 // Create the new macro.
Faisal Valiac506d72017-07-17 17:18:43 +00002308 MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002309
Chris Lattnerf64b3522008-03-09 01:54:53 +00002310 Token Tok;
2311 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002312
Faisal Vali6bf67912017-07-25 03:15:36 +00002313 // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2314 // within their appropriate context.
2315 VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2316
Chris Lattnerf64b3522008-03-09 01:54:53 +00002317 // If this is a function-like macro definition, parse the argument list,
2318 // marking each of the identifiers as being used as macro arguments. Also,
2319 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002320 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002321 if (ImmediatelyAfterHeaderGuard) {
2322 // Save this macro information since it may part of a header guard.
2323 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2324 MacroNameTok.getLocation());
2325 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002326 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002327 } else if (Tok.hasLeadingSpace()) {
2328 // This is a normal token with leading space. Clear the leading space
2329 // marker on the first token to get proper expansion.
2330 Tok.clearFlag(Token::LeadingSpace);
2331 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002332 // This is a function-like macro definition. Read the argument list.
2333 MI->setIsFunctionLike();
Faisal Valiac506d72017-07-17 17:18:43 +00002334 if (ReadMacroParameterList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002335 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002336 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002337 DiscardUntilEndOfDirective();
Faisal Valiac506d72017-07-17 17:18:43 +00002338 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002339 }
2340
Faisal Vali6bf67912017-07-25 03:15:36 +00002341 // If this is a definition of an ISO C/C++ variadic function-like macro (not
2342 // using the GNU named varargs extension) inform our variadic scope guard
2343 // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2344 // allowed only within the definition of a variadic macro.
Mike Stump11289f42009-09-09 15:08:12 +00002345
Faisal Vali6bf67912017-07-25 03:15:36 +00002346 if (MI->isC99Varargs()) {
2347 VariadicMacroScopeGuard.enterScope();
2348 }
Mike Stump11289f42009-09-09 15:08:12 +00002349
Chris Lattnerf64b3522008-03-09 01:54:53 +00002350 // Read the first token after the arg list for down below.
2351 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002352 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002353 // C99 requires whitespace between the macro definition and the body. Emit
2354 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002355 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002356 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002357 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2358 // first character of a replacement list is not a character required by
2359 // subclause 5.2.1, then there shall be white-space separation between the
2360 // identifier and the replacement list.". 5.2.1 lists this set:
2361 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2362 // is irrelevant here.
2363 bool isInvalid = false;
2364 if (Tok.is(tok::at)) // @ is not in the list above.
2365 isInvalid = true;
2366 else if (Tok.is(tok::unknown)) {
2367 // If we have an unknown token, it is something strange like "`". Since
2368 // all of valid characters would have lexed into a single character
2369 // token of some sort, we know this is not a valid case.
2370 isInvalid = true;
2371 }
2372 if (isInvalid)
2373 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2374 else
2375 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002376 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002377
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002378 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002379 LastTok = Tok;
2380
Chris Lattnerf64b3522008-03-09 01:54:53 +00002381 // Read the rest of the macro body.
2382 if (MI->isObjectLike()) {
2383 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002384 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002385 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002386 MI->AddTokenToBody(Tok);
2387 // Get the next token of the macro.
2388 LexUnexpandedToken(Tok);
2389 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002390 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002391 // Otherwise, read the body of a function-like macro. While we are at it,
2392 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2393 // parameters in function-like macro expansions.
Faisal Vali18268422017-10-15 01:26:26 +00002394
2395 VAOptDefinitionContext VAOCtx(*this);
2396
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002397 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002398 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002399
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002400 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002401 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002402
Faisal Vali18268422017-10-15 01:26:26 +00002403 if (VAOCtx.isVAOptToken(Tok)) {
2404 // If we're already within a VAOPT, emit an error.
2405 if (VAOCtx.isInVAOpt()) {
2406 Diag(Tok, diag::err_pp_vaopt_nested_use);
2407 return nullptr;
2408 }
2409 // Ensure VAOPT is followed by a '(' .
2410 LexUnexpandedToken(Tok);
2411 if (Tok.isNot(tok::l_paren)) {
2412 Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
2413 return nullptr;
2414 }
2415 MI->AddTokenToBody(Tok);
2416 VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
2417 LexUnexpandedToken(Tok);
2418 if (Tok.is(tok::hashhash)) {
2419 Diag(Tok, diag::err_vaopt_paste_at_start);
2420 return nullptr;
2421 }
2422 continue;
2423 } else if (VAOCtx.isInVAOpt()) {
2424 if (Tok.is(tok::r_paren)) {
2425 if (VAOCtx.sawClosingParen()) {
2426 const unsigned NumTokens = MI->getNumTokens();
2427 assert(NumTokens >= 3 && "Must have seen at least __VA_OPT__( "
2428 "and a subsequent tok::r_paren");
2429 if (MI->getReplacementToken(NumTokens - 2).is(tok::hashhash)) {
2430 Diag(Tok, diag::err_vaopt_paste_at_end);
2431 return nullptr;
2432 }
2433 }
2434 } else if (Tok.is(tok::l_paren)) {
2435 VAOCtx.sawOpeningParen(Tok.getLocation());
2436 }
2437 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002438 // Get the next token of the macro.
2439 LexUnexpandedToken(Tok);
2440 continue;
2441 }
Mike Stump11289f42009-09-09 15:08:12 +00002442
Richard Smith701a3522013-07-09 01:00:29 +00002443 // If we're in -traditional mode, then we should ignore stringification
2444 // and token pasting. Mark the tokens as unknown so as not to confuse
2445 // things.
2446 if (getLangOpts().TraditionalCPP) {
2447 Tok.setKind(tok::unknown);
2448 MI->AddTokenToBody(Tok);
2449
2450 // Get the next token of the macro.
2451 LexUnexpandedToken(Tok);
2452 continue;
2453 }
2454
Eli Friedman14d3c792012-11-14 02:18:46 +00002455 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002456 // If we see token pasting, check if it looks like the gcc comma
2457 // pasting extension. We'll use this information to suppress
2458 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002459
Eli Friedman14d3c792012-11-14 02:18:46 +00002460 // Get the next token of the macro.
2461 LexUnexpandedToken(Tok);
2462
2463 if (Tok.is(tok::eod)) {
2464 MI->AddTokenToBody(LastTok);
2465 break;
2466 }
2467
2468 unsigned NumTokens = MI->getNumTokens();
2469 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2470 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2471 MI->setHasCommaPasting();
2472
David Majnemer76faf1f2013-11-05 09:30:17 +00002473 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002474 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002475 continue;
2476 }
2477
Faisal Vali18268422017-10-15 01:26:26 +00002478 // Our Token is a stringization operator.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002479 // Get the next token of the macro.
2480 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002481
Faisal Vali18268422017-10-15 01:26:26 +00002482 // Check for a valid macro arg identifier or __VA_OPT__.
2483 if (!VAOCtx.isVAOptToken(Tok) &&
2484 (Tok.getIdentifierInfo() == nullptr ||
2485 MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002486
2487 // If this is assembler-with-cpp mode, we accept random gibberish after
2488 // the '#' because '#' is often a comment character. However, change
2489 // the kind of the token to tok::unknown so that the preprocessor isn't
2490 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002491 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002492 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002493 MI->AddTokenToBody(LastTok);
2494 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002495 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002496 Diag(Tok, diag::err_pp_stringize_not_parameter)
2497 << LastTok.is(tok::hashat);
Faisal Valiac506d72017-07-17 17:18:43 +00002498 return nullptr;
Chris Lattner83bd8282009-05-25 17:16:10 +00002499 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002500 }
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattner83bd8282009-05-25 17:16:10 +00002502 // Things look ok, add the '#' and param name tokens to the macro.
2503 MI->AddTokenToBody(LastTok);
Mike Stump11289f42009-09-09 15:08:12 +00002504
Faisal Vali18268422017-10-15 01:26:26 +00002505 // If the token following '#' is VAOPT, let the next iteration handle it
2506 // and check it for correctness, otherwise add the token and prime the
2507 // loop with the next one.
2508 if (!VAOCtx.isVAOptToken(Tok)) {
2509 MI->AddTokenToBody(Tok);
2510 LastTok = Tok;
2511
2512 // Get the next token of the macro.
2513 LexUnexpandedToken(Tok);
2514 }
2515 }
2516 if (VAOCtx.isInVAOpt()) {
2517 assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
2518 Diag(Tok, diag::err_pp_expected_after)
2519 << LastTok.getKind() << tok::r_paren;
2520 Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
2521 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002522 }
2523 }
Faisal Valiac506d72017-07-17 17:18:43 +00002524 MI->setDefinitionEndLoc(LastTok.getLocation());
Faisal Valiac506d72017-07-17 17:18:43 +00002525 return MI;
2526}
2527/// HandleDefineDirective - Implements \#define. This consumes the entire macro
2528/// line then lets the caller lex the next real token.
2529void Preprocessor::HandleDefineDirective(
2530 Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2531 ++NumDefined;
2532
2533 Token MacroNameTok;
2534 bool MacroShadowsKeyword;
2535 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2536
2537 // Error reading macro name? If so, diagnostic already issued.
2538 if (MacroNameTok.is(tok::eod))
2539 return;
2540
2541 // If we are supposed to keep comments in #defines, reenable comment saving
2542 // mode.
2543 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2544
2545 MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2546 MacroNameTok, ImmediatelyAfterHeaderGuard);
2547
2548 if (!MI) return;
Mike Stump11289f42009-09-09 15:08:12 +00002549
Serge Pavlov07c0f042014-12-18 11:14:21 +00002550 if (MacroShadowsKeyword &&
2551 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2552 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
Faisal Valiac506d72017-07-17 17:18:43 +00002553 }
Chris Lattner57540c52011-04-15 05:22:18 +00002554 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002555 // replacement list.
2556 unsigned NumTokens = MI->getNumTokens();
2557 if (NumTokens != 0) {
2558 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2559 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002560 return;
2561 }
2562 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2563 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002564 return;
2565 }
2566 }
Mike Stump11289f42009-09-09 15:08:12 +00002567
Faisal Valiac506d72017-07-17 17:18:43 +00002568
Mike Stump11289f42009-09-09 15:08:12 +00002569
Chris Lattnerf64b3522008-03-09 01:54:53 +00002570 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002571 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002572 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002573 // In Objective-C, ignore attempts to directly redefine the builtin
2574 // definitions of the ownership qualifiers. It's still possible to
2575 // #undef them.
2576 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2577 return II->isStr("__strong") ||
2578 II->isStr("__weak") ||
2579 II->isStr("__unsafe_unretained") ||
2580 II->isStr("__autoreleasing");
2581 };
2582 if (getLangOpts().ObjC1 &&
2583 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2584 == getPredefinesFileID() &&
2585 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2586 // Warn if it changes the tokens.
2587 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2588 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2589 !MI->isIdenticalTo(*OtherMI, *this,
2590 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2591 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2592 }
2593 assert(!OtherMI->isWarnIfUnused());
2594 return;
2595 }
2596
Chris Lattner5244f342009-01-16 19:50:11 +00002597 // It is very common for system headers to have tons of macro redefinitions
2598 // and for warnings to be disabled in system headers. If this is the case,
2599 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002600 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002601 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002602 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002603 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002604
Taewook Oh755e4d22016-06-13 21:55:33 +00002605 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002606 // C++ [cpp.predefined]p4, but allow it as an extension.
2607 if (OtherMI->isBuiltinMacro())
2608 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002609 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002610 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002611 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002612 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002613 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2614 << MacroNameTok.getIdentifierInfo();
2615 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2616 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002617 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002618 if (OtherMI->isWarnIfUnused())
2619 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002620 }
Mike Stump11289f42009-09-09 15:08:12 +00002621
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002622 DefMacroDirective *MD =
2623 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002624
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002625 assert(!MI->isUsed());
2626 // If we need warning for not using the macro, add its location in the
2627 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002628 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002629 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002630 MI->setIsWarnIfUnused(true);
2631 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2632 }
2633
Chris Lattner928e9092009-04-12 01:39:54 +00002634 // If the callbacks want to know, tell them about the macro definition.
2635 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002636 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002637}
2638
James Dennettf6333ac2012-06-22 05:46:07 +00002639/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002640///
Erik Verbruggen4bddef92016-10-26 08:52:41 +00002641void Preprocessor::HandleUndefDirective() {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002642 ++NumUndefined;
2643
2644 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002645 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002646
Chris Lattnerf64b3522008-03-09 01:54:53 +00002647 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002648 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002649 return;
Mike Stump11289f42009-09-09 15:08:12 +00002650
Chris Lattnerf64b3522008-03-09 01:54:53 +00002651 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002652 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002653
Richard Smith20e883e2015-04-29 23:20:19 +00002654 // Okay, we have a valid identifier to undef.
2655 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002656 auto MD = getMacroDefinition(II);
Vedant Kumar349a6242017-04-26 21:05:44 +00002657 UndefMacroDirective *Undef = nullptr;
2658
2659 // If the macro is not defined, this is a noop undef.
2660 if (const MacroInfo *MI = MD.getMacroInfo()) {
2661 if (!MI->isUsed() && MI->isWarnIfUnused())
2662 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2663
2664 if (MI->isWarnIfUnused())
2665 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2666
2667 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
2668 }
Mike Stump11289f42009-09-09 15:08:12 +00002669
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002670 // If the callbacks want to know, tell them about the macro #undef.
2671 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002672 if (Callbacks)
Vedant Kumar349a6242017-04-26 21:05:44 +00002673 Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002674
Vedant Kumar349a6242017-04-26 21:05:44 +00002675 if (Undef)
2676 appendMacroDirective(II, Undef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002677}
2678
Chris Lattnerf64b3522008-03-09 01:54:53 +00002679//===----------------------------------------------------------------------===//
2680// Preprocessor Conditional Directive Handling.
2681//===----------------------------------------------------------------------===//
2682
James Dennettf6333ac2012-06-22 05:46:07 +00002683/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2684/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2685/// true if any tokens have been returned or pp-directives activated before this
2686/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002687///
Vedant Kumar3919a502017-09-11 20:47:42 +00002688void Preprocessor::HandleIfdefDirective(Token &Result,
2689 const Token &HashToken,
2690 bool isIfndef,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002691 bool ReadAnyTokensBeforeDirective) {
2692 ++NumIf;
2693 Token DirectiveTok = Result;
2694
2695 Token MacroNameTok;
2696 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002697
Chris Lattnerf64b3522008-03-09 01:54:53 +00002698 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002699 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002700 // Skip code until we get to #endif. This helps with recovery by not
2701 // emitting an error when the #endif is reached.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002702 SkipExcludedConditionalBlock(HashToken.getLocation(),
2703 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002704 /*Foundnonskip*/ false, /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002705 return;
2706 }
Mike Stump11289f42009-09-09 15:08:12 +00002707
Chris Lattnerf64b3522008-03-09 01:54:53 +00002708 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002709 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002710
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002711 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002712 auto MD = getMacroDefinition(MII);
2713 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002714
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002715 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002716 // If the start of a top-level #ifdef and if the macro is not defined,
2717 // inform MIOpt that this might be the start of a proper include guard.
2718 // Otherwise it is some other form of unknown conditional which we can't
2719 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002720 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002721 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002722 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002723 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002724 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002725 }
2726
Chris Lattnerf64b3522008-03-09 01:54:53 +00002727 // If there is a macro, process it.
2728 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002729 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002730
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002731 if (Callbacks) {
2732 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002733 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002734 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002735 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002736 }
2737
Chris Lattnerf64b3522008-03-09 01:54:53 +00002738 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002739 if (PPOpts->SingleFileParseMode && !MI) {
2740 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2741 // the directive blocks.
2742 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002743 /*wasskip*/false, /*foundnonskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002744 /*foundelse*/false);
2745 } else if (!MI == isIfndef) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002746 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002747 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2748 /*wasskip*/false, /*foundnonskip*/true,
2749 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002750 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002751 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002752 SkipExcludedConditionalBlock(HashToken.getLocation(),
2753 DirectiveTok.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002754 /*Foundnonskip*/ false,
2755 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002756 }
2757}
2758
James Dennettf6333ac2012-06-22 05:46:07 +00002759/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002760///
2761void Preprocessor::HandleIfDirective(Token &IfToken,
Vedant Kumar3919a502017-09-11 20:47:42 +00002762 const Token &HashToken,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002763 bool ReadAnyTokensBeforeDirective) {
2764 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002765
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002766 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002767 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002768 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002769 const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
2770 const bool ConditionalTrue = DER.Conditional;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002771 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002772
2773 // If this condition is equivalent to #ifndef X, and if this is the first
2774 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002775 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002776 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002777 // FIXME: Pass in the location of the macro name, not the 'if' token.
2778 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002779 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002780 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002781 }
2782
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002783 if (Callbacks)
2784 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002785 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002786 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002787
Chris Lattnerf64b3522008-03-09 01:54:53 +00002788 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002789 if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
2790 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2791 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002792 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002793 /*foundnonskip*/false, /*foundelse*/false);
2794 } else if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002795 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002796 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002797 /*foundnonskip*/true, /*foundelse*/false);
2798 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002799 // No, skip the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002800 SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
Vedant Kumar3919a502017-09-11 20:47:42 +00002801 /*Foundnonskip*/ false,
2802 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002803 }
2804}
2805
James Dennettf6333ac2012-06-22 05:46:07 +00002806/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002807///
2808void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2809 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002810
Chris Lattnerf64b3522008-03-09 01:54:53 +00002811 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002812 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002813
Chris Lattnerf64b3522008-03-09 01:54:53 +00002814 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002815 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002816 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002817 Diag(EndifToken, diag::err_pp_endif_without_if);
2818 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002819 }
Mike Stump11289f42009-09-09 15:08:12 +00002820
Chris Lattnerf64b3522008-03-09 01:54:53 +00002821 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002822 if (CurPPLexer->getConditionalStackDepth() == 0)
2823 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002824
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002825 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002826 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002827
2828 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002829 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002830}
2831
James Dennettf6333ac2012-06-22 05:46:07 +00002832/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002833///
Vedant Kumar3919a502017-09-11 20:47:42 +00002834void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002835 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002836
Chris Lattnerf64b3522008-03-09 01:54:53 +00002837 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002838 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002839
Chris Lattnerf64b3522008-03-09 01:54:53 +00002840 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002841 if (CurPPLexer->popConditionalLevel(CI)) {
2842 Diag(Result, diag::pp_err_else_without_if);
2843 return;
2844 }
Mike Stump11289f42009-09-09 15:08:12 +00002845
Chris Lattnerf64b3522008-03-09 01:54:53 +00002846 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002847 if (CurPPLexer->getConditionalStackDepth() == 0)
2848 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002849
2850 // If this is a #else with a #else before it, report the error.
2851 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002852
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002853 if (Callbacks)
2854 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2855
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002856 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002857 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2858 // the directive blocks.
2859 CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002860 /*foundnonskip*/false, /*foundelse*/true);
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002861 return;
2862 }
2863
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002864 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002865 SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
2866 /*Foundnonskip*/ true,
Vedant Kumar3919a502017-09-11 20:47:42 +00002867 /*FoundElse*/ true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002868}
2869
James Dennettf6333ac2012-06-22 05:46:07 +00002870/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002871///
Vedant Kumar3919a502017-09-11 20:47:42 +00002872void Preprocessor::HandleElifDirective(Token &ElifToken,
2873 const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002874 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002875
Chris Lattnerf64b3522008-03-09 01:54:53 +00002876 // #elif directive in a non-skipping conditional... start skipping.
2877 // We don't care what the condition is, because we will always skip it (since
2878 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002879 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002880 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002881 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002882
2883 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002884 if (CurPPLexer->popConditionalLevel(CI)) {
2885 Diag(ElifToken, diag::pp_err_elif_without_if);
2886 return;
2887 }
Mike Stump11289f42009-09-09 15:08:12 +00002888
Chris Lattnerf64b3522008-03-09 01:54:53 +00002889 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002890 if (CurPPLexer->getConditionalStackDepth() == 0)
2891 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002892
Chris Lattnerf64b3522008-03-09 01:54:53 +00002893 // If this is a #elif with a #else before it, report the error.
2894 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Taewook Oh755e4d22016-06-13 21:55:33 +00002895
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002896 if (Callbacks)
2897 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002898 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002899 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002900
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002901 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002902 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2903 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002904 CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002905 /*foundnonskip*/false, /*foundelse*/false);
2906 return;
2907 }
2908
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002909 // Finally, skip the rest of the contents of this block.
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002910 SkipExcludedConditionalBlock(
2911 HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
2912 /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002913}