blob: 1d8056eb75f8c01d3c5b5d309aec25ca36cbdfd7 [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.
Vedant Kumar3919a502017-09-11 20:47:42 +0000353void Preprocessor::SkipExcludedConditionalBlock(const Token &HashToken,
354 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
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000361 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000363
Ted Kremenek56572ab2008-12-12 18:34:08 +0000364 if (CurPTHLexer) {
365 PTHSkipExcludedConditionalBlock();
366 return;
367 }
Mike Stump11289f42009-09-09 15:08:12 +0000368
Chris Lattnerf64b3522008-03-09 01:54:53 +0000369 // Enter raw mode to disable identifier lookup (and thus macro expansion),
370 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000371 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000372 Token Tok;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000373 while (true) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000374 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000375
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000376 if (Tok.is(tok::code_completion)) {
377 if (CodeComplete)
378 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000379 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000380 continue;
381 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000382
Chris Lattnerf64b3522008-03-09 01:54:53 +0000383 // If this is the end of the buffer, we have an error.
384 if (Tok.is(tok::eof)) {
Ilya Biryukov8f738ac2017-09-12 08:35:57 +0000385 // We don't emit errors for unterminated conditionals here,
386 // Lexer::LexEndOfFile can do that propertly.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000387 // Just return and let the caller lex after this #include.
388 break;
389 }
Mike Stump11289f42009-09-09 15:08:12 +0000390
Chris Lattnerf64b3522008-03-09 01:54:53 +0000391 // If this token is not a preprocessor directive, just skip it.
392 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
393 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattnerf64b3522008-03-09 01:54:53 +0000395 // We just parsed a # character at the start of a line, so we're in
396 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000397 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000398 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000399 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000400
Mike Stump11289f42009-09-09 15:08:12 +0000401
Chris Lattnerf64b3522008-03-09 01:54:53 +0000402 // Read the next token, the directive flavor.
403 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000404
Chris Lattnerf64b3522008-03-09 01:54:53 +0000405 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
406 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000407 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000408 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000409 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000410 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000411 continue;
412 }
413
414 // If the first letter isn't i or e, it isn't intesting to us. We know that
415 // this is safe in the face of spelling differences, because there is no way
416 // to spell an i/e in a strange way that is another letter. Skipping this
417 // allows us to avoid looking up the identifier info for #define/#undef and
418 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000419 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000420
Alp Toker2d57cea2014-05-17 04:53:25 +0000421 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000422 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000423 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000424 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000425 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000426 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000427 continue;
428 }
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattnerf64b3522008-03-09 01:54:53 +0000430 // Get the identifier name without trigraphs or embedded newlines. Note
431 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
432 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000433 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000434 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000435 if (!Tok.needsCleaning() && RI.size() < 20) {
436 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000437 } else {
438 std::string DirectiveStr = getSpelling(Tok);
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000439 size_t IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000440 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000441 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000442 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000443 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000444 continue;
445 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000446 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000447 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000448 }
Mike Stump11289f42009-09-09 15:08:12 +0000449
Benjamin Kramer144884642009-12-31 13:32:38 +0000450 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000451 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000452 if (Sub.empty() || // "if"
453 Sub == "def" || // "ifdef"
454 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000455 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
456 // bother parsing the condition.
457 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000458 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000459 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000460 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000461 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000462 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000463 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000464 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000465 PPConditionalInfo CondInfo;
466 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000467 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000468 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000469 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000470
Chris Lattnerf64b3522008-03-09 01:54:53 +0000471 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000472 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000473 // Restore the value of LexingRawMode so that trailing comments
474 // are handled correctly, if we've reached the outermost block.
475 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000476 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000477 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000478 if (Callbacks)
479 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000480 break;
Richard Smithd0124572012-06-21 00:35:03 +0000481 } else {
482 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000483 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000484 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000485 // #else directive in a skipping conditional. If not in some other
486 // skipping conditional, and if #else hasn't already been seen, enter it
487 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000488 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000489
Chris Lattnerf64b3522008-03-09 01:54:53 +0000490 // If this is a #else with a #else before it, report the error.
491 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000492
Chris Lattnerf64b3522008-03-09 01:54:53 +0000493 // Note that we've seen a #else in this conditional.
494 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattnerf64b3522008-03-09 01:54:53 +0000496 // If the conditional is at the top level, and the #if block wasn't
497 // entered, enter the #else block now.
498 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
499 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000500 // Restore the value of LexingRawMode so that trailing comments
501 // are handled correctly.
502 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000503 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000504 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000505 if (Callbacks)
506 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000507 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000508 } else {
509 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000510 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000511 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000512 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000513
John Thompson17c35732013-12-04 20:19:30 +0000514 // If this is a #elif with a #else before it, report the error.
515 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
516
Chris Lattnerf64b3522008-03-09 01:54:53 +0000517 // If this is in a skipping block or if we're already handled this #if
518 // block, don't bother parsing the condition.
519 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
520 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000521 } else {
John Thompson17c35732013-12-04 20:19:30 +0000522 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000523 // Restore the value of LexingRawMode so that identifiers are
524 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000525 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
526 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000527 IdentifierInfo *IfNDefMacro = nullptr;
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +0000528 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro).Conditional;
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000529 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000530 if (Callbacks) {
531 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000532 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000533 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000534 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000535 }
536 // If this condition is true, enter it!
537 if (CondValue) {
538 CondInfo.FoundNonSkip = true;
539 break;
540 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000541 }
542 }
543 }
Mike Stump11289f42009-09-09 15:08:12 +0000544
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000545 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000546 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000547 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000548 }
549
550 // Finally, if we are out of the conditional (saw an #endif or ran off the end
551 // of the file, just stop skipping and return to lexing whatever came after
552 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000553 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000554
Vedant Kumar3919a502017-09-11 20:47:42 +0000555 if (Callbacks)
556 Callbacks->SourceRangeSkipped(
557 SourceRange(HashToken.getLocation(), CurPPLexer->getSourceLocation()),
558 Tok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000559}
560
Ted Kremenek56572ab2008-12-12 18:34:08 +0000561void Preprocessor::PTHSkipExcludedConditionalBlock() {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000562 while (true) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000563 assert(CurPTHLexer);
564 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000565
Ted Kremenek56572ab2008-12-12 18:34:08 +0000566 // Skip to the next '#else', '#elif', or #endif.
567 if (CurPTHLexer->SkipBlock()) {
568 // We have reached an #endif. Both the '#' and 'endif' tokens
569 // have been consumed by the PTHLexer. Just pop off the condition level.
570 PPConditionalInfo CondInfo;
571 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000572 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000573 assert(!InCond && "Can't be skipping if not in a conditional!");
574 break;
575 }
Mike Stump11289f42009-09-09 15:08:12 +0000576
Ted Kremenek56572ab2008-12-12 18:34:08 +0000577 // We have reached a '#else' or '#elif'. Lex the next token to get
578 // the directive flavor.
579 Token Tok;
580 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000581
Ted Kremenek56572ab2008-12-12 18:34:08 +0000582 // We can actually look up the IdentifierInfo here since we aren't in
583 // raw mode.
584 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
585
586 if (K == tok::pp_else) {
587 // #else: Enter the else condition. We aren't in a nested condition
588 // since we skip those. We're always in the one matching the last
589 // blocked we skipped.
590 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
591 // Note that we've seen a #else in this conditional.
592 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000593
Ted Kremenek56572ab2008-12-12 18:34:08 +0000594 // If the #if block wasn't entered then enter the #else block now.
595 if (!CondInfo.FoundNonSkip) {
596 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000597
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000598 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000599 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000600 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000601 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Ted Kremenek56572ab2008-12-12 18:34:08 +0000603 break;
604 }
Mike Stump11289f42009-09-09 15:08:12 +0000605
Ted Kremenek56572ab2008-12-12 18:34:08 +0000606 // Otherwise skip this block.
607 continue;
608 }
Mike Stump11289f42009-09-09 15:08:12 +0000609
Ted Kremenek56572ab2008-12-12 18:34:08 +0000610 assert(K == tok::pp_elif);
611 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
612
613 // If this is a #elif with a #else before it, report the error.
614 if (CondInfo.FoundElse)
615 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000616
Ted Kremenek56572ab2008-12-12 18:34:08 +0000617 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000618 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000619 if (CondInfo.FoundNonSkip)
620 continue;
621
622 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000623 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000624 CurPTHLexer->ParsingPreprocessorDirective = true;
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +0000625 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro).Conditional;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000626 CurPTHLexer->ParsingPreprocessorDirective = false;
627
628 // If this condition is true, enter it!
629 if (ShouldEnter) {
630 CondInfo.FoundNonSkip = true;
631 break;
632 }
633
634 // Otherwise, skip this block and go to the next one.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000635 }
636}
637
Richard Smith2a553082015-04-23 22:58:06 +0000638Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000639 if (!SourceMgr.isInMainFile(Loc)) {
640 // Try to determine the module of the include directive.
641 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
642 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
643 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
644 // The include comes from an included file.
645 return HeaderInfo.getModuleMap()
646 .findModuleForHeader(EntryOfIncl)
647 .getModule();
648 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000649 }
Richard Smith7e82e012016-02-19 22:25:36 +0000650
651 // This is either in the main file or not in a file at all. It belongs
652 // to the current module, if there is one.
653 return getLangOpts().CurrentModule.empty()
654 ? nullptr
655 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000656}
657
Richard Smith4eb83932016-04-27 21:57:05 +0000658const FileEntry *
659Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000660 Module *M,
Richard Smith4eb83932016-04-27 21:57:05 +0000661 SourceLocation Loc) {
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000662 assert(M && "no module to include");
663
Richard Smith4eb83932016-04-27 21:57:05 +0000664 // If we have a module import syntax, we shouldn't include a header to
665 // make a particular module visible.
666 if (getLangOpts().ObjC2)
667 return nullptr;
668
Richard Smith4eb83932016-04-27 21:57:05 +0000669 Module *TopM = M->getTopLevelModule();
670 Module *IncM = getModuleForLocation(IncLoc);
671
672 // Walk up through the include stack, looking through textual headers of M
673 // until we hit a non-textual header that we can #include. (We assume textual
674 // headers of a module with non-textual headers aren't meant to be used to
675 // import entities from the module.)
676 auto &SM = getSourceManager();
677 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
678 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
679 auto *FE = SM.getFileEntryForID(ID);
Richard Smith040e1262017-06-02 01:55:39 +0000680 if (!FE)
681 break;
Richard Smith4eb83932016-04-27 21:57:05 +0000682
683 bool InTextualHeader = false;
684 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
685 if (!Header.getModule()->isSubModuleOf(TopM))
686 continue;
687
688 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
689 // If this is an accessible, non-textual header of M's top-level module
690 // that transitively includes the given location and makes the
691 // corresponding module visible, this is the thing to #include.
692 if (Header.isAccessibleFrom(IncM))
693 return FE;
694
695 // It's in a private header; we can't #include it.
696 // FIXME: If there's a public header in some module that re-exports it,
697 // then we could suggest including that, but it's not clear that's the
698 // expected way to make this entity visible.
699 continue;
700 }
701
702 InTextualHeader = true;
703 }
704
705 if (!InTextualHeader)
706 break;
707
708 Loc = SM.getIncludeLoc(ID);
709 }
710
711 return nullptr;
712}
713
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000714const FileEntry *Preprocessor::LookupFile(
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000715 SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
716 const DirectoryLookup *FromDir, const FileEntry *FromFile,
717 const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000718 SmallVectorImpl<char> *RelativePath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000719 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000720 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000721 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000722
Will Wilson0fafd342013-12-27 19:46:16 +0000723 // If the header lookup mechanism may be relative to the current inclusion
724 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000725 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
726 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000727 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000728 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000729 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000730 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000731
Chris Lattner022923a2009-02-04 19:45:07 +0000732 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000733 // predefines buffer or the module includes buffer. Any other file is not
734 // lexed with a normal lexer, so it won't be scanned for preprocessor
735 // directives.
736 //
737 // If we have the predefines buffer, resolve #include references (which come
738 // from the -include command line argument) from the current working
739 // directory instead of relative to the main file.
740 //
741 // If we have the module includes buffer, resolve #include references (which
742 // come from header declarations in the module map) relative to the module
743 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000744 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000745 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000746 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000747 BuildSystemModule = getCurrentModule()->IsSystem;
748 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000749 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000750 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
751 } else {
752 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
753 }
Will Wilson0fafd342013-12-27 19:46:16 +0000754
755 // MSVC searches the current include stack from top to bottom for
756 // headers included by quoted include directives.
757 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000758 if (LangOpts.MSVCCompat && !isAngled) {
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000759 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000760 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000761 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000762 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000763 }
Chris Lattner022923a2009-02-04 19:45:07 +0000764 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000765 }
Mike Stump11289f42009-09-09 15:08:12 +0000766
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000767 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000768
769 if (FromFile) {
770 // We're supposed to start looking from after a particular file. Search
771 // the include path until we find that file or run out of files.
772 const DirectoryLookup *TmpCurDir = CurDir;
773 const DirectoryLookup *TmpFromDir = nullptr;
774 while (const FileEntry *FE = HeaderInfo.LookupFile(
775 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000776 Includers, SearchPath, RelativePath, RequestingModule,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000777 SuggestedModule, /*IsMapped=*/nullptr, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000778 // Keep looking as if this file did a #include_next.
779 TmpFromDir = TmpCurDir;
780 ++TmpFromDir;
781 if (FE == FromFile) {
782 // Found it.
783 FromDir = TmpFromDir;
784 CurDir = TmpCurDir;
785 break;
786 }
787 }
788 }
789
790 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000791 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000792 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000793 RelativePath, RequestingModule, SuggestedModule, IsMapped, SkipCache,
Manman Rene4a5d372016-05-17 02:15:12 +0000794 BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000795 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000796 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000797 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000798 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
799 Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000800 return FE;
801 }
Mike Stump11289f42009-09-09 15:08:12 +0000802
Will Wilson0fafd342013-12-27 19:46:16 +0000803 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000804 // Otherwise, see if this is a subframework header. If so, this is relative
805 // to one of the headers on the #include stack. Walk the list of the current
806 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000807 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000808 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000809 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000810 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000811 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000812 SuggestedModule))) {
813 if (SuggestedModule && !LangOpts.AsmPreprocessor)
814 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000815 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
816 Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000817 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000818 }
819 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000820 }
Mike Stump11289f42009-09-09 15:08:12 +0000821
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000822 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000823 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000824 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000825 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000826 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000827 RequestingModule, SuggestedModule))) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000828 if (SuggestedModule && !LangOpts.AsmPreprocessor)
829 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000830 RequestingModule, RequestingModuleIsModuleInterface,
831 FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000832 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000833 }
834 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000835 }
836 }
Mike Stump11289f42009-09-09 15:08:12 +0000837
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000838 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000839 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000840}
841
Chris Lattnerf64b3522008-03-09 01:54:53 +0000842//===----------------------------------------------------------------------===//
843// Preprocessor Directive Handling.
844//===----------------------------------------------------------------------===//
845
David Blaikied5321242012-06-06 18:52:13 +0000846class Preprocessor::ResetMacroExpansionHelper {
847public:
848 ResetMacroExpansionHelper(Preprocessor *pp)
849 : PP(pp), save(pp->DisableMacroExpansion) {
850 if (pp->MacroExpansionInDirectivesOverride)
851 pp->DisableMacroExpansion = false;
852 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000853
David Blaikied5321242012-06-06 18:52:13 +0000854 ~ResetMacroExpansionHelper() {
855 PP->DisableMacroExpansion = save;
856 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000857
David Blaikied5321242012-06-06 18:52:13 +0000858private:
859 Preprocessor *PP;
860 bool save;
861};
862
Chris Lattnerf64b3522008-03-09 01:54:53 +0000863/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000864/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000865/// lexer/preprocessor state, and advances the lexer(s) so that the next token
866/// read is the correct one.
867void Preprocessor::HandleDirective(Token &Result) {
868 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000869
Chris Lattnerf64b3522008-03-09 01:54:53 +0000870 // We just parsed a # character at the start of a line, so we're in directive
871 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000872 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000873 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000874 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000875
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000876 bool ImmediatelyAfterTopLevelIfndef =
877 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
878 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
879
Chris Lattnerf64b3522008-03-09 01:54:53 +0000880 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000881
Chris Lattnerf64b3522008-03-09 01:54:53 +0000882 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000883 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000884 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000885 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000886
Chris Lattner2d17ab72009-03-18 21:00:25 +0000887 // Save the '#' token in case we need to return it later.
888 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000889
Chris Lattnerf64b3522008-03-09 01:54:53 +0000890 // Read the next token, the directive flavor. This isn't expanded due to
891 // C99 6.10.3p8.
892 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000893
Chris Lattnerf64b3522008-03-09 01:54:53 +0000894 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
895 // #define A(x) #x
896 // A(abc
897 // #warning blah
898 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000899 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
900 // not support this for #include-like directives, since that can result in
901 // terrible diagnostics, and does not work in GCC.
902 if (InMacroArgs) {
903 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
904 switch (II->getPPKeywordID()) {
905 case tok::pp_include:
906 case tok::pp_import:
907 case tok::pp_include_next:
908 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000909 case tok::pp_pragma:
910 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000911 DiscardUntilEndOfDirective();
912 return;
913 default:
914 break;
915 }
916 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000917 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000918 }
Mike Stump11289f42009-09-09 15:08:12 +0000919
David Blaikied5321242012-06-06 18:52:13 +0000920 // Temporarily enable macro expansion if set so
921 // and reset to previous state when returning from this function.
922 ResetMacroExpansionHelper helper(this);
923
Chris Lattnerf64b3522008-03-09 01:54:53 +0000924 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000925 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000926 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000927 case tok::code_completion:
928 if (CodeComplete)
929 CodeComplete->CodeCompleteDirective(
930 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000931 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000932 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000933 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000934 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000935 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000936 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000937 default:
938 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000939 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattnerf64b3522008-03-09 01:54:53 +0000941 // Ask what the preprocessor keyword ID is.
942 switch (II->getPPKeywordID()) {
943 default: break;
944 // C99 6.10.1 - Conditional Inclusion.
945 case tok::pp_if:
Vedant Kumar3919a502017-09-11 20:47:42 +0000946 return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000947 case tok::pp_ifdef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000948 return HandleIfdefDirective(Result, SavedHash, false,
949 true /*not valid for miopt*/);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000950 case tok::pp_ifndef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000951 return HandleIfdefDirective(Result, SavedHash, true,
952 ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000953 case tok::pp_elif:
Vedant Kumar3919a502017-09-11 20:47:42 +0000954 return HandleElifDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000955 case tok::pp_else:
Vedant Kumar3919a502017-09-11 20:47:42 +0000956 return HandleElseDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000957 case tok::pp_endif:
958 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000959
Chris Lattnerf64b3522008-03-09 01:54:53 +0000960 // C99 6.10.2 - Source File Inclusion.
961 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000962 // Handle #include.
963 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000964 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000965 // Handle -imacros.
Taewook Oh755e4d22016-06-13 21:55:33 +0000966 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Chris Lattnerf64b3522008-03-09 01:54:53 +0000968 // C99 6.10.3 - Macro Replacement.
969 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000970 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000971 case tok::pp_undef:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000972 return HandleUndefDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000973
974 // C99 6.10.4 - Line Control.
975 case tok::pp_line:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000976 return HandleLineDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000977
Chris Lattnerf64b3522008-03-09 01:54:53 +0000978 // C99 6.10.5 - Error Directive.
979 case tok::pp_error:
980 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000981
Chris Lattnerf64b3522008-03-09 01:54:53 +0000982 // C99 6.10.6 - Pragma Directive.
983 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000984 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattnerf64b3522008-03-09 01:54:53 +0000986 // GNU Extensions.
987 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000988 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000989 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000990 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Chris Lattnerf64b3522008-03-09 01:54:53 +0000992 case tok::pp_warning:
993 Diag(Result, diag::ext_pp_warning_directive);
994 return HandleUserDiagnosticDirective(Result, true);
995 case tok::pp_ident:
996 return HandleIdentSCCSDirective(Result);
997 case tok::pp_sccs:
998 return HandleIdentSCCSDirective(Result);
999 case tok::pp_assert:
1000 //isExtension = true; // FIXME: implement #assert
1001 break;
1002 case tok::pp_unassert:
1003 //isExtension = true; // FIXME: implement #unassert
1004 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001005
Douglas Gregor663b48f2012-01-03 19:48:16 +00001006 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001007 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001008 return HandleMacroPublicDirective(Result);
1009 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001010
Douglas Gregor663b48f2012-01-03 19:48:16 +00001011 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001012 if (getLangOpts().Modules)
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001013 return HandleMacroPrivateDirective();
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001014 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001015 }
1016 break;
1017 }
Mike Stump11289f42009-09-09 15:08:12 +00001018
Chris Lattner2d17ab72009-03-18 21:00:25 +00001019 // If this is a .S file, treat unknown # directives as non-preprocessor
1020 // directives. This is important because # may be a comment or introduce
1021 // various pseudo-ops. Just return the # token and push back the following
1022 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001023 if (getLangOpts().AsmPreprocessor) {
David Blaikie2eabcc92016-02-09 18:52:09 +00001024 auto Toks = llvm::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001025 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001026 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001027 Toks[1] = Result;
Taewook Oh755e4d22016-06-13 21:55:33 +00001028
Chris Lattner56f64c12011-01-06 05:01:51 +00001029 // If the second token is a hashhash token, then we need to translate it to
1030 // unknown so the token lexer doesn't try to perform token pasting.
1031 if (Result.is(tok::hashhash))
1032 Toks[1].setKind(tok::unknown);
Taewook Oh755e4d22016-06-13 21:55:33 +00001033
Chris Lattner2d17ab72009-03-18 21:00:25 +00001034 // Enter this token stream so that we re-lex the tokens. Make sure to
1035 // enable macro expansion, in case the token after the # is an identifier
1036 // that is expanded.
David Blaikie2eabcc92016-02-09 18:52:09 +00001037 EnterTokenStream(std::move(Toks), 2, false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001038 return;
1039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040
Chris Lattnerf64b3522008-03-09 01:54:53 +00001041 // If we reached here, the preprocessing token is not valid!
1042 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001043
Chris Lattnerf64b3522008-03-09 01:54:53 +00001044 // Read the rest of the PP line.
1045 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001046
Chris Lattnerf64b3522008-03-09 01:54:53 +00001047 // Okay, we're done parsing the directive.
1048}
1049
Chris Lattner76e68962009-01-26 06:19:46 +00001050/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1051/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1052static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001053 unsigned DiagID, Preprocessor &PP,
1054 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001055 if (DigitTok.isNot(tok::numeric_constant)) {
1056 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001057
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001058 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001059 PP.DiscardUntilEndOfDirective();
1060 return true;
1061 }
Mike Stump11289f42009-09-09 15:08:12 +00001062
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001063 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001064 IntegerBuffer.resize(DigitTok.getLength());
1065 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001066 bool Invalid = false;
1067 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1068 if (Invalid)
1069 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001070
Chris Lattnerd66f1722009-04-18 18:35:15 +00001071 // Verify that we have a simple digit-sequence, and compute the value. This
1072 // is always a simple digit string computed in decimal, so we do this manually
1073 // here.
1074 Val = 0;
1075 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001076 // C++1y [lex.fcon]p1:
1077 // Optional separating single quotes in a digit-sequence are ignored
1078 if (DigitTokBegin[i] == '\'')
1079 continue;
1080
Jordan Rosea7d03842013-02-08 22:30:41 +00001081 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001082 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001083 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001084 PP.DiscardUntilEndOfDirective();
1085 return true;
1086 }
Mike Stump11289f42009-09-09 15:08:12 +00001087
Chris Lattnerd66f1722009-04-18 18:35:15 +00001088 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1089 if (NextVal < Val) { // overflow.
1090 PP.Diag(DigitTok, DiagID);
1091 PP.DiscardUntilEndOfDirective();
1092 return true;
1093 }
1094 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001095 }
Mike Stump11289f42009-09-09 15:08:12 +00001096
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001097 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001098 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1099 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001100
Chris Lattner76e68962009-01-26 06:19:46 +00001101 return false;
1102}
1103
James Dennettf6333ac2012-06-22 05:46:07 +00001104/// \brief Handle a \#line directive: C99 6.10.4.
1105///
1106/// The two acceptable forms are:
1107/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001108/// # line digit-sequence
1109/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001110/// \endverbatim
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001111void Preprocessor::HandleLineDirective() {
Chris Lattner100c65e2009-01-26 05:29:08 +00001112 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1113 // expanded.
1114 Token DigitTok;
1115 Lex(DigitTok);
1116
Chris Lattner100c65e2009-01-26 05:29:08 +00001117 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001118 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001119 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001120 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001121
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001122 if (LineNo == 0)
1123 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001124
Chris Lattner76e68962009-01-26 06:19:46 +00001125 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1126 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001127 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001128 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001129 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001130 if (LineNo >= LineLimit)
1131 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001132 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001133 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001134
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001135 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001136 Token StrTok;
1137 Lex(StrTok);
1138
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001139 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1140 // string followed by eod.
1141 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001142 ; // ok
1143 else if (StrTok.isNot(tok::string_literal)) {
1144 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001145 return DiscardUntilEndOfDirective();
1146 } else if (StrTok.hasUDSuffix()) {
1147 Diag(StrTok, diag::err_invalid_string_udl);
1148 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001149 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001150 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001151 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001152 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001153 if (Literal.hadError)
1154 return DiscardUntilEndOfDirective();
1155 if (Literal.Pascal) {
1156 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1157 return DiscardUntilEndOfDirective();
1158 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001159 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001160
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001161 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001162 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1163 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001164 }
Mike Stump11289f42009-09-09 15:08:12 +00001165
Reid Klecknereb00ee02017-05-22 21:42:58 +00001166 // Take the file kind of the file containing the #line directive. #line
1167 // directives are often used for generated sources from the same codebase, so
1168 // the new file should generally be classified the same way as the current
1169 // file. This is visible in GCC's pre-processed output, which rewrites #line
1170 // to GNU line markers.
1171 SrcMgr::CharacteristicKind FileKind =
1172 SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1173
1174 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1175 false, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001176
Chris Lattner839150e2009-03-27 17:13:49 +00001177 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001178 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Reid Klecknereb00ee02017-05-22 21:42:58 +00001179 PPCallbacks::RenameFile, FileKind);
Chris Lattner100c65e2009-01-26 05:29:08 +00001180}
1181
Chris Lattner76e68962009-01-26 06:19:46 +00001182/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1183/// marker directive.
1184static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
Reid Klecknereb00ee02017-05-22 21:42:58 +00001185 SrcMgr::CharacteristicKind &FileKind,
Chris Lattner76e68962009-01-26 06:19:46 +00001186 Preprocessor &PP) {
1187 unsigned FlagVal;
1188 Token FlagTok;
1189 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001190 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001191 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1192 return true;
1193
1194 if (FlagVal == 1) {
1195 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001196
Chris Lattner76e68962009-01-26 06:19:46 +00001197 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 } else if (FlagVal == 2) {
1202 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001203
Chris Lattner1c967782009-02-04 06:25:26 +00001204 SourceManager &SM = PP.getSourceManager();
1205 // If we are leaving the current presumed file, check to make sure the
1206 // presumed include stack isn't empty!
1207 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001208 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001209 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001210 if (PLoc.isInvalid())
1211 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001212
Chris Lattner1c967782009-02-04 06:25:26 +00001213 // If there is no include loc (main file) or if the include loc is in a
1214 // different physical file, then we aren't in a "1" line marker flag region.
1215 SourceLocation IncLoc = PLoc.getIncludeLoc();
1216 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001217 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001218 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1219 PP.DiscardUntilEndOfDirective();
1220 return true;
1221 }
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattner76e68962009-01-26 06:19:46 +00001223 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001224 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001225 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1226 return true;
1227 }
1228
1229 // We must have 3 if there are still flags.
1230 if (FlagVal != 3) {
1231 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001232 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001233 return true;
1234 }
Mike Stump11289f42009-09-09 15:08:12 +00001235
Reid Klecknereb00ee02017-05-22 21:42:58 +00001236 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001237
Chris Lattner76e68962009-01-26 06:19:46 +00001238 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001239 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001240 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001241 return true;
1242
1243 // We must have 4 if there is yet another flag.
1244 if (FlagVal != 4) {
1245 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001246 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001247 return true;
1248 }
Mike Stump11289f42009-09-09 15:08:12 +00001249
Reid Klecknereb00ee02017-05-22 21:42:58 +00001250 FileKind = SrcMgr::C_ExternCSystem;
Mike Stump11289f42009-09-09 15:08:12 +00001251
Chris Lattner76e68962009-01-26 06:19:46 +00001252 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001253 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001254
1255 // There are no more valid flags here.
1256 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001257 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001258 return true;
1259}
1260
1261/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1262/// one of the following forms:
1263///
1264/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001265/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001266/// # 42 "file" ('1' | '2')? '3' '4'?
1267///
1268void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1269 // Validate the number and convert it to an unsigned. GNU does not have a
1270 // line # limit other than it fit in 32-bits.
1271 unsigned LineNo;
1272 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001273 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001274 return;
Mike Stump11289f42009-09-09 15:08:12 +00001275
Chris Lattner76e68962009-01-26 06:19:46 +00001276 Token StrTok;
1277 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001278
Chris Lattner76e68962009-01-26 06:19:46 +00001279 bool IsFileEntry = false, IsFileExit = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001280 int FilenameID = -1;
Reid Klecknereb00ee02017-05-22 21:42:58 +00001281 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001282
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001283 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1284 // string followed by eod.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001285 if (StrTok.is(tok::eod)) {
1286 // Treat this like "#line NN", which doesn't change file characteristics.
1287 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1288 } else if (StrTok.isNot(tok::string_literal)) {
Chris Lattner76e68962009-01-26 06:19:46 +00001289 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001290 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001291 } else if (StrTok.hasUDSuffix()) {
1292 Diag(StrTok, diag::err_invalid_string_udl);
1293 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001294 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001295 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001296 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001297 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001298 if (Literal.hadError)
1299 return DiscardUntilEndOfDirective();
1300 if (Literal.Pascal) {
1301 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1302 return DiscardUntilEndOfDirective();
1303 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001304 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001305
Chris Lattner76e68962009-01-26 06:19:46 +00001306 // If a filename was present, read any flags that are present.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001307 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001308 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001309 }
Mike Stump11289f42009-09-09 15:08:12 +00001310
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001311 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001312 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1313 IsFileExit, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001314
Chris Lattner839150e2009-03-27 17:13:49 +00001315 // If the preprocessor has callbacks installed, notify them of the #line
1316 // change. This is used so that the line marker comes out in -E mode for
1317 // example.
1318 if (Callbacks) {
1319 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1320 if (IsFileEntry)
1321 Reason = PPCallbacks::EnterFile;
1322 else if (IsFileExit)
1323 Reason = PPCallbacks::ExitFile;
Mike Stump11289f42009-09-09 15:08:12 +00001324
Chris Lattnerc745cec2010-04-14 04:28:50 +00001325 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001326 }
Chris Lattner76e68962009-01-26 06:19:46 +00001327}
1328
Chris Lattner38d7fd22009-01-26 05:30:54 +00001329/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1330///
Mike Stump11289f42009-09-09 15:08:12 +00001331void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001332 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001333 // PTH doesn't emit #warning or #error directives.
1334 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001335 return CurPTHLexer->DiscardToEndOfLine();
1336
Chris Lattnerf64b3522008-03-09 01:54:53 +00001337 // Read the rest of the line raw. We do this because we don't want macros
1338 // to be expanded and we don't require that the tokens be valid preprocessing
1339 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1340 // collapse multiple consequtive white space between tokens, but this isn't
1341 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001342 SmallString<128> Message;
1343 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001344
1345 // Find the first non-whitespace character, so that we can make the
1346 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001347 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001348
Chris Lattner100c65e2009-01-26 05:29:08 +00001349 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001350 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001351 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001352 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001353}
1354
1355/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1356///
1357void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1358 // Yes, this directive is an extension.
1359 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattnerf64b3522008-03-09 01:54:53 +00001361 // Read the string argument.
1362 Token StrTok;
1363 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001364
Chris Lattnerf64b3522008-03-09 01:54:53 +00001365 // If the token kind isn't a string, it's a malformed directive.
1366 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001367 StrTok.isNot(tok::wide_string_literal)) {
1368 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001369 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001370 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001371 return;
1372 }
Mike Stump11289f42009-09-09 15:08:12 +00001373
Richard Smithd67aea22012-03-06 03:21:47 +00001374 if (StrTok.hasUDSuffix()) {
1375 Diag(StrTok, diag::err_invalid_string_udl);
1376 return DiscardUntilEndOfDirective();
1377 }
1378
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001379 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001380 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001381
Douglas Gregordc970f02010-03-16 22:30:13 +00001382 if (Callbacks) {
1383 bool Invalid = false;
1384 std::string Str = getSpelling(StrTok, &Invalid);
1385 if (!Invalid)
1386 Callbacks->Ident(Tok.getLocation(), Str);
1387 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001388}
1389
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001390/// \brief Handle a #public directive.
1391void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001392 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001393 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001394
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001395 // Error reading macro name? If so, diagnostic already issued.
1396 if (MacroNameTok.is(tok::eod))
1397 return;
1398
Douglas Gregor663b48f2012-01-03 19:48:16 +00001399 // Check to see if this is the last token on the #__public_macro line.
1400 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001401
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001402 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001403 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001404 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001405
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001406 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001407 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001408 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001409 return;
1410 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001411
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001412 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001413 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1414 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001415}
1416
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001417/// \brief Handle a #private directive.
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001418void Preprocessor::HandleMacroPrivateDirective() {
Douglas Gregorebf00492011-10-17 15:32:29 +00001419 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001420 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001421
Douglas Gregorebf00492011-10-17 15:32:29 +00001422 // Error reading macro name? If so, diagnostic already issued.
1423 if (MacroNameTok.is(tok::eod))
1424 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001425
Douglas Gregor663b48f2012-01-03 19:48:16 +00001426 // Check to see if this is the last token on the #__private_macro line.
1427 CheckEndOfDirective("__private_macro");
Taewook Oh755e4d22016-06-13 21:55:33 +00001428
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001429 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001430 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001431 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001432
Douglas Gregorebf00492011-10-17 15:32:29 +00001433 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001434 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001435 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001436 return;
1437 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001438
Douglas Gregorebf00492011-10-17 15:32:29 +00001439 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001440 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1441 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001442}
1443
Chris Lattnerf64b3522008-03-09 01:54:53 +00001444//===----------------------------------------------------------------------===//
1445// Preprocessor Include Directive Handling.
1446//===----------------------------------------------------------------------===//
1447
1448/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001449/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001450/// true if the input filename was in <>'s or false if it were in ""'s. The
1451/// caller is expected to provide a buffer that is large enough to hold the
1452/// spelling of the filename, but is also expected to handle the case when
1453/// this method decides to use a different buffer.
1454bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001455 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001456 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001457 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001458
Chris Lattnerf64b3522008-03-09 01:54:53 +00001459 // Make sure the filename is <x> or "x".
1460 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001461 if (Buffer[0] == '<') {
1462 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001463 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001464 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001465 return true;
1466 }
1467 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001468 } else if (Buffer[0] == '"') {
1469 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001470 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001471 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001472 return true;
1473 }
1474 isAngled = false;
1475 } else {
1476 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001477 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001478 return true;
1479 }
Mike Stump11289f42009-09-09 15:08:12 +00001480
Chris Lattnerf64b3522008-03-09 01:54:53 +00001481 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001482 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001483 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001484 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001485 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001486 }
Mike Stump11289f42009-09-09 15:08:12 +00001487
Chris Lattnerf64b3522008-03-09 01:54:53 +00001488 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001489 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001490 return isAngled;
1491}
1492
James Dennett4a4f72d2013-11-27 01:27:40 +00001493// \brief Handle cases where the \#include name is expanded from a macro
1494// as multiple tokens, which need to be glued together.
1495//
1496// This occurs for code like:
1497// \code
1498// \#define FOO <a/b.h>
1499// \#include FOO
1500// \endcode
1501// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1502//
1503// This code concatenates and consumes tokens up to the '>' token. It returns
1504// false if the > was found, otherwise it returns true if it finds and consumes
1505// the EOD marker.
1506bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001507 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001508 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001509
John Thompsonb5353522009-10-30 13:49:06 +00001510 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001511 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001512 End = CurTok.getLocation();
Taewook Oh755e4d22016-06-13 21:55:33 +00001513
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001514 // FIXME: Provide code completion for #includes.
1515 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001516 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001517 Lex(CurTok);
1518 continue;
1519 }
1520
Chris Lattnerf64b3522008-03-09 01:54:53 +00001521 // Append the spelling of this token to the buffer. If there was a space
1522 // before it, add it now.
1523 if (CurTok.hasLeadingSpace())
1524 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001525
Chris Lattnerf64b3522008-03-09 01:54:53 +00001526 // Get the spelling of the token, directly into FilenameBuffer if possible.
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001527 size_t PreAppendSize = FilenameBuffer.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001528 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001529
Chris Lattnerf64b3522008-03-09 01:54:53 +00001530 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001531 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001532
Chris Lattnerf64b3522008-03-09 01:54:53 +00001533 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1534 if (BufPtr != &FilenameBuffer[PreAppendSize])
1535 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001536
Chris Lattnerf64b3522008-03-09 01:54:53 +00001537 // Resize FilenameBuffer to the correct size.
1538 if (CurTok.getLength() != ActualLen)
1539 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001540
Chris Lattnerf64b3522008-03-09 01:54:53 +00001541 // If we found the '>' marker, return success.
1542 if (CurTok.is(tok::greater))
1543 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001544
John Thompsonb5353522009-10-30 13:49:06 +00001545 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001546 }
1547
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001548 // If we hit the eod marker, emit an error and return true so that the caller
1549 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001550 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001551 return true;
1552}
1553
Richard Smith34f30512013-11-23 04:06:09 +00001554/// \brief Push a token onto the token stream containing an annotation.
Richard Smithc51c38b2017-04-29 00:34:47 +00001555void Preprocessor::EnterAnnotationToken(SourceRange Range,
1556 tok::TokenKind Kind,
1557 void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001558 // FIXME: Produce this as the current token directly, rather than
1559 // allocating a new token for it.
David Blaikie2eabcc92016-02-09 18:52:09 +00001560 auto Tok = llvm::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001561 Tok[0].startToken();
1562 Tok[0].setKind(Kind);
Richard Smithc51c38b2017-04-29 00:34:47 +00001563 Tok[0].setLocation(Range.getBegin());
1564 Tok[0].setAnnotationEndLoc(Range.getEnd());
Richard Smith34f30512013-11-23 04:06:09 +00001565 Tok[0].setAnnotationValue(AnnotationVal);
Richard Smithc51c38b2017-04-29 00:34:47 +00001566 EnterTokenStream(std::move(Tok), 1, true);
Richard Smith34f30512013-11-23 04:06:09 +00001567}
1568
Richard Smith63b6fce2015-05-18 04:45:41 +00001569/// \brief Produce a diagnostic informing the user that a #include or similar
1570/// was implicitly treated as a module import.
1571static void diagnoseAutoModuleImport(
1572 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1573 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1574 SourceLocation PathEnd) {
1575 assert(PP.getLangOpts().ObjC2 && "no import syntax available");
1576
1577 SmallString<128> PathString;
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001578 for (size_t I = 0, N = Path.size(); I != N; ++I) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001579 if (I)
1580 PathString += '.';
1581 PathString += Path[I].first->getName();
1582 }
1583 int IncludeKind = 0;
Taewook Oh755e4d22016-06-13 21:55:33 +00001584
Richard Smith63b6fce2015-05-18 04:45:41 +00001585 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1586 case tok::pp_include:
1587 IncludeKind = 0;
1588 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001589
Richard Smith63b6fce2015-05-18 04:45:41 +00001590 case tok::pp_import:
1591 IncludeKind = 1;
Taewook Oh755e4d22016-06-13 21:55:33 +00001592 break;
1593
Richard Smith63b6fce2015-05-18 04:45:41 +00001594 case tok::pp_include_next:
1595 IncludeKind = 2;
1596 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001597
Richard Smith63b6fce2015-05-18 04:45:41 +00001598 case tok::pp___include_macros:
1599 IncludeKind = 3;
1600 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001601
Richard Smith63b6fce2015-05-18 04:45:41 +00001602 default:
1603 llvm_unreachable("unknown include directive kind");
1604 }
1605
1606 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1607 /*IsTokenRange=*/false);
1608 PP.Diag(HashLoc, diag::warn_auto_module_import)
1609 << IncludeKind << PathString
1610 << FixItHint::CreateReplacement(ReplaceRange,
1611 ("@import " + PathString + ";").str());
1612}
1613
Taewook Ohf42103c2016-06-13 20:40:21 +00001614// Given a vector of path components and a string containing the real
1615// path to the file, build a properly-cased replacement in the vector,
1616// and return true if the replacement should be suggested.
1617static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1618 StringRef RealPathName) {
1619 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1620 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1621 int Cnt = 0;
1622 bool SuggestReplacement = false;
1623 // Below is a best-effort to handle ".." in paths. It is admittedly
1624 // not 100% correct in the presence of symlinks.
1625 for (auto &Component : llvm::reverse(Components)) {
1626 if ("." == Component) {
1627 } else if (".." == Component) {
1628 ++Cnt;
1629 } else if (Cnt) {
1630 --Cnt;
1631 } else if (RealPathComponentIter != RealPathComponentEnd) {
1632 if (Component != *RealPathComponentIter) {
1633 // If these path components differ by more than just case, then we
1634 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1635 // noisy false positives.
1636 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1637 if (!SuggestReplacement)
1638 break;
1639 Component = *RealPathComponentIter;
1640 }
1641 ++RealPathComponentIter;
1642 }
1643 }
1644 return SuggestReplacement;
1645}
1646
Richard Smith27e5aa02017-06-05 18:57:56 +00001647bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
1648 const TargetInfo &TargetInfo,
1649 DiagnosticsEngine &Diags, Module *M) {
1650 Module::Requirement Requirement;
1651 Module::UnresolvedHeaderDirective MissingHeader;
1652 if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader))
1653 return false;
1654
1655 if (MissingHeader.FileNameLoc.isValid()) {
1656 Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1657 << MissingHeader.IsUmbrella << MissingHeader.FileName;
1658 } else {
1659 // FIXME: Track the location at which the requirement was specified, and
1660 // use it here.
1661 Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
1662 << M->getFullModuleName() << Requirement.second << Requirement.first;
1663 }
1664 return true;
1665}
1666
James Dennettf6333ac2012-06-22 05:46:07 +00001667/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1668/// the file to be included from the lexer, then include it! This is a common
1669/// routine with functionality shared between \#include, \#include_next and
1670/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001671/// specifies the file to start searching from.
Taewook Oh755e4d22016-06-13 21:55:33 +00001672void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001673 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001674 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001675 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001676 bool isImport) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001677 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001678 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001679
Chris Lattnerf64b3522008-03-09 01:54:53 +00001680 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001681 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001682 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001683 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001684 SourceLocation CharEnd; // the end of this directive, in characters
Taewook Oh755e4d22016-06-13 21:55:33 +00001685
Chris Lattnerf64b3522008-03-09 01:54:53 +00001686 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001687 case tok::eod:
1688 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001689 return;
Mike Stump11289f42009-09-09 15:08:12 +00001690
Chris Lattnerf64b3522008-03-09 01:54:53 +00001691 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001692 case tok::string_literal:
1693 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001694 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001695 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001696 break;
Mike Stump11289f42009-09-09 15:08:12 +00001697
Chris Lattnerf64b3522008-03-09 01:54:53 +00001698 case tok::less:
1699 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1700 // case, glue the tokens together into FilenameBuffer and interpret those.
1701 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001702 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001703 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001704 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001705 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001706 break;
1707 default:
1708 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1709 DiscardUntilEndOfDirective();
1710 return;
1711 }
Mike Stump11289f42009-09-09 15:08:12 +00001712
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001713 CharSourceRange FilenameRange
1714 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001715 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001716 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001717 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001718 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1719 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001720 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001721 DiscardUntilEndOfDirective();
1722 return;
1723 }
Mike Stump11289f42009-09-09 15:08:12 +00001724
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001725 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001726 // we allow macros that expand to nothing after the filename, because this
1727 // falls into the category of "#include pp-tokens new-line" specified in
1728 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001729 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001730
1731 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001732 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1733 Diag(FilenameTok, diag::err_pp_include_too_deep);
1734 return;
1735 }
Mike Stump11289f42009-09-09 15:08:12 +00001736
John McCall32f5fe12011-09-30 05:12:12 +00001737 // Complain about attempts to #include files in an audit pragma.
1738 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1739 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1740 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1741
1742 // Immediately leave the pragma.
1743 PragmaARCCFCodeAuditedLoc = SourceLocation();
1744 }
1745
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001746 // Complain about attempts to #include files in an assume-nonnull pragma.
1747 if (PragmaAssumeNonNullLoc.isValid()) {
1748 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1749 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1750
1751 // Immediately leave the pragma.
1752 PragmaAssumeNonNullLoc = SourceLocation();
1753 }
1754
Aaron Ballman611306e2012-03-02 22:51:54 +00001755 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001756 // Map the filename with the brackets still attached. If the name doesn't
1757 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001758 // spelling for.
1759 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1760 if (!NewName.empty())
1761 Filename = NewName;
1762 }
1763
Chris Lattnerf64b3522008-03-09 01:54:53 +00001764 // Search include directories.
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001765 bool IsMapped = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001766 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001767 SmallString<1024> SearchPath;
1768 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001769 // We get the raw path only if we have 'Callbacks' to which we later pass
1770 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001771 ModuleMap::KnownHeader SuggestedModule;
1772 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001773 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001774 if (LangOpts.MSVCCompat) {
1775 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001776#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001777 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001778#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001779 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001780 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001781 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001782 isAngled, LookupFrom, LookupFromFile, CurDir,
1783 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001784 &SuggestedModule, &IsMapped);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001785
Richard Smithdbbc5232015-05-14 02:25:44 +00001786 if (!File) {
1787 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001788 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001789 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001790 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1791 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1792 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001793 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001794 HeaderInfo.AddSearchPath(DL, isAngled);
Taewook Oh755e4d22016-06-13 21:55:33 +00001795
Douglas Gregor11729f02011-11-30 18:12:06 +00001796 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001797 File = LookupFile(
1798 FilenameLoc,
1799 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1800 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001801 &SuggestedModule, &IsMapped, /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001802 }
1803 }
1804 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001805
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001806 if (!SuppressIncludeNotFoundError) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001807 // If the file could not be located and it was included via angle
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001808 // brackets, we can attempt a lookup as though it were a quoted path to
1809 // provide the user with a possible fixit.
1810 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001811 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001812 FilenameLoc,
1813 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1814 LookupFrom, LookupFromFile, CurDir,
1815 Callbacks ? &SearchPath : nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001816 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001817 if (File) {
1818 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001819 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1820 Filename <<
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001821 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1822 }
1823 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001824
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001825 // If the file is still not found, just go with the vanilla diagnostic
1826 if (!File)
Erik Verbruggen45449542016-10-25 10:13:10 +00001827 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename
1828 << FilenameRange;
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001829 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001830 }
1831
Richard Smith63b6fce2015-05-18 04:45:41 +00001832 // Should we enter the source file? Set to false if either the source file is
1833 // known to have no effect beyond its effect on module visibility -- that is,
1834 // if it's got an include guard that is already defined or is a modular header
1835 // we've imported or already built.
1836 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001837
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001838 if (PPOpts->SingleFileParseMode)
1839 ShouldEnter = false;
1840
Richard Smith63b6fce2015-05-18 04:45:41 +00001841 // Determine whether we should try to import the module for this #include, if
1842 // there is one. Don't do so if precompiled module support is disabled or we
1843 // are processing this module textually (because we're building the module).
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001844 if (ShouldEnter && File && SuggestedModule && getLangOpts().Modules &&
Richard Smith63b6fce2015-05-18 04:45:41 +00001845 SuggestedModule.getModule()->getTopLevelModuleName() !=
Richard Smith7e82e012016-02-19 22:25:36 +00001846 getLangOpts().CurrentModule) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001847 // If this include corresponds to a module but that module is
1848 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001849 // FIXME: Remove this; loadModule does the same check (but produces
1850 // slightly worse diagnostics).
Richard Smith27e5aa02017-06-05 18:57:56 +00001851 if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
1852 SuggestedModule.getModule())) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001853 Diag(FilenameTok.getLocation(),
1854 diag::note_implicit_top_level_module_import_here)
Richard Smith27e5aa02017-06-05 18:57:56 +00001855 << SuggestedModule.getModule()->getTopLevelModuleName();
Sean Silva8b7c0392015-08-17 16:39:30 +00001856 return;
1857 }
1858
Douglas Gregor71944202011-11-30 00:36:36 +00001859 // Compute the module access path corresponding to this module.
1860 // FIXME: Should we have a second loadModule() overload to avoid this
1861 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001862 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001863 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001864 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1865 FilenameTok.getLocation()));
1866 std::reverse(Path.begin(), Path.end());
1867
Douglas Gregor41e115a2011-11-30 18:02:36 +00001868 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001869 // We only do this in Objective-C, where we have a module-import syntax.
1870 if (getLangOpts().ObjC2)
1871 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001872
Richard Smith10434f32015-05-02 02:08:26 +00001873 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001874 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001875 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1876 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001877 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1878 IncludeTok.getLocation(), Path, Module::Hidden,
1879 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001880 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001881 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001882
Richard Smith63b6fce2015-05-18 04:45:41 +00001883 if (Imported)
1884 ShouldEnter = false;
1885 else if (Imported.isMissingExpected()) {
1886 // We failed to find a submodule that we assumed would exist (because it
1887 // was in the directory of an umbrella header, for instance), but no
Richard Smitha114c462016-12-06 00:40:17 +00001888 // actual module containing it exists (because the umbrella header is
Richard Smith63b6fce2015-05-18 04:45:41 +00001889 // incomplete). Treat this as a textual inclusion.
1890 SuggestedModule = ModuleMap::KnownHeader();
Richard Smitha114c462016-12-06 00:40:17 +00001891 } else if (Imported.isConfigMismatch()) {
1892 // On a configuration mismatch, enter the header textually. We still know
1893 // that it's part of the corresponding module.
Richard Smith63b6fce2015-05-18 04:45:41 +00001894 } else {
1895 // We hit an error processing the import. Bail out.
1896 if (hadModuleLoaderFatalFailure()) {
1897 // With a fatal failure in the module loader, we abort parsing.
1898 Token &Result = IncludeTok;
1899 if (CurLexer) {
1900 Result.startToken();
1901 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1902 CurLexer->cutOffLexing();
1903 } else {
1904 assert(CurPTHLexer && "#include but no current lexer set!");
1905 CurPTHLexer->getEOF(Result);
1906 }
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001907 }
1908 return;
1909 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001910 }
1911
Richard Smithc5247e62017-05-30 02:03:19 +00001912 // The #included file will be considered to be a system header if either it is
1913 // in a system include directory, or if the #includer is a system include
1914 // header.
1915 SrcMgr::CharacteristicKind FileCharacter =
1916 SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
1917 if (File)
1918 FileCharacter = std::max(HeaderInfo.getFileDirFlavor(File), FileCharacter);
1919
1920 // Ask HeaderInfo if we should enter this #include file. If not, #including
1921 // this file will have no effect.
1922 bool SkipHeader = false;
1923 if (ShouldEnter && File &&
1924 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
1925 getLangOpts().Modules,
1926 SuggestedModule.getModule())) {
1927 ShouldEnter = false;
1928 SkipHeader = true;
1929 }
1930
Richard Smith63b6fce2015-05-18 04:45:41 +00001931 if (Callbacks) {
1932 // Notify the callback object that we've seen an inclusion directive.
1933 Callbacks->InclusionDirective(
1934 HashLoc, IncludeTok,
1935 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1936 FilenameRange, File, SearchPath, RelativePath,
1937 ShouldEnter ? nullptr : SuggestedModule.getModule());
Richard Smithc5247e62017-05-30 02:03:19 +00001938 if (SkipHeader && !SuggestedModule.getModule())
1939 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Douglas Gregor97eec242011-09-15 22:00:41 +00001940 }
Richard Smith63b6fce2015-05-18 04:45:41 +00001941
1942 if (!File)
1943 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001944
Richard Smith54ef4c32015-05-19 19:58:11 +00001945 // FIXME: If we have a suggested module, and we've already visited this file,
1946 // don't bother entering it again. We know it has no further effect.
1947
Taewook Ohf42103c2016-06-13 20:40:21 +00001948 // Issue a diagnostic if the name of the file on disk has a different case
1949 // than the one we're about to open.
1950 const bool CheckIncludePathPortability =
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001951 !IsMapped && File && !File->tryGetRealPathName().empty();
Taewook Ohf42103c2016-06-13 20:40:21 +00001952
1953 if (CheckIncludePathPortability) {
1954 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
1955 StringRef RealPathName = File->tryGetRealPathName();
1956 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
1957 llvm::sys::path::end(Name));
1958
1959 if (trySimplifyPath(Components, RealPathName)) {
1960 SmallString<128> Path;
1961 Path.reserve(Name.size()+2);
1962 Path.push_back(isAngled ? '<' : '"');
Taewook Ohcc89bac2017-02-21 22:30:55 +00001963 bool isLeadingSeparator = llvm::sys::path::is_absolute(Name);
Taewook Ohf42103c2016-06-13 20:40:21 +00001964 for (auto Component : Components) {
Taewook Ohcc89bac2017-02-21 22:30:55 +00001965 if (isLeadingSeparator)
1966 isLeadingSeparator = false;
1967 else
1968 Path.append(Component);
Taewook Ohf42103c2016-06-13 20:40:21 +00001969 // Append the separator the user used, or the close quote
1970 Path.push_back(
1971 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
1972 (isAngled ? '>' : '"'));
1973 }
Taewook Ohf42103c2016-06-13 20:40:21 +00001974 // For user files and known standard headers, by default we issue a diagnostic.
1975 // For other system headers, we don't. They can be controlled separately.
1976 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
1977 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
1978 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Reid Kleckner273895b2017-02-14 18:38:40 +00001979 Diag(FilenameTok, DiagId) << Path <<
1980 FixItHint::CreateReplacement(Range, Path);
Taewook Ohf42103c2016-06-13 20:40:21 +00001981 }
1982 }
1983
Richard Smith63b6fce2015-05-18 04:45:41 +00001984 // If we don't need to enter the file, stop now.
1985 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001986 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00001987 if (auto *M = SuggestedModule.getModule()) {
Manman Renffd3e9d2017-01-09 19:20:18 +00001988 // When building a pch, -fmodule-name tells the compiler to textually
1989 // include headers in the specified module. But it is possible that
1990 // ShouldEnter is false because we are skipping the header. In that
1991 // case, We are not importing the specified module.
1992 if (SkipHeader && getLangOpts().CompilingPCH &&
1993 M->getTopLevelModuleName() == getLangOpts().CurrentModule)
1994 return;
1995
Richard Smitha0aafa32015-05-18 03:52:30 +00001996 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00001997
1998 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
1999 tok::pp___include_macros)
Richard Smithc51c38b2017-04-29 00:34:47 +00002000 EnterAnnotationToken(SourceRange(HashLoc, End),
2001 tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00002002 }
Chris Lattner72286d62010-04-19 20:44:31 +00002003 return;
2004 }
2005
Chris Lattnerf64b3522008-03-09 01:54:53 +00002006 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002007 SourceLocation IncludePos = End;
2008 // If the filename string was the result of macro expansions, set the include
2009 // position on the file where it will be included and after the expansions.
2010 if (IncludePos.isMacroID())
2011 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
2012 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002013 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002014
Richard Smith34f30512013-11-23 04:06:09 +00002015 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002016 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
2017 return;
Richard Smith34f30512013-11-23 04:06:09 +00002018
Richard Smitha0aafa32015-05-18 03:52:30 +00002019 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002020 if (auto *M = SuggestedModule.getModule()) {
Manman Renffd3e9d2017-01-09 19:20:18 +00002021 // When building a pch, -fmodule-name tells the compiler to textually
2022 // include headers in the specified module. We are not building the
2023 // specified module.
2024 if (getLangOpts().CompilingPCH &&
2025 M->getTopLevelModuleName() == getLangOpts().CurrentModule)
2026 return;
2027
Richard Smithd1386302017-05-04 00:29:54 +00002028 assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2029 CurLexerSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002030
Richard Smitha0aafa32015-05-18 03:52:30 +00002031 // Let the macro handling code know that any future macros are within
2032 // the new submodule.
Richard Smithd1386302017-05-04 00:29:54 +00002033 EnterSubmodule(M, HashLoc, /*ForPragma*/false);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002034
Richard Smitha0aafa32015-05-18 03:52:30 +00002035 // Let the parser know that any future declarations are within the new
2036 // submodule.
2037 // FIXME: There's no point doing this if we're handling a #__include_macros
2038 // directive.
Richard Smithc51c38b2017-04-29 00:34:47 +00002039 EnterAnnotationToken(SourceRange(HashLoc, End), tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00002040 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002041}
2042
James Dennettf6333ac2012-06-22 05:46:07 +00002043/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002044///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002045void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2046 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002047 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002048
Chris Lattnerf64b3522008-03-09 01:54:53 +00002049 // #include_next is like #include, except that we start searching after
2050 // the current found directory. If we can't do this, issue a
2051 // diagnostic.
2052 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002053 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00002054 if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2055 // If the main file is a header, then it's either for PCH/AST generation,
2056 // or libclang opened it. Either way, handle it as a normal include below
2057 // and do not complain about include_next.
2058 } else if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002059 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002060 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smithd1386302017-05-04 00:29:54 +00002061 } else if (CurLexerSubmodule) {
Richard Smith25d50752014-10-20 00:15:49 +00002062 // Start looking up in the directory *after* the one in which the current
2063 // file would be found, if any.
2064 assert(CurPPLexer && "#include_next directive in macro?");
2065 LookupFromFile = CurPPLexer->getFileEntry();
2066 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002067 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002068 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2069 } else {
2070 // Start looking up in the next directory.
2071 ++Lookup;
2072 }
Mike Stump11289f42009-09-09 15:08:12 +00002073
Richard Smith25d50752014-10-20 00:15:49 +00002074 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2075 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002076}
2077
James Dennettf6333ac2012-06-22 05:46:07 +00002078/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002079void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2080 // The Microsoft #import directive takes a type library and generates header
2081 // files from it, and includes those. This is beyond the scope of what clang
2082 // does, so we ignore it and error out. However, #import can optionally have
2083 // trailing attributes that span multiple lines. We're going to eat those
2084 // so we can continue processing from there.
2085 Diag(Tok, diag::err_pp_import_directive_ms );
2086
Taewook Oh755e4d22016-06-13 21:55:33 +00002087 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002088 // directive can be split over multiple lines using the backslash character.
2089 DiscardUntilEndOfDirective();
2090}
2091
James Dennettf6333ac2012-06-22 05:46:07 +00002092/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002093///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002094void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2095 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00002096 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002097 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002098 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002099 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002100 }
Richard Smith25d50752014-10-20 00:15:49 +00002101 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002102}
2103
Chris Lattner58a1eb02009-04-08 18:46:40 +00002104/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2105/// pseudo directive in the predefines buffer. This handles it by sucking all
2106/// tokens through the preprocessor and discarding them (only keeping the side
2107/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002108void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2109 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002110 // This directive should only occur in the predefines buffer. If not, emit an
2111 // error and reject it.
2112 SourceLocation Loc = IncludeMacrosTok.getLocation();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002113 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002114 Diag(IncludeMacrosTok.getLocation(),
2115 diag::pp_include_macros_out_of_predefines);
2116 DiscardUntilEndOfDirective();
2117 return;
2118 }
Mike Stump11289f42009-09-09 15:08:12 +00002119
Chris Lattnere01d82b2009-04-08 20:53:24 +00002120 // Treat this as a normal #include for checking purposes. If this is
2121 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002122 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002123
Chris Lattnere01d82b2009-04-08 20:53:24 +00002124 Token TmpTok;
2125 do {
2126 Lex(TmpTok);
2127 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2128 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002129}
2130
Chris Lattnerf64b3522008-03-09 01:54:53 +00002131//===----------------------------------------------------------------------===//
2132// Preprocessor Macro Directive Handling.
2133//===----------------------------------------------------------------------===//
2134
Faisal Valiac506d72017-07-17 17:18:43 +00002135/// ReadMacroParameterList - The ( starting an argument list of a macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00002136/// definition has just been read. Lex the rest of the arguments and the
2137/// closing ), updating MI with what we learn. Return true if an error occurs
2138/// parsing the arg list.
Faisal Valiac506d72017-07-17 17:18:43 +00002139bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002140 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00002141
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002142 while (true) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002143 LexUnexpandedToken(Tok);
2144 switch (Tok.getKind()) {
2145 case tok::r_paren:
2146 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00002147 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002148 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002149 // Otherwise we have #define FOO(A,)
2150 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2151 return true;
2152 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002153 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002154 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002155 diag::warn_cxx98_compat_variadic_macro :
2156 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002157
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002158 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2159 if (LangOpts.OpenCL) {
2160 Diag(Tok, diag::err_pp_opencl_variadic_macros);
2161 return true;
2162 }
2163
Chris Lattnerf64b3522008-03-09 01:54:53 +00002164 // Lex the token after the identifier.
2165 LexUnexpandedToken(Tok);
2166 if (Tok.isNot(tok::r_paren)) {
2167 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2168 return true;
2169 }
2170 // Add the __VA_ARGS__ identifier as an argument.
2171 Arguments.push_back(Ident__VA_ARGS__);
2172 MI->setIsC99Varargs();
Faisal Valiac506d72017-07-17 17:18:43 +00002173 MI->setParameterList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002174 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002175 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002176 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2177 return true;
2178 default:
2179 // Handle keywords and identifiers here to accept things like
2180 // #define Foo(for) for.
2181 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002182 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002183 // #define X(1
2184 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2185 return true;
2186 }
2187
2188 // If this is already used as an argument, it is used multiple times (e.g.
2189 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00002190 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00002191 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002192 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002193 return true;
2194 }
Mike Stump11289f42009-09-09 15:08:12 +00002195
Chris Lattnerf64b3522008-03-09 01:54:53 +00002196 // Add the argument to the macro info.
2197 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002198
Chris Lattnerf64b3522008-03-09 01:54:53 +00002199 // Lex the token after the identifier.
2200 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002201
Chris Lattnerf64b3522008-03-09 01:54:53 +00002202 switch (Tok.getKind()) {
2203 default: // #define X(A B
2204 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2205 return true;
2206 case tok::r_paren: // #define X(A)
Faisal Valiac506d72017-07-17 17:18:43 +00002207 MI->setParameterList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002208 return false;
2209 case tok::comma: // #define X(A,
2210 break;
2211 case tok::ellipsis: // #define X(A... -> GCC extension
2212 // Diagnose extension.
2213 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002214
Chris Lattnerf64b3522008-03-09 01:54:53 +00002215 // Lex the token after the identifier.
2216 LexUnexpandedToken(Tok);
2217 if (Tok.isNot(tok::r_paren)) {
2218 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2219 return true;
2220 }
Mike Stump11289f42009-09-09 15:08:12 +00002221
Chris Lattnerf64b3522008-03-09 01:54:53 +00002222 MI->setIsGNUVarargs();
Faisal Valiac506d72017-07-17 17:18:43 +00002223 MI->setParameterList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002224 return false;
2225 }
2226 }
2227 }
2228}
2229
Serge Pavlov07c0f042014-12-18 11:14:21 +00002230static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2231 const LangOptions &LOptions) {
2232 if (MI->getNumTokens() == 1) {
2233 const Token &Value = MI->getReplacementToken(0);
2234
2235 // Macro that is identity, like '#define inline inline' is a valid pattern.
2236 if (MacroName.getKind() == Value.getKind())
2237 return true;
2238
2239 // Macro that maps a keyword to the same keyword decorated with leading/
2240 // trailing underscores is a valid pattern:
2241 // #define inline __inline
2242 // #define inline __inline__
2243 // #define inline _inline (in MS compatibility mode)
2244 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2245 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2246 if (!II->isKeyword(LOptions))
2247 return false;
2248 StringRef ValueText = II->getName();
2249 StringRef TrimmedValue = ValueText;
2250 if (!ValueText.startswith("__")) {
2251 if (ValueText.startswith("_"))
2252 TrimmedValue = TrimmedValue.drop_front(1);
2253 else
2254 return false;
2255 } else {
2256 TrimmedValue = TrimmedValue.drop_front(2);
2257 if (TrimmedValue.endswith("__"))
2258 TrimmedValue = TrimmedValue.drop_back(2);
2259 }
2260 return TrimmedValue.equals(MacroText);
2261 } else {
2262 return false;
2263 }
2264 }
2265
2266 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002267 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2268 tok::kw_const) &&
2269 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002270}
2271
Faisal Valiac506d72017-07-17 17:18:43 +00002272// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2273// entire line) of the macro's tokens and adds them to MacroInfo, and while
2274// doing so performs certain validity checks including (but not limited to):
2275// - # (stringization) is followed by a macro parameter
2276//
2277// Returns a nullptr if an invalid sequence of tokens is encountered or returns
2278// a pointer to a MacroInfo object.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002279
Faisal Valiac506d72017-07-17 17:18:43 +00002280MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2281 const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002282
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002283 Token LastTok = MacroNameTok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002284 // Create the new macro.
Faisal Valiac506d72017-07-17 17:18:43 +00002285 MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002286
Chris Lattnerf64b3522008-03-09 01:54:53 +00002287 Token Tok;
2288 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002289
Faisal Vali6bf67912017-07-25 03:15:36 +00002290 // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2291 // within their appropriate context.
2292 VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2293
Chris Lattnerf64b3522008-03-09 01:54:53 +00002294 // If this is a function-like macro definition, parse the argument list,
2295 // marking each of the identifiers as being used as macro arguments. Also,
2296 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002297 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002298 if (ImmediatelyAfterHeaderGuard) {
2299 // Save this macro information since it may part of a header guard.
2300 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2301 MacroNameTok.getLocation());
2302 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002303 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002304 } else if (Tok.hasLeadingSpace()) {
2305 // This is a normal token with leading space. Clear the leading space
2306 // marker on the first token to get proper expansion.
2307 Tok.clearFlag(Token::LeadingSpace);
2308 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002309 // This is a function-like macro definition. Read the argument list.
2310 MI->setIsFunctionLike();
Faisal Valiac506d72017-07-17 17:18:43 +00002311 if (ReadMacroParameterList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002312 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002313 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002314 DiscardUntilEndOfDirective();
Faisal Valiac506d72017-07-17 17:18:43 +00002315 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002316 }
2317
Faisal Vali6bf67912017-07-25 03:15:36 +00002318 // If this is a definition of an ISO C/C++ variadic function-like macro (not
2319 // using the GNU named varargs extension) inform our variadic scope guard
2320 // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2321 // allowed only within the definition of a variadic macro.
Mike Stump11289f42009-09-09 15:08:12 +00002322
Faisal Vali6bf67912017-07-25 03:15:36 +00002323 if (MI->isC99Varargs()) {
2324 VariadicMacroScopeGuard.enterScope();
2325 }
Mike Stump11289f42009-09-09 15:08:12 +00002326
Chris Lattnerf64b3522008-03-09 01:54:53 +00002327 // Read the first token after the arg list for down below.
2328 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002329 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002330 // C99 requires whitespace between the macro definition and the body. Emit
2331 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002332 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002333 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002334 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2335 // first character of a replacement list is not a character required by
2336 // subclause 5.2.1, then there shall be white-space separation between the
2337 // identifier and the replacement list.". 5.2.1 lists this set:
2338 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2339 // is irrelevant here.
2340 bool isInvalid = false;
2341 if (Tok.is(tok::at)) // @ is not in the list above.
2342 isInvalid = true;
2343 else if (Tok.is(tok::unknown)) {
2344 // If we have an unknown token, it is something strange like "`". Since
2345 // all of valid characters would have lexed into a single character
2346 // token of some sort, we know this is not a valid case.
2347 isInvalid = true;
2348 }
2349 if (isInvalid)
2350 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2351 else
2352 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002353 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002354
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002355 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002356 LastTok = Tok;
2357
Chris Lattnerf64b3522008-03-09 01:54:53 +00002358 // Read the rest of the macro body.
2359 if (MI->isObjectLike()) {
2360 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002361 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002362 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002363 MI->AddTokenToBody(Tok);
2364 // Get the next token of the macro.
2365 LexUnexpandedToken(Tok);
2366 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002367 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002368 // Otherwise, read the body of a function-like macro. While we are at it,
2369 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2370 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002371 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002372 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002373
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002374 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002375 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002376
Chris Lattnerf64b3522008-03-09 01:54:53 +00002377 // Get the next token of the macro.
2378 LexUnexpandedToken(Tok);
2379 continue;
2380 }
Mike Stump11289f42009-09-09 15:08:12 +00002381
Richard Smith701a3522013-07-09 01:00:29 +00002382 // If we're in -traditional mode, then we should ignore stringification
2383 // and token pasting. Mark the tokens as unknown so as not to confuse
2384 // things.
2385 if (getLangOpts().TraditionalCPP) {
2386 Tok.setKind(tok::unknown);
2387 MI->AddTokenToBody(Tok);
2388
2389 // Get the next token of the macro.
2390 LexUnexpandedToken(Tok);
2391 continue;
2392 }
2393
Eli Friedman14d3c792012-11-14 02:18:46 +00002394 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002395 // If we see token pasting, check if it looks like the gcc comma
2396 // pasting extension. We'll use this information to suppress
2397 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002398
Eli Friedman14d3c792012-11-14 02:18:46 +00002399 // Get the next token of the macro.
2400 LexUnexpandedToken(Tok);
2401
2402 if (Tok.is(tok::eod)) {
2403 MI->AddTokenToBody(LastTok);
2404 break;
2405 }
2406
2407 unsigned NumTokens = MI->getNumTokens();
2408 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2409 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2410 MI->setHasCommaPasting();
2411
David Majnemer76faf1f2013-11-05 09:30:17 +00002412 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002413 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002414 continue;
2415 }
2416
Chris Lattnerf64b3522008-03-09 01:54:53 +00002417 // Get the next token of the macro.
2418 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002419
Chris Lattner83bd8282009-05-25 17:16:10 +00002420 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002421 if (Tok.getIdentifierInfo() == nullptr ||
Faisal Valiac506d72017-07-17 17:18:43 +00002422 MI->getParameterNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002423
2424 // If this is assembler-with-cpp mode, we accept random gibberish after
2425 // the '#' because '#' is often a comment character. However, change
2426 // the kind of the token to tok::unknown so that the preprocessor isn't
2427 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002428 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002429 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002430 MI->AddTokenToBody(LastTok);
2431 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002432 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002433 Diag(Tok, diag::err_pp_stringize_not_parameter)
2434 << LastTok.is(tok::hashat);
Faisal Valiac506d72017-07-17 17:18:43 +00002435 return nullptr;
Chris Lattner83bd8282009-05-25 17:16:10 +00002436 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002437 }
Mike Stump11289f42009-09-09 15:08:12 +00002438
Chris Lattner83bd8282009-05-25 17:16:10 +00002439 // Things look ok, add the '#' and param name tokens to the macro.
2440 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002441 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002442 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002443
Chris Lattnerf64b3522008-03-09 01:54:53 +00002444 // Get the next token of the macro.
2445 LexUnexpandedToken(Tok);
2446 }
2447 }
Faisal Valiac506d72017-07-17 17:18:43 +00002448 MI->setDefinitionEndLoc(LastTok.getLocation());
Faisal Valiac506d72017-07-17 17:18:43 +00002449 return MI;
2450}
2451/// HandleDefineDirective - Implements \#define. This consumes the entire macro
2452/// line then lets the caller lex the next real token.
2453void Preprocessor::HandleDefineDirective(
2454 Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2455 ++NumDefined;
2456
2457 Token MacroNameTok;
2458 bool MacroShadowsKeyword;
2459 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2460
2461 // Error reading macro name? If so, diagnostic already issued.
2462 if (MacroNameTok.is(tok::eod))
2463 return;
2464
2465 // If we are supposed to keep comments in #defines, reenable comment saving
2466 // mode.
2467 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2468
2469 MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2470 MacroNameTok, ImmediatelyAfterHeaderGuard);
2471
2472 if (!MI) return;
Mike Stump11289f42009-09-09 15:08:12 +00002473
Serge Pavlov07c0f042014-12-18 11:14:21 +00002474 if (MacroShadowsKeyword &&
2475 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2476 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
Faisal Valiac506d72017-07-17 17:18:43 +00002477 }
Chris Lattner57540c52011-04-15 05:22:18 +00002478 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002479 // replacement list.
2480 unsigned NumTokens = MI->getNumTokens();
2481 if (NumTokens != 0) {
2482 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2483 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002484 return;
2485 }
2486 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2487 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002488 return;
2489 }
2490 }
Mike Stump11289f42009-09-09 15:08:12 +00002491
Faisal Valiac506d72017-07-17 17:18:43 +00002492
Mike Stump11289f42009-09-09 15:08:12 +00002493
Chris Lattnerf64b3522008-03-09 01:54:53 +00002494 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002495 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002496 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002497 // In Objective-C, ignore attempts to directly redefine the builtin
2498 // definitions of the ownership qualifiers. It's still possible to
2499 // #undef them.
2500 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2501 return II->isStr("__strong") ||
2502 II->isStr("__weak") ||
2503 II->isStr("__unsafe_unretained") ||
2504 II->isStr("__autoreleasing");
2505 };
2506 if (getLangOpts().ObjC1 &&
2507 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2508 == getPredefinesFileID() &&
2509 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2510 // Warn if it changes the tokens.
2511 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2512 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2513 !MI->isIdenticalTo(*OtherMI, *this,
2514 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2515 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2516 }
2517 assert(!OtherMI->isWarnIfUnused());
2518 return;
2519 }
2520
Chris Lattner5244f342009-01-16 19:50:11 +00002521 // It is very common for system headers to have tons of macro redefinitions
2522 // and for warnings to be disabled in system headers. If this is the case,
2523 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002524 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002525 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002526 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002527 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002528
Taewook Oh755e4d22016-06-13 21:55:33 +00002529 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002530 // C++ [cpp.predefined]p4, but allow it as an extension.
2531 if (OtherMI->isBuiltinMacro())
2532 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002533 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002534 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002535 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002536 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002537 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2538 << MacroNameTok.getIdentifierInfo();
2539 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2540 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002541 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002542 if (OtherMI->isWarnIfUnused())
2543 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002544 }
Mike Stump11289f42009-09-09 15:08:12 +00002545
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002546 DefMacroDirective *MD =
2547 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002548
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002549 assert(!MI->isUsed());
2550 // If we need warning for not using the macro, add its location in the
2551 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002552 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002553 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002554 MI->setIsWarnIfUnused(true);
2555 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2556 }
2557
Chris Lattner928e9092009-04-12 01:39:54 +00002558 // If the callbacks want to know, tell them about the macro definition.
2559 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002560 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002561}
2562
James Dennettf6333ac2012-06-22 05:46:07 +00002563/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002564///
Erik Verbruggen4bddef92016-10-26 08:52:41 +00002565void Preprocessor::HandleUndefDirective() {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002566 ++NumUndefined;
2567
2568 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002569 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002570
Chris Lattnerf64b3522008-03-09 01:54:53 +00002571 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002572 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002573 return;
Mike Stump11289f42009-09-09 15:08:12 +00002574
Chris Lattnerf64b3522008-03-09 01:54:53 +00002575 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002576 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002577
Richard Smith20e883e2015-04-29 23:20:19 +00002578 // Okay, we have a valid identifier to undef.
2579 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002580 auto MD = getMacroDefinition(II);
Vedant Kumar349a6242017-04-26 21:05:44 +00002581 UndefMacroDirective *Undef = nullptr;
2582
2583 // If the macro is not defined, this is a noop undef.
2584 if (const MacroInfo *MI = MD.getMacroInfo()) {
2585 if (!MI->isUsed() && MI->isWarnIfUnused())
2586 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2587
2588 if (MI->isWarnIfUnused())
2589 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2590
2591 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
2592 }
Mike Stump11289f42009-09-09 15:08:12 +00002593
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002594 // If the callbacks want to know, tell them about the macro #undef.
2595 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002596 if (Callbacks)
Vedant Kumar349a6242017-04-26 21:05:44 +00002597 Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002598
Vedant Kumar349a6242017-04-26 21:05:44 +00002599 if (Undef)
2600 appendMacroDirective(II, Undef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002601}
2602
Chris Lattnerf64b3522008-03-09 01:54:53 +00002603//===----------------------------------------------------------------------===//
2604// Preprocessor Conditional Directive Handling.
2605//===----------------------------------------------------------------------===//
2606
James Dennettf6333ac2012-06-22 05:46:07 +00002607/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2608/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2609/// true if any tokens have been returned or pp-directives activated before this
2610/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002611///
Vedant Kumar3919a502017-09-11 20:47:42 +00002612void Preprocessor::HandleIfdefDirective(Token &Result,
2613 const Token &HashToken,
2614 bool isIfndef,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002615 bool ReadAnyTokensBeforeDirective) {
2616 ++NumIf;
2617 Token DirectiveTok = Result;
2618
2619 Token MacroNameTok;
2620 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002621
Chris Lattnerf64b3522008-03-09 01:54:53 +00002622 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002623 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002624 // Skip code until we get to #endif. This helps with recovery by not
2625 // emitting an error when the #endif is reached.
Vedant Kumar3919a502017-09-11 20:47:42 +00002626 SkipExcludedConditionalBlock(HashToken, DirectiveTok.getLocation(),
2627 /*Foundnonskip*/ false, /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002628 return;
2629 }
Mike Stump11289f42009-09-09 15:08:12 +00002630
Chris Lattnerf64b3522008-03-09 01:54:53 +00002631 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002632 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002633
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002634 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002635 auto MD = getMacroDefinition(MII);
2636 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002637
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002638 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002639 // If the start of a top-level #ifdef and if the macro is not defined,
2640 // inform MIOpt that this might be the start of a proper include guard.
2641 // Otherwise it is some other form of unknown conditional which we can't
2642 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002643 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002644 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002645 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002646 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002647 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002648 }
2649
Chris Lattnerf64b3522008-03-09 01:54:53 +00002650 // If there is a macro, process it.
2651 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002652 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002653
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002654 if (Callbacks) {
2655 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002656 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002657 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002658 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002659 }
2660
Chris Lattnerf64b3522008-03-09 01:54:53 +00002661 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002662 if (PPOpts->SingleFileParseMode && !MI) {
2663 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2664 // the directive blocks.
2665 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002666 /*wasskip*/false, /*foundnonskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002667 /*foundelse*/false);
2668 } else if (!MI == isIfndef) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002669 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002670 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2671 /*wasskip*/false, /*foundnonskip*/true,
2672 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002673 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002674 // No, skip the contents of this block.
Vedant Kumar3919a502017-09-11 20:47:42 +00002675 SkipExcludedConditionalBlock(HashToken, DirectiveTok.getLocation(),
2676 /*Foundnonskip*/ false,
2677 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002678 }
2679}
2680
James Dennettf6333ac2012-06-22 05:46:07 +00002681/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002682///
2683void Preprocessor::HandleIfDirective(Token &IfToken,
Vedant Kumar3919a502017-09-11 20:47:42 +00002684 const Token &HashToken,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002685 bool ReadAnyTokensBeforeDirective) {
2686 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002687
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002688 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002689 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002690 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002691 const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
2692 const bool ConditionalTrue = DER.Conditional;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002693 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002694
2695 // If this condition is equivalent to #ifndef X, and if this is the first
2696 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002697 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002698 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002699 // FIXME: Pass in the location of the macro name, not the 'if' token.
2700 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002701 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002702 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002703 }
2704
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002705 if (Callbacks)
2706 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002707 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002708 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002709
Chris Lattnerf64b3522008-03-09 01:54:53 +00002710 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002711 if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
2712 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2713 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002714 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002715 /*foundnonskip*/false, /*foundelse*/false);
2716 } else if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002717 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002718 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002719 /*foundnonskip*/true, /*foundelse*/false);
2720 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002721 // No, skip the contents of this block.
Vedant Kumar3919a502017-09-11 20:47:42 +00002722 SkipExcludedConditionalBlock(HashToken, IfToken.getLocation(),
2723 /*Foundnonskip*/ false,
2724 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002725 }
2726}
2727
James Dennettf6333ac2012-06-22 05:46:07 +00002728/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002729///
2730void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2731 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002732
Chris Lattnerf64b3522008-03-09 01:54:53 +00002733 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002734 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002735
Chris Lattnerf64b3522008-03-09 01:54:53 +00002736 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002737 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002738 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002739 Diag(EndifToken, diag::err_pp_endif_without_if);
2740 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002741 }
Mike Stump11289f42009-09-09 15:08:12 +00002742
Chris Lattnerf64b3522008-03-09 01:54:53 +00002743 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002744 if (CurPPLexer->getConditionalStackDepth() == 0)
2745 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002746
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002747 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002748 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002749
2750 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002751 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002752}
2753
James Dennettf6333ac2012-06-22 05:46:07 +00002754/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002755///
Vedant Kumar3919a502017-09-11 20:47:42 +00002756void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002757 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002758
Chris Lattnerf64b3522008-03-09 01:54:53 +00002759 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002760 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002761
Chris Lattnerf64b3522008-03-09 01:54:53 +00002762 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002763 if (CurPPLexer->popConditionalLevel(CI)) {
2764 Diag(Result, diag::pp_err_else_without_if);
2765 return;
2766 }
Mike Stump11289f42009-09-09 15:08:12 +00002767
Chris Lattnerf64b3522008-03-09 01:54:53 +00002768 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002769 if (CurPPLexer->getConditionalStackDepth() == 0)
2770 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002771
2772 // If this is a #else with a #else before it, report the error.
2773 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002774
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002775 if (Callbacks)
2776 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2777
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002778 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002779 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2780 // the directive blocks.
2781 CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002782 /*foundnonskip*/false, /*foundelse*/true);
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002783 return;
2784 }
2785
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002786 // Finally, skip the rest of the contents of this block.
Vedant Kumar3919a502017-09-11 20:47:42 +00002787 SkipExcludedConditionalBlock(HashToken, CI.IfLoc, /*Foundnonskip*/ true,
2788 /*FoundElse*/ true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002789}
2790
James Dennettf6333ac2012-06-22 05:46:07 +00002791/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002792///
Vedant Kumar3919a502017-09-11 20:47:42 +00002793void Preprocessor::HandleElifDirective(Token &ElifToken,
2794 const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002795 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002796
Chris Lattnerf64b3522008-03-09 01:54:53 +00002797 // #elif directive in a non-skipping conditional... start skipping.
2798 // We don't care what the condition is, because we will always skip it (since
2799 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002800 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002801 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002802 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002803
2804 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002805 if (CurPPLexer->popConditionalLevel(CI)) {
2806 Diag(ElifToken, diag::pp_err_elif_without_if);
2807 return;
2808 }
Mike Stump11289f42009-09-09 15:08:12 +00002809
Chris Lattnerf64b3522008-03-09 01:54:53 +00002810 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002811 if (CurPPLexer->getConditionalStackDepth() == 0)
2812 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002813
Chris Lattnerf64b3522008-03-09 01:54:53 +00002814 // If this is a #elif with a #else before it, report the error.
2815 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Taewook Oh755e4d22016-06-13 21:55:33 +00002816
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002817 if (Callbacks)
2818 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002819 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002820 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002821
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002822 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002823 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2824 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002825 CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002826 /*foundnonskip*/false, /*foundelse*/false);
2827 return;
2828 }
2829
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002830 // Finally, skip the rest of the contents of this block.
Vedant Kumar3919a502017-09-11 20:47:42 +00002831 SkipExcludedConditionalBlock(HashToken, CI.IfLoc, /*Foundnonskip*/ true,
2832 /*FoundElse*/ CI.FoundElse,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002833 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002834}