blob: eb9f11f3d4df8972dd71b6de77f3736280c2393a [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 Kumar3919a502017-09-11 20:47:42 +000082/// the tok::eod token is found. If the discarded tokens are in a skipped range,
83/// complete the range and pass it to the \c SourceRangeSkipped callback.
Chris Lattnerf64b3522008-03-09 01:54:53 +000084void Preprocessor::DiscardUntilEndOfDirective() {
85 Token Tmp;
86 do {
87 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000088 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000089 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000090}
91
Serge Pavlov07c0f042014-12-18 11:14:21 +000092/// \brief Enumerates possible cases of #define/#undef a reserved identifier.
93enum MacroDiag {
94 MD_NoWarn, //> Not a reserved identifier
95 MD_KeywordDef, //> Macro hides keyword, enabled by default
96 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
97};
98
99/// \brief Checks if the specified identifier is reserved in the specified
100/// language.
101/// This function does not check if the identifier is a keyword.
102static bool isReservedId(StringRef Text, const LangOptions &Lang) {
103 // C++ [macro.names], C11 7.1.3:
104 // All identifiers that begin with an underscore and either an uppercase
105 // letter or another underscore are always reserved for any use.
106 if (Text.size() >= 2 && Text[0] == '_' &&
107 (isUppercase(Text[1]) || Text[1] == '_'))
108 return true;
109 // C++ [global.names]
110 // Each name that contains a double underscore ... is reserved to the
111 // implementation for any use.
112 if (Lang.CPlusPlus) {
113 if (Text.find("__") != StringRef::npos)
114 return true;
115 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000116 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000117}
118
Serge Pavlov07c0f042014-12-18 11:14:21 +0000119static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
120 const LangOptions &Lang = PP.getLangOpts();
121 StringRef Text = II->getName();
122 if (isReservedId(Text, Lang))
123 return MD_ReservedMacro;
124 if (II->isKeyword(Lang))
125 return MD_KeywordDef;
126 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
127 return MD_KeywordDef;
128 return MD_NoWarn;
129}
130
131static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
132 const LangOptions &Lang = PP.getLangOpts();
133 StringRef Text = II->getName();
134 // Do not warn on keyword undef. It is generally harmless and widely used.
135 if (isReservedId(Text, Lang))
136 return MD_ReservedMacro;
137 return MD_NoWarn;
138}
139
Taewook Ohf42103c2016-06-13 20:40:21 +0000140// Return true if we want to issue a diagnostic by default if we
141// encounter this name in a #include with the wrong case. For now,
142// this includes the standard C and C++ headers, Posix headers,
143// and Boost headers. Improper case for these #includes is a
144// potential portability issue.
145static bool warnByDefaultOnWrongCase(StringRef Include) {
146 // If the first component of the path is "boost", treat this like a standard header
147 // for the purposes of diagnostics.
148 if (::llvm::sys::path::begin(Include)->equals_lower("boost"))
149 return true;
150
151 // "condition_variable" is the longest standard header name at 18 characters.
152 // If the include file name is longer than that, it can't be a standard header.
Taewook Oh755e4d22016-06-13 21:55:33 +0000153 static const size_t MaxStdHeaderNameLen = 18u;
Taewook Ohf42103c2016-06-13 20:40:21 +0000154 if (Include.size() > MaxStdHeaderNameLen)
155 return false;
156
157 // Lowercase and normalize the search string.
158 SmallString<32> LowerInclude{Include};
159 for (char &Ch : LowerInclude) {
160 // In the ASCII range?
George Burgess IV5d3bd932016-06-16 02:30:33 +0000161 if (static_cast<unsigned char>(Ch) > 0x7f)
Taewook Ohf42103c2016-06-13 20:40:21 +0000162 return false; // Can't be a standard header
163 // ASCII lowercase:
164 if (Ch >= 'A' && Ch <= 'Z')
165 Ch += 'a' - 'A';
166 // Normalize path separators for comparison purposes.
167 else if (::llvm::sys::path::is_separator(Ch))
168 Ch = '/';
169 }
170
171 // The standard C/C++ and Posix headers
172 return llvm::StringSwitch<bool>(LowerInclude)
173 // C library headers
174 .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
175 .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
176 .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
177 .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
178 .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
179 .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
180
181 // C++ headers for C library facilities
182 .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
183 .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
184 .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
185 .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
186 .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
187 .Case("cwctype", true)
188
189 // C++ library headers
190 .Cases("algorithm", "fstream", "list", "regex", "thread", true)
191 .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
192 .Cases("atomic", "future", "map", "set", "type_traits", true)
193 .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
194 .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
195 .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
196 .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
197 .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
198 .Cases("deque", "istream", "queue", "string", "valarray", true)
199 .Cases("exception", "iterator", "random", "strstream", "vector", true)
200 .Cases("forward_list", "limits", "ratio", "system_error", true)
201
202 // POSIX headers (which aren't also C headers)
203 .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
204 .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
205 .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
206 .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
207 .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
208 .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
209 .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
210 .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
211 .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
212 .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
213 .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
214 .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
215 .Default(false);
216}
217
Serge Pavlov07c0f042014-12-18 11:14:21 +0000218bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
219 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000220 // Missing macro name?
221 if (MacroNameTok.is(tok::eod))
222 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
223
224 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Olivier Goffart90f981b2017-07-14 09:23:40 +0000225 if (!II)
226 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000227
Olivier Goffart90f981b2017-07-14 09:23:40 +0000228 if (II->isCPlusPlusOperatorKeyword()) {
Alp Tokere03e9e12014-05-31 16:32:22 +0000229 // C++ 2.5p2: Alternative tokens behave the same as its primary token
230 // except for their spellings.
231 Diag(MacroNameTok, getLangOpts().MicrosoftExt
232 ? diag::ext_pp_operator_used_as_macro_name
233 : diag::err_pp_operator_used_as_macro_name)
234 << II << MacroNameTok.getKind();
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000235 // Allow #defining |and| and friends for Microsoft compatibility or
236 // recovery when legacy C headers are included in C++.
Alp Tokerb05e0b52014-05-21 06:13:51 +0000237 }
238
Serge Pavlovd024f522014-10-24 17:31:32 +0000239 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000240 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
241 return Diag(MacroNameTok, diag::err_defined_macro_name);
242 }
243
Richard Smith20e883e2015-04-29 23:20:19 +0000244 if (isDefineUndef == MU_Undef) {
245 auto *MI = getMacroInfo(II);
246 if (MI && MI->isBuiltinMacro()) {
247 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
248 // and C++ [cpp.predefined]p4], but allow it as an extension.
249 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
250 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000251 }
252
Serge Pavlov07c0f042014-12-18 11:14:21 +0000253 // If defining/undefining reserved identifier or a keyword, we need to issue
254 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000255 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000256 if (ShadowFlag)
257 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000258 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
Mehdi Amini99d1b292016-10-01 16:38:28 +0000259 (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000260 MacroDiag D = MD_NoWarn;
261 if (isDefineUndef == MU_Define) {
262 D = shouldWarnOnMacroDef(*this, II);
263 }
264 else if (isDefineUndef == MU_Undef)
265 D = shouldWarnOnMacroUndef(*this, II);
266 if (D == MD_KeywordDef) {
267 // We do not want to warn on some patterns widely used in configuration
268 // scripts. This requires analyzing next tokens, so do not issue warnings
269 // now, only inform caller.
270 if (ShadowFlag)
271 *ShadowFlag = true;
272 }
273 if (D == MD_ReservedMacro)
274 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000275 }
276
Alp Tokerb05e0b52014-05-21 06:13:51 +0000277 // Okay, we got a good identifier.
278 return false;
279}
280
James Dennettf6333ac2012-06-22 05:46:07 +0000281/// \brief Lex and validate a macro name, which occurs after a
282/// \#define or \#undef.
283///
Serge Pavlovd024f522014-10-24 17:31:32 +0000284/// This sets the token kind to eod and discards the rest of the macro line if
285/// the macro name is invalid.
286///
287/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000288/// \param isDefineUndef Context in which macro is used.
289/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
290void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
291 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000292 // Read the token, don't allow macro expansion on it.
293 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000294
Douglas Gregor12785102010-08-24 20:21:13 +0000295 if (MacroNameTok.is(tok::code_completion)) {
296 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000297 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000298 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000299 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000300 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000301
Serge Pavlov07c0f042014-12-18 11:14:21 +0000302 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000303 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000304
305 // Invalid macro name, read and discard the rest of the line and set the
306 // token kind to tok::eod if necessary.
307 if (MacroNameTok.isNot(tok::eod)) {
308 MacroNameTok.setKind(tok::eod);
309 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000310 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000311}
312
James Dennettf6333ac2012-06-22 05:46:07 +0000313/// \brief Ensure that the next token is a tok::eod token.
314///
315/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000316/// true, then we consider macros that expand to zero tokens as being ok.
317void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000318 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000319 // Lex unexpanded tokens for most directives: macros might expand to zero
320 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
321 // #line) allow empty macros.
322 if (EnableMacros)
323 Lex(Tmp);
324 else
325 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000326
Chris Lattnerf64b3522008-03-09 01:54:53 +0000327 // There should be no tokens after the directive, but we allow them as an
328 // extension.
329 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
330 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000331
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000332 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000333 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000334 // or if this is a macro-style preprocessing directive, because it is more
335 // trouble than it is worth to insert /**/ and check that there is no /**/
336 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000337 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000338 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000339 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000340 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
341 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000342 DiscardUntilEndOfDirective();
343 }
344}
345
James Dennettf6333ac2012-06-22 05:46:07 +0000346/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
347/// decided that the subsequent tokens are in the \#if'd out portion of the
348/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000349/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000350/// this \#if directive, so \#else/\#elif blocks should never be entered.
351/// If ElseOk is true, then \#else directives are ok, if not, then we have
352/// already seen one so a \#else directive is a duplicate. When this returns,
353/// the caller can lex the first valid token.
Vedant Kumar3919a502017-09-11 20:47:42 +0000354void Preprocessor::SkipExcludedConditionalBlock(const Token &HashToken,
355 SourceLocation IfTokenLoc,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000356 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000357 bool FoundElse,
358 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000359 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000360 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000361
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000362 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000363 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000364
Ted Kremenek56572ab2008-12-12 18:34:08 +0000365 if (CurPTHLexer) {
366 PTHSkipExcludedConditionalBlock();
367 return;
368 }
Mike Stump11289f42009-09-09 15:08:12 +0000369
Chris Lattnerf64b3522008-03-09 01:54:53 +0000370 // Enter raw mode to disable identifier lookup (and thus macro expansion),
371 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000372 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000373 Token Tok;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000374 while (true) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000375 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000376
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000377 if (Tok.is(tok::code_completion)) {
378 if (CodeComplete)
379 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000380 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000381 continue;
382 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000383
Chris Lattnerf64b3522008-03-09 01:54:53 +0000384 // If this is the end of the buffer, we have an error.
385 if (Tok.is(tok::eof)) {
Ilya Biryukov8f738ac2017-09-12 08:35:57 +0000386 // We don't emit errors for unterminated conditionals here,
387 // Lexer::LexEndOfFile can do that propertly.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000388 // Just return and let the caller lex after this #include.
389 break;
390 }
Mike Stump11289f42009-09-09 15:08:12 +0000391
Chris Lattnerf64b3522008-03-09 01:54:53 +0000392 // If this token is not a preprocessor directive, just skip it.
393 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
394 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Chris Lattnerf64b3522008-03-09 01:54:53 +0000396 // We just parsed a # character at the start of a line, so we're in
397 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000398 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000399 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000400 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000401
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattnerf64b3522008-03-09 01:54:53 +0000403 // Read the next token, the directive flavor.
404 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattnerf64b3522008-03-09 01:54:53 +0000406 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
407 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000408 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000409 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000410 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000411 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000412 continue;
413 }
414
415 // If the first letter isn't i or e, it isn't intesting to us. We know that
416 // this is safe in the face of spelling differences, because there is no way
417 // to spell an i/e in a strange way that is another letter. Skipping this
418 // allows us to avoid looking up the identifier info for #define/#undef and
419 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000420 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000421
Alp Toker2d57cea2014-05-17 04:53:25 +0000422 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000423 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000424 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000425 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000426 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000427 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000428 continue;
429 }
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattnerf64b3522008-03-09 01:54:53 +0000431 // Get the identifier name without trigraphs or embedded newlines. Note
432 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
433 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000434 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000435 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000436 if (!Tok.needsCleaning() && RI.size() < 20) {
437 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000438 } else {
439 std::string DirectiveStr = getSpelling(Tok);
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000440 size_t IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000441 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000442 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000443 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000444 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000445 continue;
446 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000447 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000448 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000449 }
Mike Stump11289f42009-09-09 15:08:12 +0000450
Benjamin Kramer144884642009-12-31 13:32:38 +0000451 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000452 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000453 if (Sub.empty() || // "if"
454 Sub == "def" || // "ifdef"
455 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000456 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
457 // bother parsing the condition.
458 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000459 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000460 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000461 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000462 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000463 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000464 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000465 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000466 PPConditionalInfo CondInfo;
467 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000468 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000469 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000470 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000471
Chris Lattnerf64b3522008-03-09 01:54:53 +0000472 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000473 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000474 // Restore the value of LexingRawMode so that trailing comments
475 // are handled correctly, if we've reached the outermost block.
476 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000477 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000478 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000479 if (Callbacks)
480 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000481 break;
Richard Smithd0124572012-06-21 00:35:03 +0000482 } else {
483 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000484 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000485 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000486 // #else directive in a skipping conditional. If not in some other
487 // skipping conditional, and if #else hasn't already been seen, enter it
488 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000489 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000490
Chris Lattnerf64b3522008-03-09 01:54:53 +0000491 // If this is a #else with a #else before it, report the error.
492 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000493
Chris Lattnerf64b3522008-03-09 01:54:53 +0000494 // Note that we've seen a #else in this conditional.
495 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000496
Chris Lattnerf64b3522008-03-09 01:54:53 +0000497 // If the conditional is at the top level, and the #if block wasn't
498 // entered, enter the #else block now.
499 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
500 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000501 // Restore the value of LexingRawMode so that trailing comments
502 // are handled correctly.
503 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000504 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000505 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000506 if (Callbacks)
507 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000508 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000509 } else {
510 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000511 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000512 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000513 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000514
John Thompson17c35732013-12-04 20:19:30 +0000515 // If this is a #elif with a #else before it, report the error.
516 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
517
Chris Lattnerf64b3522008-03-09 01:54:53 +0000518 // If this is in a skipping block or if we're already handled this #if
519 // block, don't bother parsing the condition.
520 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
521 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000522 } else {
John Thompson17c35732013-12-04 20:19:30 +0000523 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000524 // Restore the value of LexingRawMode so that identifiers are
525 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000526 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
527 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000528 IdentifierInfo *IfNDefMacro = nullptr;
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +0000529 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro).Conditional;
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000530 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000531 if (Callbacks) {
532 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000533 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000534 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000535 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000536 }
537 // If this condition is true, enter it!
538 if (CondValue) {
539 CondInfo.FoundNonSkip = true;
540 break;
541 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000542 }
543 }
544 }
Mike Stump11289f42009-09-09 15:08:12 +0000545
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000546 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000547 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000548 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000549 }
550
551 // Finally, if we are out of the conditional (saw an #endif or ran off the end
552 // of the file, just stop skipping and return to lexing whatever came after
553 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000554 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000555
Vedant Kumar3919a502017-09-11 20:47:42 +0000556 if (Callbacks)
557 Callbacks->SourceRangeSkipped(
558 SourceRange(HashToken.getLocation(), CurPPLexer->getSourceLocation()),
559 Tok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000560}
561
Ted Kremenek56572ab2008-12-12 18:34:08 +0000562void Preprocessor::PTHSkipExcludedConditionalBlock() {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000563 while (true) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000564 assert(CurPTHLexer);
565 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000566
Ted Kremenek56572ab2008-12-12 18:34:08 +0000567 // Skip to the next '#else', '#elif', or #endif.
568 if (CurPTHLexer->SkipBlock()) {
569 // We have reached an #endif. Both the '#' and 'endif' tokens
570 // have been consumed by the PTHLexer. Just pop off the condition level.
571 PPConditionalInfo CondInfo;
572 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000573 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000574 assert(!InCond && "Can't be skipping if not in a conditional!");
575 break;
576 }
Mike Stump11289f42009-09-09 15:08:12 +0000577
Ted Kremenek56572ab2008-12-12 18:34:08 +0000578 // We have reached a '#else' or '#elif'. Lex the next token to get
579 // the directive flavor.
580 Token Tok;
581 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000582
Ted Kremenek56572ab2008-12-12 18:34:08 +0000583 // We can actually look up the IdentifierInfo here since we aren't in
584 // raw mode.
585 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
586
587 if (K == tok::pp_else) {
588 // #else: Enter the else condition. We aren't in a nested condition
589 // since we skip those. We're always in the one matching the last
590 // blocked we skipped.
591 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
592 // Note that we've seen a #else in this conditional.
593 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000594
Ted Kremenek56572ab2008-12-12 18:34:08 +0000595 // If the #if block wasn't entered then enter the #else block now.
596 if (!CondInfo.FoundNonSkip) {
597 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000598
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000599 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000600 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000601 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000602 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000603
Ted Kremenek56572ab2008-12-12 18:34:08 +0000604 break;
605 }
Mike Stump11289f42009-09-09 15:08:12 +0000606
Ted Kremenek56572ab2008-12-12 18:34:08 +0000607 // Otherwise skip this block.
608 continue;
609 }
Mike Stump11289f42009-09-09 15:08:12 +0000610
Ted Kremenek56572ab2008-12-12 18:34:08 +0000611 assert(K == tok::pp_elif);
612 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
613
614 // If this is a #elif with a #else before it, report the error.
615 if (CondInfo.FoundElse)
616 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000617
Ted Kremenek56572ab2008-12-12 18:34:08 +0000618 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000619 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000620 if (CondInfo.FoundNonSkip)
621 continue;
622
623 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000624 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000625 CurPTHLexer->ParsingPreprocessorDirective = true;
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +0000626 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro).Conditional;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000627 CurPTHLexer->ParsingPreprocessorDirective = false;
628
629 // If this condition is true, enter it!
630 if (ShouldEnter) {
631 CondInfo.FoundNonSkip = true;
632 break;
633 }
634
635 // Otherwise, skip this block and go to the next one.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000636 }
637}
638
Richard Smith2a553082015-04-23 22:58:06 +0000639Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000640 if (!SourceMgr.isInMainFile(Loc)) {
641 // Try to determine the module of the include directive.
642 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
643 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
644 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
645 // The include comes from an included file.
646 return HeaderInfo.getModuleMap()
647 .findModuleForHeader(EntryOfIncl)
648 .getModule();
649 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000650 }
Richard Smith7e82e012016-02-19 22:25:36 +0000651
652 // This is either in the main file or not in a file at all. It belongs
653 // to the current module, if there is one.
654 return getLangOpts().CurrentModule.empty()
655 ? nullptr
656 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000657}
658
Richard Smith4eb83932016-04-27 21:57:05 +0000659const FileEntry *
660Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000661 Module *M,
Richard Smith4eb83932016-04-27 21:57:05 +0000662 SourceLocation Loc) {
Richard Smithcbf7d8a2017-05-19 23:49:00 +0000663 assert(M && "no module to include");
664
Richard Smith4eb83932016-04-27 21:57:05 +0000665 // If we have a module import syntax, we shouldn't include a header to
666 // make a particular module visible.
667 if (getLangOpts().ObjC2)
668 return nullptr;
669
Richard Smith4eb83932016-04-27 21:57:05 +0000670 Module *TopM = M->getTopLevelModule();
671 Module *IncM = getModuleForLocation(IncLoc);
672
673 // Walk up through the include stack, looking through textual headers of M
674 // until we hit a non-textual header that we can #include. (We assume textual
675 // headers of a module with non-textual headers aren't meant to be used to
676 // import entities from the module.)
677 auto &SM = getSourceManager();
678 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
679 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
680 auto *FE = SM.getFileEntryForID(ID);
Richard Smith040e1262017-06-02 01:55:39 +0000681 if (!FE)
682 break;
Richard Smith4eb83932016-04-27 21:57:05 +0000683
684 bool InTextualHeader = false;
685 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
686 if (!Header.getModule()->isSubModuleOf(TopM))
687 continue;
688
689 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
690 // If this is an accessible, non-textual header of M's top-level module
691 // that transitively includes the given location and makes the
692 // corresponding module visible, this is the thing to #include.
693 if (Header.isAccessibleFrom(IncM))
694 return FE;
695
696 // It's in a private header; we can't #include it.
697 // FIXME: If there's a public header in some module that re-exports it,
698 // then we could suggest including that, but it's not clear that's the
699 // expected way to make this entity visible.
700 continue;
701 }
702
703 InTextualHeader = true;
704 }
705
706 if (!InTextualHeader)
707 break;
708
709 Loc = SM.getIncludeLoc(ID);
710 }
711
712 return nullptr;
713}
714
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000715const FileEntry *Preprocessor::LookupFile(
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000716 SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
717 const DirectoryLookup *FromDir, const FileEntry *FromFile,
718 const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000719 SmallVectorImpl<char> *RelativePath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000720 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000721 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000722 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000723
Will Wilson0fafd342013-12-27 19:46:16 +0000724 // If the header lookup mechanism may be relative to the current inclusion
725 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000726 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
727 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000728 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000729 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000730 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000731 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattner022923a2009-02-04 19:45:07 +0000733 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000734 // predefines buffer or the module includes buffer. Any other file is not
735 // lexed with a normal lexer, so it won't be scanned for preprocessor
736 // directives.
737 //
738 // If we have the predefines buffer, resolve #include references (which come
739 // from the -include command line argument) from the current working
740 // directory instead of relative to the main file.
741 //
742 // If we have the module includes buffer, resolve #include references (which
743 // come from header declarations in the module map) relative to the module
744 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000745 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000746 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000747 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000748 BuildSystemModule = getCurrentModule()->IsSystem;
749 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000750 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000751 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
752 } else {
753 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
754 }
Will Wilson0fafd342013-12-27 19:46:16 +0000755
756 // MSVC searches the current include stack from top to bottom for
757 // headers included by quoted include directives.
758 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000759 if (LangOpts.MSVCCompat && !isAngled) {
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000760 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000761 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000762 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000763 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000764 }
Chris Lattner022923a2009-02-04 19:45:07 +0000765 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000766 }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000768 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000769
770 if (FromFile) {
771 // We're supposed to start looking from after a particular file. Search
772 // the include path until we find that file or run out of files.
773 const DirectoryLookup *TmpCurDir = CurDir;
774 const DirectoryLookup *TmpFromDir = nullptr;
775 while (const FileEntry *FE = HeaderInfo.LookupFile(
776 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000777 Includers, SearchPath, RelativePath, RequestingModule,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000778 SuggestedModule, /*IsMapped=*/nullptr, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000779 // Keep looking as if this file did a #include_next.
780 TmpFromDir = TmpCurDir;
781 ++TmpFromDir;
782 if (FE == FromFile) {
783 // Found it.
784 FromDir = TmpFromDir;
785 CurDir = TmpCurDir;
786 break;
787 }
788 }
789 }
790
791 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000792 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000793 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000794 RelativePath, RequestingModule, SuggestedModule, IsMapped, SkipCache,
Manman Rene4a5d372016-05-17 02:15:12 +0000795 BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000796 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000797 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000798 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000799 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
800 Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000801 return FE;
802 }
Mike Stump11289f42009-09-09 15:08:12 +0000803
Will Wilson0fafd342013-12-27 19:46:16 +0000804 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000805 // Otherwise, see if this is a subframework header. If so, this is relative
806 // to one of the headers on the #include stack. Walk the list of the current
807 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000808 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000809 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000810 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000811 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000812 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000813 SuggestedModule))) {
814 if (SuggestedModule && !LangOpts.AsmPreprocessor)
815 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000816 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
817 Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000818 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000819 }
820 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000821 }
Mike Stump11289f42009-09-09 15:08:12 +0000822
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +0000823 for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000824 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000825 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000826 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000827 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000828 RequestingModule, SuggestedModule))) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000829 if (SuggestedModule && !LangOpts.AsmPreprocessor)
830 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000831 RequestingModule, RequestingModuleIsModuleInterface,
832 FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000833 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000834 }
835 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000836 }
837 }
Mike Stump11289f42009-09-09 15:08:12 +0000838
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000839 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000840 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000841}
842
Chris Lattnerf64b3522008-03-09 01:54:53 +0000843//===----------------------------------------------------------------------===//
844// Preprocessor Directive Handling.
845//===----------------------------------------------------------------------===//
846
David Blaikied5321242012-06-06 18:52:13 +0000847class Preprocessor::ResetMacroExpansionHelper {
848public:
849 ResetMacroExpansionHelper(Preprocessor *pp)
850 : PP(pp), save(pp->DisableMacroExpansion) {
851 if (pp->MacroExpansionInDirectivesOverride)
852 pp->DisableMacroExpansion = false;
853 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000854
David Blaikied5321242012-06-06 18:52:13 +0000855 ~ResetMacroExpansionHelper() {
856 PP->DisableMacroExpansion = save;
857 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000858
David Blaikied5321242012-06-06 18:52:13 +0000859private:
860 Preprocessor *PP;
861 bool save;
862};
863
Chris Lattnerf64b3522008-03-09 01:54:53 +0000864/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000865/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000866/// lexer/preprocessor state, and advances the lexer(s) so that the next token
867/// read is the correct one.
868void Preprocessor::HandleDirective(Token &Result) {
869 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000870
Chris Lattnerf64b3522008-03-09 01:54:53 +0000871 // We just parsed a # character at the start of a line, so we're in directive
872 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000873 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000874 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000875 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000876
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000877 bool ImmediatelyAfterTopLevelIfndef =
878 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
879 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
880
Chris Lattnerf64b3522008-03-09 01:54:53 +0000881 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000882
Chris Lattnerf64b3522008-03-09 01:54:53 +0000883 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000884 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000885 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000886 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000887
Chris Lattner2d17ab72009-03-18 21:00:25 +0000888 // Save the '#' token in case we need to return it later.
889 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000890
Chris Lattnerf64b3522008-03-09 01:54:53 +0000891 // Read the next token, the directive flavor. This isn't expanded due to
892 // C99 6.10.3p8.
893 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000894
Chris Lattnerf64b3522008-03-09 01:54:53 +0000895 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
896 // #define A(x) #x
897 // A(abc
898 // #warning blah
899 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000900 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
901 // not support this for #include-like directives, since that can result in
902 // terrible diagnostics, and does not work in GCC.
903 if (InMacroArgs) {
904 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
905 switch (II->getPPKeywordID()) {
906 case tok::pp_include:
907 case tok::pp_import:
908 case tok::pp_include_next:
909 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000910 case tok::pp_pragma:
911 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000912 DiscardUntilEndOfDirective();
913 return;
914 default:
915 break;
916 }
917 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000918 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000919 }
Mike Stump11289f42009-09-09 15:08:12 +0000920
David Blaikied5321242012-06-06 18:52:13 +0000921 // Temporarily enable macro expansion if set so
922 // and reset to previous state when returning from this function.
923 ResetMacroExpansionHelper helper(this);
924
Chris Lattnerf64b3522008-03-09 01:54:53 +0000925 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000926 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000927 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000928 case tok::code_completion:
929 if (CodeComplete)
930 CodeComplete->CodeCompleteDirective(
931 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000932 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000933 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000934 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000935 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000936 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000937 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000938 default:
939 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000940 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattnerf64b3522008-03-09 01:54:53 +0000942 // Ask what the preprocessor keyword ID is.
943 switch (II->getPPKeywordID()) {
944 default: break;
945 // C99 6.10.1 - Conditional Inclusion.
946 case tok::pp_if:
Vedant Kumar3919a502017-09-11 20:47:42 +0000947 return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000948 case tok::pp_ifdef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000949 return HandleIfdefDirective(Result, SavedHash, false,
950 true /*not valid for miopt*/);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000951 case tok::pp_ifndef:
Vedant Kumar3919a502017-09-11 20:47:42 +0000952 return HandleIfdefDirective(Result, SavedHash, true,
953 ReadAnyTokensBeforeDirective);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000954 case tok::pp_elif:
Vedant Kumar3919a502017-09-11 20:47:42 +0000955 return HandleElifDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000956 case tok::pp_else:
Vedant Kumar3919a502017-09-11 20:47:42 +0000957 return HandleElseDirective(Result, SavedHash);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000958 case tok::pp_endif:
959 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chris Lattnerf64b3522008-03-09 01:54:53 +0000961 // C99 6.10.2 - Source File Inclusion.
962 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000963 // Handle #include.
964 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000965 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000966 // Handle -imacros.
Taewook Oh755e4d22016-06-13 21:55:33 +0000967 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattnerf64b3522008-03-09 01:54:53 +0000969 // C99 6.10.3 - Macro Replacement.
970 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000971 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000972 case tok::pp_undef:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000973 return HandleUndefDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000974
975 // C99 6.10.4 - Line Control.
976 case tok::pp_line:
Erik Verbruggen4bddef92016-10-26 08:52:41 +0000977 return HandleLineDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattnerf64b3522008-03-09 01:54:53 +0000979 // C99 6.10.5 - Error Directive.
980 case tok::pp_error:
981 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000982
Chris Lattnerf64b3522008-03-09 01:54:53 +0000983 // C99 6.10.6 - Pragma Directive.
984 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000985 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000986
Chris Lattnerf64b3522008-03-09 01:54:53 +0000987 // GNU Extensions.
988 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000989 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000990 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000991 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000992
Chris Lattnerf64b3522008-03-09 01:54:53 +0000993 case tok::pp_warning:
994 Diag(Result, diag::ext_pp_warning_directive);
995 return HandleUserDiagnosticDirective(Result, true);
996 case tok::pp_ident:
997 return HandleIdentSCCSDirective(Result);
998 case tok::pp_sccs:
999 return HandleIdentSCCSDirective(Result);
1000 case tok::pp_assert:
1001 //isExtension = true; // FIXME: implement #assert
1002 break;
1003 case tok::pp_unassert:
1004 //isExtension = true; // FIXME: implement #unassert
1005 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001006
Douglas Gregor663b48f2012-01-03 19:48:16 +00001007 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001008 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001009 return HandleMacroPublicDirective(Result);
1010 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001011
Douglas Gregor663b48f2012-01-03 19:48:16 +00001012 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001013 if (getLangOpts().Modules)
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001014 return HandleMacroPrivateDirective();
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001015 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001016 }
1017 break;
1018 }
Mike Stump11289f42009-09-09 15:08:12 +00001019
Chris Lattner2d17ab72009-03-18 21:00:25 +00001020 // If this is a .S file, treat unknown # directives as non-preprocessor
1021 // directives. This is important because # may be a comment or introduce
1022 // various pseudo-ops. Just return the # token and push back the following
1023 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001024 if (getLangOpts().AsmPreprocessor) {
David Blaikie2eabcc92016-02-09 18:52:09 +00001025 auto Toks = llvm::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001026 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001027 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001028 Toks[1] = Result;
Taewook Oh755e4d22016-06-13 21:55:33 +00001029
Chris Lattner56f64c12011-01-06 05:01:51 +00001030 // If the second token is a hashhash token, then we need to translate it to
1031 // unknown so the token lexer doesn't try to perform token pasting.
1032 if (Result.is(tok::hashhash))
1033 Toks[1].setKind(tok::unknown);
Taewook Oh755e4d22016-06-13 21:55:33 +00001034
Chris Lattner2d17ab72009-03-18 21:00:25 +00001035 // Enter this token stream so that we re-lex the tokens. Make sure to
1036 // enable macro expansion, in case the token after the # is an identifier
1037 // that is expanded.
David Blaikie2eabcc92016-02-09 18:52:09 +00001038 EnterTokenStream(std::move(Toks), 2, false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001039 return;
1040 }
Mike Stump11289f42009-09-09 15:08:12 +00001041
Chris Lattnerf64b3522008-03-09 01:54:53 +00001042 // If we reached here, the preprocessing token is not valid!
1043 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001044
Chris Lattnerf64b3522008-03-09 01:54:53 +00001045 // Read the rest of the PP line.
1046 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattnerf64b3522008-03-09 01:54:53 +00001048 // Okay, we're done parsing the directive.
1049}
1050
Chris Lattner76e68962009-01-26 06:19:46 +00001051/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1052/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1053static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001054 unsigned DiagID, Preprocessor &PP,
1055 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001056 if (DigitTok.isNot(tok::numeric_constant)) {
1057 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001058
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001059 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001060 PP.DiscardUntilEndOfDirective();
1061 return true;
1062 }
Mike Stump11289f42009-09-09 15:08:12 +00001063
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001064 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001065 IntegerBuffer.resize(DigitTok.getLength());
1066 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001067 bool Invalid = false;
1068 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1069 if (Invalid)
1070 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001071
Chris Lattnerd66f1722009-04-18 18:35:15 +00001072 // Verify that we have a simple digit-sequence, and compute the value. This
1073 // is always a simple digit string computed in decimal, so we do this manually
1074 // here.
1075 Val = 0;
1076 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001077 // C++1y [lex.fcon]p1:
1078 // Optional separating single quotes in a digit-sequence are ignored
1079 if (DigitTokBegin[i] == '\'')
1080 continue;
1081
Jordan Rosea7d03842013-02-08 22:30:41 +00001082 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001083 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001084 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001085 PP.DiscardUntilEndOfDirective();
1086 return true;
1087 }
Mike Stump11289f42009-09-09 15:08:12 +00001088
Chris Lattnerd66f1722009-04-18 18:35:15 +00001089 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1090 if (NextVal < Val) { // overflow.
1091 PP.Diag(DigitTok, DiagID);
1092 PP.DiscardUntilEndOfDirective();
1093 return true;
1094 }
1095 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001096 }
Mike Stump11289f42009-09-09 15:08:12 +00001097
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001098 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001099 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1100 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001101
Chris Lattner76e68962009-01-26 06:19:46 +00001102 return false;
1103}
1104
James Dennettf6333ac2012-06-22 05:46:07 +00001105/// \brief Handle a \#line directive: C99 6.10.4.
1106///
1107/// The two acceptable forms are:
1108/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001109/// # line digit-sequence
1110/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001111/// \endverbatim
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001112void Preprocessor::HandleLineDirective() {
Chris Lattner100c65e2009-01-26 05:29:08 +00001113 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1114 // expanded.
1115 Token DigitTok;
1116 Lex(DigitTok);
1117
Chris Lattner100c65e2009-01-26 05:29:08 +00001118 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001119 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001120 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001121 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001122
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001123 if (LineNo == 0)
1124 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001125
Chris Lattner76e68962009-01-26 06:19:46 +00001126 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1127 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001128 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001129 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001130 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001131 if (LineNo >= LineLimit)
1132 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001133 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001134 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001135
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001136 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001137 Token StrTok;
1138 Lex(StrTok);
1139
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001140 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1141 // string followed by eod.
1142 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001143 ; // ok
1144 else if (StrTok.isNot(tok::string_literal)) {
1145 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001146 return DiscardUntilEndOfDirective();
1147 } else if (StrTok.hasUDSuffix()) {
1148 Diag(StrTok, diag::err_invalid_string_udl);
1149 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001150 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001151 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001152 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001153 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001154 if (Literal.hadError)
1155 return DiscardUntilEndOfDirective();
1156 if (Literal.Pascal) {
1157 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1158 return DiscardUntilEndOfDirective();
1159 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001160 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001161
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001162 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001163 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1164 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001165 }
Mike Stump11289f42009-09-09 15:08:12 +00001166
Reid Klecknereb00ee02017-05-22 21:42:58 +00001167 // Take the file kind of the file containing the #line directive. #line
1168 // directives are often used for generated sources from the same codebase, so
1169 // the new file should generally be classified the same way as the current
1170 // file. This is visible in GCC's pre-processed output, which rewrites #line
1171 // to GNU line markers.
1172 SrcMgr::CharacteristicKind FileKind =
1173 SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1174
1175 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1176 false, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001177
Chris Lattner839150e2009-03-27 17:13:49 +00001178 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001179 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Reid Klecknereb00ee02017-05-22 21:42:58 +00001180 PPCallbacks::RenameFile, FileKind);
Chris Lattner100c65e2009-01-26 05:29:08 +00001181}
1182
Chris Lattner76e68962009-01-26 06:19:46 +00001183/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1184/// marker directive.
1185static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
Reid Klecknereb00ee02017-05-22 21:42:58 +00001186 SrcMgr::CharacteristicKind &FileKind,
Chris Lattner76e68962009-01-26 06:19:46 +00001187 Preprocessor &PP) {
1188 unsigned FlagVal;
1189 Token FlagTok;
1190 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001191 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001192 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1193 return true;
1194
1195 if (FlagVal == 1) {
1196 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001197
Chris Lattner76e68962009-01-26 06:19:46 +00001198 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001199 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001200 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1201 return true;
1202 } else if (FlagVal == 2) {
1203 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001204
Chris Lattner1c967782009-02-04 06:25:26 +00001205 SourceManager &SM = PP.getSourceManager();
1206 // If we are leaving the current presumed file, check to make sure the
1207 // presumed include stack isn't empty!
1208 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001209 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001210 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001211 if (PLoc.isInvalid())
1212 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001213
Chris Lattner1c967782009-02-04 06:25:26 +00001214 // If there is no include loc (main file) or if the include loc is in a
1215 // different physical file, then we aren't in a "1" line marker flag region.
1216 SourceLocation IncLoc = PLoc.getIncludeLoc();
1217 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001218 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001219 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1220 PP.DiscardUntilEndOfDirective();
1221 return true;
1222 }
Mike Stump11289f42009-09-09 15:08:12 +00001223
Chris Lattner76e68962009-01-26 06:19:46 +00001224 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001225 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001226 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1227 return true;
1228 }
1229
1230 // We must have 3 if there are still flags.
1231 if (FlagVal != 3) {
1232 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001233 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001234 return true;
1235 }
Mike Stump11289f42009-09-09 15:08:12 +00001236
Reid Klecknereb00ee02017-05-22 21:42:58 +00001237 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001238
Chris Lattner76e68962009-01-26 06:19:46 +00001239 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001240 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001241 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001242 return true;
1243
1244 // We must have 4 if there is yet another flag.
1245 if (FlagVal != 4) {
1246 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001247 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001248 return true;
1249 }
Mike Stump11289f42009-09-09 15:08:12 +00001250
Reid Klecknereb00ee02017-05-22 21:42:58 +00001251 FileKind = SrcMgr::C_ExternCSystem;
Mike Stump11289f42009-09-09 15:08:12 +00001252
Chris Lattner76e68962009-01-26 06:19:46 +00001253 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001254 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001255
1256 // There are no more valid flags here.
1257 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001258 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001259 return true;
1260}
1261
1262/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1263/// one of the following forms:
1264///
1265/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001266/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001267/// # 42 "file" ('1' | '2')? '3' '4'?
1268///
1269void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1270 // Validate the number and convert it to an unsigned. GNU does not have a
1271 // line # limit other than it fit in 32-bits.
1272 unsigned LineNo;
1273 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001274 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001275 return;
Mike Stump11289f42009-09-09 15:08:12 +00001276
Chris Lattner76e68962009-01-26 06:19:46 +00001277 Token StrTok;
1278 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001279
Chris Lattner76e68962009-01-26 06:19:46 +00001280 bool IsFileEntry = false, IsFileExit = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001281 int FilenameID = -1;
Reid Klecknereb00ee02017-05-22 21:42:58 +00001282 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001283
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001284 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1285 // string followed by eod.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001286 if (StrTok.is(tok::eod)) {
1287 // Treat this like "#line NN", which doesn't change file characteristics.
1288 FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1289 } else if (StrTok.isNot(tok::string_literal)) {
Chris Lattner76e68962009-01-26 06:19:46 +00001290 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001291 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001292 } else if (StrTok.hasUDSuffix()) {
1293 Diag(StrTok, diag::err_invalid_string_udl);
1294 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001295 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001296 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001297 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001298 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001299 if (Literal.hadError)
1300 return DiscardUntilEndOfDirective();
1301 if (Literal.Pascal) {
1302 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1303 return DiscardUntilEndOfDirective();
1304 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001305 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001306
Chris Lattner76e68962009-01-26 06:19:46 +00001307 // If a filename was present, read any flags that are present.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001308 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001309 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001310 }
Mike Stump11289f42009-09-09 15:08:12 +00001311
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001312 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +00001313 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1314 IsFileExit, FileKind);
Mike Stump11289f42009-09-09 15:08:12 +00001315
Chris Lattner839150e2009-03-27 17:13:49 +00001316 // If the preprocessor has callbacks installed, notify them of the #line
1317 // change. This is used so that the line marker comes out in -E mode for
1318 // example.
1319 if (Callbacks) {
1320 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1321 if (IsFileEntry)
1322 Reason = PPCallbacks::EnterFile;
1323 else if (IsFileExit)
1324 Reason = PPCallbacks::ExitFile;
Mike Stump11289f42009-09-09 15:08:12 +00001325
Chris Lattnerc745cec2010-04-14 04:28:50 +00001326 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001327 }
Chris Lattner76e68962009-01-26 06:19:46 +00001328}
1329
Chris Lattner38d7fd22009-01-26 05:30:54 +00001330/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1331///
Mike Stump11289f42009-09-09 15:08:12 +00001332void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001333 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001334 // PTH doesn't emit #warning or #error directives.
1335 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001336 return CurPTHLexer->DiscardToEndOfLine();
1337
Chris Lattnerf64b3522008-03-09 01:54:53 +00001338 // Read the rest of the line raw. We do this because we don't want macros
1339 // to be expanded and we don't require that the tokens be valid preprocessing
1340 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1341 // collapse multiple consequtive white space between tokens, but this isn't
1342 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001343 SmallString<128> Message;
1344 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001345
1346 // Find the first non-whitespace character, so that we can make the
1347 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001348 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001349
Chris Lattner100c65e2009-01-26 05:29:08 +00001350 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001351 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001352 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001353 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001354}
1355
1356/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1357///
1358void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1359 // Yes, this directive is an extension.
1360 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001361
Chris Lattnerf64b3522008-03-09 01:54:53 +00001362 // Read the string argument.
1363 Token StrTok;
1364 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001365
Chris Lattnerf64b3522008-03-09 01:54:53 +00001366 // If the token kind isn't a string, it's a malformed directive.
1367 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001368 StrTok.isNot(tok::wide_string_literal)) {
1369 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001370 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001371 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001372 return;
1373 }
Mike Stump11289f42009-09-09 15:08:12 +00001374
Richard Smithd67aea22012-03-06 03:21:47 +00001375 if (StrTok.hasUDSuffix()) {
1376 Diag(StrTok, diag::err_invalid_string_udl);
1377 return DiscardUntilEndOfDirective();
1378 }
1379
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001380 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001381 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001382
Douglas Gregordc970f02010-03-16 22:30:13 +00001383 if (Callbacks) {
1384 bool Invalid = false;
1385 std::string Str = getSpelling(StrTok, &Invalid);
1386 if (!Invalid)
1387 Callbacks->Ident(Tok.getLocation(), Str);
1388 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001389}
1390
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001391/// \brief Handle a #public directive.
1392void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001393 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001394 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001395
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001396 // Error reading macro name? If so, diagnostic already issued.
1397 if (MacroNameTok.is(tok::eod))
1398 return;
1399
Douglas Gregor663b48f2012-01-03 19:48:16 +00001400 // Check to see if this is the last token on the #__public_macro line.
1401 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001402
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001403 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001404 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001405 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001406
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001407 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001408 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001409 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001410 return;
1411 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001412
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001413 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001414 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1415 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001416}
1417
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001418/// \brief Handle a #private directive.
Erik Verbruggen4bddef92016-10-26 08:52:41 +00001419void Preprocessor::HandleMacroPrivateDirective() {
Douglas Gregorebf00492011-10-17 15:32:29 +00001420 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001421 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001422
Douglas Gregorebf00492011-10-17 15:32:29 +00001423 // Error reading macro name? If so, diagnostic already issued.
1424 if (MacroNameTok.is(tok::eod))
1425 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001426
Douglas Gregor663b48f2012-01-03 19:48:16 +00001427 // Check to see if this is the last token on the #__private_macro line.
1428 CheckEndOfDirective("__private_macro");
Taewook Oh755e4d22016-06-13 21:55:33 +00001429
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001430 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001431 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001432 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001433
Douglas Gregorebf00492011-10-17 15:32:29 +00001434 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001435 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001436 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001437 return;
1438 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001439
Douglas Gregorebf00492011-10-17 15:32:29 +00001440 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001441 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1442 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001443}
1444
Chris Lattnerf64b3522008-03-09 01:54:53 +00001445//===----------------------------------------------------------------------===//
1446// Preprocessor Include Directive Handling.
1447//===----------------------------------------------------------------------===//
1448
1449/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001450/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001451/// true if the input filename was in <>'s or false if it were in ""'s. The
1452/// caller is expected to provide a buffer that is large enough to hold the
1453/// spelling of the filename, but is also expected to handle the case when
1454/// this method decides to use a different buffer.
1455bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001456 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001457 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001458 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattnerf64b3522008-03-09 01:54:53 +00001460 // Make sure the filename is <x> or "x".
1461 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001462 if (Buffer[0] == '<') {
1463 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001464 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001465 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001466 return true;
1467 }
1468 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001469 } else if (Buffer[0] == '"') {
1470 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001471 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001472 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001473 return true;
1474 }
1475 isAngled = false;
1476 } else {
1477 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001478 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001479 return true;
1480 }
Mike Stump11289f42009-09-09 15:08:12 +00001481
Chris Lattnerf64b3522008-03-09 01:54:53 +00001482 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001483 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001484 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001485 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001486 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001487 }
Mike Stump11289f42009-09-09 15:08:12 +00001488
Chris Lattnerf64b3522008-03-09 01:54:53 +00001489 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001490 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001491 return isAngled;
1492}
1493
James Dennett4a4f72d2013-11-27 01:27:40 +00001494// \brief Handle cases where the \#include name is expanded from a macro
1495// as multiple tokens, which need to be glued together.
1496//
1497// This occurs for code like:
1498// \code
1499// \#define FOO <a/b.h>
1500// \#include FOO
1501// \endcode
1502// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1503//
1504// This code concatenates and consumes tokens up to the '>' token. It returns
1505// false if the > was found, otherwise it returns true if it finds and consumes
1506// the EOD marker.
1507bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001508 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001509 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001510
John Thompsonb5353522009-10-30 13:49:06 +00001511 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001512 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001513 End = CurTok.getLocation();
Taewook Oh755e4d22016-06-13 21:55:33 +00001514
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001515 // FIXME: Provide code completion for #includes.
1516 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001517 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001518 Lex(CurTok);
1519 continue;
1520 }
1521
Chris Lattnerf64b3522008-03-09 01:54:53 +00001522 // Append the spelling of this token to the buffer. If there was a space
1523 // before it, add it now.
1524 if (CurTok.hasLeadingSpace())
1525 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattnerf64b3522008-03-09 01:54:53 +00001527 // Get the spelling of the token, directly into FilenameBuffer if possible.
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001528 size_t PreAppendSize = FilenameBuffer.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001529 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001530
Chris Lattnerf64b3522008-03-09 01:54:53 +00001531 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001532 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001533
Chris Lattnerf64b3522008-03-09 01:54:53 +00001534 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1535 if (BufPtr != &FilenameBuffer[PreAppendSize])
1536 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001537
Chris Lattnerf64b3522008-03-09 01:54:53 +00001538 // Resize FilenameBuffer to the correct size.
1539 if (CurTok.getLength() != ActualLen)
1540 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001541
Chris Lattnerf64b3522008-03-09 01:54:53 +00001542 // If we found the '>' marker, return success.
1543 if (CurTok.is(tok::greater))
1544 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001545
John Thompsonb5353522009-10-30 13:49:06 +00001546 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001547 }
1548
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001549 // If we hit the eod marker, emit an error and return true so that the caller
1550 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001551 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001552 return true;
1553}
1554
Richard Smith34f30512013-11-23 04:06:09 +00001555/// \brief Push a token onto the token stream containing an annotation.
Richard Smithc51c38b2017-04-29 00:34:47 +00001556void Preprocessor::EnterAnnotationToken(SourceRange Range,
1557 tok::TokenKind Kind,
1558 void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001559 // FIXME: Produce this as the current token directly, rather than
1560 // allocating a new token for it.
David Blaikie2eabcc92016-02-09 18:52:09 +00001561 auto Tok = llvm::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001562 Tok[0].startToken();
1563 Tok[0].setKind(Kind);
Richard Smithc51c38b2017-04-29 00:34:47 +00001564 Tok[0].setLocation(Range.getBegin());
1565 Tok[0].setAnnotationEndLoc(Range.getEnd());
Richard Smith34f30512013-11-23 04:06:09 +00001566 Tok[0].setAnnotationValue(AnnotationVal);
Richard Smithc51c38b2017-04-29 00:34:47 +00001567 EnterTokenStream(std::move(Tok), 1, true);
Richard Smith34f30512013-11-23 04:06:09 +00001568}
1569
Richard Smith63b6fce2015-05-18 04:45:41 +00001570/// \brief Produce a diagnostic informing the user that a #include or similar
1571/// was implicitly treated as a module import.
1572static void diagnoseAutoModuleImport(
1573 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1574 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1575 SourceLocation PathEnd) {
1576 assert(PP.getLangOpts().ObjC2 && "no import syntax available");
1577
1578 SmallString<128> PathString;
Erik Verbruggen4d5b99a2016-10-26 09:58:31 +00001579 for (size_t I = 0, N = Path.size(); I != N; ++I) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001580 if (I)
1581 PathString += '.';
1582 PathString += Path[I].first->getName();
1583 }
1584 int IncludeKind = 0;
Taewook Oh755e4d22016-06-13 21:55:33 +00001585
Richard Smith63b6fce2015-05-18 04:45:41 +00001586 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1587 case tok::pp_include:
1588 IncludeKind = 0;
1589 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001590
Richard Smith63b6fce2015-05-18 04:45:41 +00001591 case tok::pp_import:
1592 IncludeKind = 1;
Taewook Oh755e4d22016-06-13 21:55:33 +00001593 break;
1594
Richard Smith63b6fce2015-05-18 04:45:41 +00001595 case tok::pp_include_next:
1596 IncludeKind = 2;
1597 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001598
Richard Smith63b6fce2015-05-18 04:45:41 +00001599 case tok::pp___include_macros:
1600 IncludeKind = 3;
1601 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001602
Richard Smith63b6fce2015-05-18 04:45:41 +00001603 default:
1604 llvm_unreachable("unknown include directive kind");
1605 }
1606
1607 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1608 /*IsTokenRange=*/false);
1609 PP.Diag(HashLoc, diag::warn_auto_module_import)
1610 << IncludeKind << PathString
1611 << FixItHint::CreateReplacement(ReplaceRange,
1612 ("@import " + PathString + ";").str());
1613}
1614
Taewook Ohf42103c2016-06-13 20:40:21 +00001615// Given a vector of path components and a string containing the real
1616// path to the file, build a properly-cased replacement in the vector,
1617// and return true if the replacement should be suggested.
1618static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1619 StringRef RealPathName) {
1620 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1621 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1622 int Cnt = 0;
1623 bool SuggestReplacement = false;
1624 // Below is a best-effort to handle ".." in paths. It is admittedly
1625 // not 100% correct in the presence of symlinks.
1626 for (auto &Component : llvm::reverse(Components)) {
1627 if ("." == Component) {
1628 } else if (".." == Component) {
1629 ++Cnt;
1630 } else if (Cnt) {
1631 --Cnt;
1632 } else if (RealPathComponentIter != RealPathComponentEnd) {
1633 if (Component != *RealPathComponentIter) {
1634 // If these path components differ by more than just case, then we
1635 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1636 // noisy false positives.
1637 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1638 if (!SuggestReplacement)
1639 break;
1640 Component = *RealPathComponentIter;
1641 }
1642 ++RealPathComponentIter;
1643 }
1644 }
1645 return SuggestReplacement;
1646}
1647
Richard Smith27e5aa02017-06-05 18:57:56 +00001648bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
1649 const TargetInfo &TargetInfo,
1650 DiagnosticsEngine &Diags, Module *M) {
1651 Module::Requirement Requirement;
1652 Module::UnresolvedHeaderDirective MissingHeader;
1653 if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader))
1654 return false;
1655
1656 if (MissingHeader.FileNameLoc.isValid()) {
1657 Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1658 << MissingHeader.IsUmbrella << MissingHeader.FileName;
1659 } else {
1660 // FIXME: Track the location at which the requirement was specified, and
1661 // use it here.
1662 Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
1663 << M->getFullModuleName() << Requirement.second << Requirement.first;
1664 }
1665 return true;
1666}
1667
James Dennettf6333ac2012-06-22 05:46:07 +00001668/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1669/// the file to be included from the lexer, then include it! This is a common
1670/// routine with functionality shared between \#include, \#include_next and
1671/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001672/// specifies the file to start searching from.
Taewook Oh755e4d22016-06-13 21:55:33 +00001673void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001674 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001675 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001676 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001677 bool isImport) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001678 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001679 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattnerf64b3522008-03-09 01:54:53 +00001681 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001682 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001683 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001684 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001685 SourceLocation CharEnd; // the end of this directive, in characters
Taewook Oh755e4d22016-06-13 21:55:33 +00001686
Chris Lattnerf64b3522008-03-09 01:54:53 +00001687 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001688 case tok::eod:
1689 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001690 return;
Mike Stump11289f42009-09-09 15:08:12 +00001691
Chris Lattnerf64b3522008-03-09 01:54:53 +00001692 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001693 case tok::string_literal:
1694 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001695 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001696 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001697 break;
Mike Stump11289f42009-09-09 15:08:12 +00001698
Chris Lattnerf64b3522008-03-09 01:54:53 +00001699 case tok::less:
1700 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1701 // case, glue the tokens together into FilenameBuffer and interpret those.
1702 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001703 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001704 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001705 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001706 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001707 break;
1708 default:
1709 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1710 DiscardUntilEndOfDirective();
1711 return;
1712 }
Mike Stump11289f42009-09-09 15:08:12 +00001713
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001714 CharSourceRange FilenameRange
1715 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001716 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001717 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001718 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001719 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1720 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001721 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001722 DiscardUntilEndOfDirective();
1723 return;
1724 }
Mike Stump11289f42009-09-09 15:08:12 +00001725
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001726 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001727 // we allow macros that expand to nothing after the filename, because this
1728 // falls into the category of "#include pp-tokens new-line" specified in
1729 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001730 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001731
1732 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001733 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1734 Diag(FilenameTok, diag::err_pp_include_too_deep);
1735 return;
1736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
John McCall32f5fe12011-09-30 05:12:12 +00001738 // Complain about attempts to #include files in an audit pragma.
1739 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1740 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1741 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1742
1743 // Immediately leave the pragma.
1744 PragmaARCCFCodeAuditedLoc = SourceLocation();
1745 }
1746
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001747 // Complain about attempts to #include files in an assume-nonnull pragma.
1748 if (PragmaAssumeNonNullLoc.isValid()) {
1749 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1750 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1751
1752 // Immediately leave the pragma.
1753 PragmaAssumeNonNullLoc = SourceLocation();
1754 }
1755
Aaron Ballman611306e2012-03-02 22:51:54 +00001756 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001757 // Map the filename with the brackets still attached. If the name doesn't
1758 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001759 // spelling for.
1760 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1761 if (!NewName.empty())
1762 Filename = NewName;
1763 }
1764
Chris Lattnerf64b3522008-03-09 01:54:53 +00001765 // Search include directories.
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001766 bool IsMapped = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001767 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001768 SmallString<1024> SearchPath;
1769 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001770 // We get the raw path only if we have 'Callbacks' to which we later pass
1771 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001772 ModuleMap::KnownHeader SuggestedModule;
1773 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001774 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001775 if (LangOpts.MSVCCompat) {
1776 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001777#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001778 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001779#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001780 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001781 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001782 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001783 isAngled, LookupFrom, LookupFromFile, CurDir,
1784 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001785 &SuggestedModule, &IsMapped);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001786
Richard Smithdbbc5232015-05-14 02:25:44 +00001787 if (!File) {
1788 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001789 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001790 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001791 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1792 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1793 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001794 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001795 HeaderInfo.AddSearchPath(DL, isAngled);
Taewook Oh755e4d22016-06-13 21:55:33 +00001796
Douglas Gregor11729f02011-11-30 18:12:06 +00001797 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001798 File = LookupFile(
1799 FilenameLoc,
1800 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1801 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001802 &SuggestedModule, &IsMapped, /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001803 }
1804 }
1805 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001806
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001807 if (!SuppressIncludeNotFoundError) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001808 // If the file could not be located and it was included via angle
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001809 // brackets, we can attempt a lookup as though it were a quoted path to
1810 // provide the user with a possible fixit.
1811 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001812 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001813 FilenameLoc,
1814 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1815 LookupFrom, LookupFromFile, CurDir,
1816 Callbacks ? &SearchPath : nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001817 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001818 if (File) {
1819 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001820 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1821 Filename <<
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001822 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1823 }
1824 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001825
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001826 // If the file is still not found, just go with the vanilla diagnostic
1827 if (!File)
Erik Verbruggen45449542016-10-25 10:13:10 +00001828 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename
1829 << FilenameRange;
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001830 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001831 }
1832
Richard Smith63b6fce2015-05-18 04:45:41 +00001833 // Should we enter the source file? Set to false if either the source file is
1834 // known to have no effect beyond its effect on module visibility -- that is,
1835 // if it's got an include guard that is already defined or is a modular header
1836 // we've imported or already built.
1837 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001838
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001839 if (PPOpts->SingleFileParseMode)
1840 ShouldEnter = false;
1841
Richard Smith63b6fce2015-05-18 04:45:41 +00001842 // Determine whether we should try to import the module for this #include, if
1843 // there is one. Don't do so if precompiled module support is disabled or we
1844 // are processing this module textually (because we're building the module).
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001845 if (ShouldEnter && File && SuggestedModule && getLangOpts().Modules &&
Richard Smith63b6fce2015-05-18 04:45:41 +00001846 SuggestedModule.getModule()->getTopLevelModuleName() !=
Richard Smith7e82e012016-02-19 22:25:36 +00001847 getLangOpts().CurrentModule) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001848 // If this include corresponds to a module but that module is
1849 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001850 // FIXME: Remove this; loadModule does the same check (but produces
1851 // slightly worse diagnostics).
Richard Smith27e5aa02017-06-05 18:57:56 +00001852 if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
1853 SuggestedModule.getModule())) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001854 Diag(FilenameTok.getLocation(),
1855 diag::note_implicit_top_level_module_import_here)
Richard Smith27e5aa02017-06-05 18:57:56 +00001856 << SuggestedModule.getModule()->getTopLevelModuleName();
Sean Silva8b7c0392015-08-17 16:39:30 +00001857 return;
1858 }
1859
Douglas Gregor71944202011-11-30 00:36:36 +00001860 // Compute the module access path corresponding to this module.
1861 // FIXME: Should we have a second loadModule() overload to avoid this
1862 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001863 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001864 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001865 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1866 FilenameTok.getLocation()));
1867 std::reverse(Path.begin(), Path.end());
1868
Douglas Gregor41e115a2011-11-30 18:02:36 +00001869 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001870 // We only do this in Objective-C, where we have a module-import syntax.
1871 if (getLangOpts().ObjC2)
1872 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001873
Richard Smith10434f32015-05-02 02:08:26 +00001874 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001875 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001876 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1877 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001878 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1879 IncludeTok.getLocation(), Path, Module::Hidden,
1880 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001881 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001882 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001883
Richard Smith63b6fce2015-05-18 04:45:41 +00001884 if (Imported)
1885 ShouldEnter = false;
1886 else if (Imported.isMissingExpected()) {
1887 // We failed to find a submodule that we assumed would exist (because it
1888 // was in the directory of an umbrella header, for instance), but no
Richard Smitha114c462016-12-06 00:40:17 +00001889 // actual module containing it exists (because the umbrella header is
Richard Smith63b6fce2015-05-18 04:45:41 +00001890 // incomplete). Treat this as a textual inclusion.
1891 SuggestedModule = ModuleMap::KnownHeader();
Richard Smitha114c462016-12-06 00:40:17 +00001892 } else if (Imported.isConfigMismatch()) {
1893 // On a configuration mismatch, enter the header textually. We still know
1894 // that it's part of the corresponding module.
Richard Smith63b6fce2015-05-18 04:45:41 +00001895 } else {
1896 // We hit an error processing the import. Bail out.
1897 if (hadModuleLoaderFatalFailure()) {
1898 // With a fatal failure in the module loader, we abort parsing.
1899 Token &Result = IncludeTok;
1900 if (CurLexer) {
1901 Result.startToken();
1902 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1903 CurLexer->cutOffLexing();
1904 } else {
1905 assert(CurPTHLexer && "#include but no current lexer set!");
1906 CurPTHLexer->getEOF(Result);
1907 }
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001908 }
1909 return;
1910 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001911 }
1912
Richard Smithc5247e62017-05-30 02:03:19 +00001913 // The #included file will be considered to be a system header if either it is
1914 // in a system include directory, or if the #includer is a system include
1915 // header.
1916 SrcMgr::CharacteristicKind FileCharacter =
1917 SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
1918 if (File)
1919 FileCharacter = std::max(HeaderInfo.getFileDirFlavor(File), FileCharacter);
1920
1921 // Ask HeaderInfo if we should enter this #include file. If not, #including
1922 // this file will have no effect.
1923 bool SkipHeader = false;
1924 if (ShouldEnter && File &&
1925 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
1926 getLangOpts().Modules,
1927 SuggestedModule.getModule())) {
1928 ShouldEnter = false;
1929 SkipHeader = true;
1930 }
1931
Richard Smith63b6fce2015-05-18 04:45:41 +00001932 if (Callbacks) {
1933 // Notify the callback object that we've seen an inclusion directive.
1934 Callbacks->InclusionDirective(
1935 HashLoc, IncludeTok,
1936 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1937 FilenameRange, File, SearchPath, RelativePath,
1938 ShouldEnter ? nullptr : SuggestedModule.getModule());
Richard Smithc5247e62017-05-30 02:03:19 +00001939 if (SkipHeader && !SuggestedModule.getModule())
1940 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Douglas Gregor97eec242011-09-15 22:00:41 +00001941 }
Richard Smith63b6fce2015-05-18 04:45:41 +00001942
1943 if (!File)
1944 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001945
Richard Smith54ef4c32015-05-19 19:58:11 +00001946 // FIXME: If we have a suggested module, and we've already visited this file,
1947 // don't bother entering it again. We know it has no further effect.
1948
Taewook Ohf42103c2016-06-13 20:40:21 +00001949 // Issue a diagnostic if the name of the file on disk has a different case
1950 // than the one we're about to open.
1951 const bool CheckIncludePathPortability =
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001952 !IsMapped && File && !File->tryGetRealPathName().empty();
Taewook Ohf42103c2016-06-13 20:40:21 +00001953
1954 if (CheckIncludePathPortability) {
1955 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
1956 StringRef RealPathName = File->tryGetRealPathName();
1957 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
1958 llvm::sys::path::end(Name));
1959
1960 if (trySimplifyPath(Components, RealPathName)) {
1961 SmallString<128> Path;
1962 Path.reserve(Name.size()+2);
1963 Path.push_back(isAngled ? '<' : '"');
Taewook Ohcc89bac2017-02-21 22:30:55 +00001964 bool isLeadingSeparator = llvm::sys::path::is_absolute(Name);
Taewook Ohf42103c2016-06-13 20:40:21 +00001965 for (auto Component : Components) {
Taewook Ohcc89bac2017-02-21 22:30:55 +00001966 if (isLeadingSeparator)
1967 isLeadingSeparator = false;
1968 else
1969 Path.append(Component);
Taewook Ohf42103c2016-06-13 20:40:21 +00001970 // Append the separator the user used, or the close quote
1971 Path.push_back(
1972 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
1973 (isAngled ? '>' : '"'));
1974 }
Taewook Ohf42103c2016-06-13 20:40:21 +00001975 // For user files and known standard headers, by default we issue a diagnostic.
1976 // For other system headers, we don't. They can be controlled separately.
1977 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
1978 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
1979 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Reid Kleckner273895b2017-02-14 18:38:40 +00001980 Diag(FilenameTok, DiagId) << Path <<
1981 FixItHint::CreateReplacement(Range, Path);
Taewook Ohf42103c2016-06-13 20:40:21 +00001982 }
1983 }
1984
Richard Smith63b6fce2015-05-18 04:45:41 +00001985 // If we don't need to enter the file, stop now.
1986 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001987 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00001988 if (auto *M = SuggestedModule.getModule()) {
Manman Renffd3e9d2017-01-09 19:20:18 +00001989 // When building a pch, -fmodule-name tells the compiler to textually
1990 // include headers in the specified module. But it is possible that
1991 // ShouldEnter is false because we are skipping the header. In that
1992 // case, We are not importing the specified module.
1993 if (SkipHeader && getLangOpts().CompilingPCH &&
1994 M->getTopLevelModuleName() == getLangOpts().CurrentModule)
1995 return;
1996
Richard Smitha0aafa32015-05-18 03:52:30 +00001997 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00001998
1999 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
2000 tok::pp___include_macros)
Richard Smithc51c38b2017-04-29 00:34:47 +00002001 EnterAnnotationToken(SourceRange(HashLoc, End),
2002 tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00002003 }
Chris Lattner72286d62010-04-19 20:44:31 +00002004 return;
2005 }
2006
Chris Lattnerf64b3522008-03-09 01:54:53 +00002007 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002008 SourceLocation IncludePos = End;
2009 // If the filename string was the result of macro expansions, set the include
2010 // position on the file where it will be included and after the expansions.
2011 if (IncludePos.isMacroID())
2012 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
2013 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002014 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002015
Richard Smith34f30512013-11-23 04:06:09 +00002016 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002017 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
2018 return;
Richard Smith34f30512013-11-23 04:06:09 +00002019
Richard Smitha0aafa32015-05-18 03:52:30 +00002020 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002021 if (auto *M = SuggestedModule.getModule()) {
Manman Renffd3e9d2017-01-09 19:20:18 +00002022 // When building a pch, -fmodule-name tells the compiler to textually
2023 // include headers in the specified module. We are not building the
2024 // specified module.
2025 if (getLangOpts().CompilingPCH &&
2026 M->getTopLevelModuleName() == getLangOpts().CurrentModule)
2027 return;
2028
Richard Smithd1386302017-05-04 00:29:54 +00002029 assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2030 CurLexerSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002031
Richard Smitha0aafa32015-05-18 03:52:30 +00002032 // Let the macro handling code know that any future macros are within
2033 // the new submodule.
Richard Smithd1386302017-05-04 00:29:54 +00002034 EnterSubmodule(M, HashLoc, /*ForPragma*/false);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002035
Richard Smitha0aafa32015-05-18 03:52:30 +00002036 // Let the parser know that any future declarations are within the new
2037 // submodule.
2038 // FIXME: There's no point doing this if we're handling a #__include_macros
2039 // directive.
Richard Smithc51c38b2017-04-29 00:34:47 +00002040 EnterAnnotationToken(SourceRange(HashLoc, End), tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00002041 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002042}
2043
James Dennettf6333ac2012-06-22 05:46:07 +00002044/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002045///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002046void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2047 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002048 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002049
Chris Lattnerf64b3522008-03-09 01:54:53 +00002050 // #include_next is like #include, except that we start searching after
2051 // the current found directory. If we can't do this, issue a
2052 // diagnostic.
2053 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002054 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00002055 if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2056 // If the main file is a header, then it's either for PCH/AST generation,
2057 // or libclang opened it. Either way, handle it as a normal include below
2058 // and do not complain about include_next.
2059 } else if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002060 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002061 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smithd1386302017-05-04 00:29:54 +00002062 } else if (CurLexerSubmodule) {
Richard Smith25d50752014-10-20 00:15:49 +00002063 // Start looking up in the directory *after* the one in which the current
2064 // file would be found, if any.
2065 assert(CurPPLexer && "#include_next directive in macro?");
2066 LookupFromFile = CurPPLexer->getFileEntry();
2067 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002068 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002069 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2070 } else {
2071 // Start looking up in the next directory.
2072 ++Lookup;
2073 }
Mike Stump11289f42009-09-09 15:08:12 +00002074
Richard Smith25d50752014-10-20 00:15:49 +00002075 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2076 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002077}
2078
James Dennettf6333ac2012-06-22 05:46:07 +00002079/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002080void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2081 // The Microsoft #import directive takes a type library and generates header
2082 // files from it, and includes those. This is beyond the scope of what clang
2083 // does, so we ignore it and error out. However, #import can optionally have
2084 // trailing attributes that span multiple lines. We're going to eat those
2085 // so we can continue processing from there.
2086 Diag(Tok, diag::err_pp_import_directive_ms );
2087
Taewook Oh755e4d22016-06-13 21:55:33 +00002088 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002089 // directive can be split over multiple lines using the backslash character.
2090 DiscardUntilEndOfDirective();
2091}
2092
James Dennettf6333ac2012-06-22 05:46:07 +00002093/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002094///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002095void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2096 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00002097 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002098 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002099 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002100 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002101 }
Richard Smith25d50752014-10-20 00:15:49 +00002102 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002103}
2104
Chris Lattner58a1eb02009-04-08 18:46:40 +00002105/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2106/// pseudo directive in the predefines buffer. This handles it by sucking all
2107/// tokens through the preprocessor and discarding them (only keeping the side
2108/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002109void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2110 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002111 // This directive should only occur in the predefines buffer. If not, emit an
2112 // error and reject it.
2113 SourceLocation Loc = IncludeMacrosTok.getLocation();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002114 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002115 Diag(IncludeMacrosTok.getLocation(),
2116 diag::pp_include_macros_out_of_predefines);
2117 DiscardUntilEndOfDirective();
2118 return;
2119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120
Chris Lattnere01d82b2009-04-08 20:53:24 +00002121 // Treat this as a normal #include for checking purposes. If this is
2122 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002123 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002124
Chris Lattnere01d82b2009-04-08 20:53:24 +00002125 Token TmpTok;
2126 do {
2127 Lex(TmpTok);
2128 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2129 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002130}
2131
Chris Lattnerf64b3522008-03-09 01:54:53 +00002132//===----------------------------------------------------------------------===//
2133// Preprocessor Macro Directive Handling.
2134//===----------------------------------------------------------------------===//
2135
Faisal Valiac506d72017-07-17 17:18:43 +00002136/// ReadMacroParameterList - The ( starting an argument list of a macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00002137/// definition has just been read. Lex the rest of the arguments and the
2138/// closing ), updating MI with what we learn. Return true if an error occurs
2139/// parsing the arg list.
Faisal Valiac506d72017-07-17 17:18:43 +00002140bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002141 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00002142
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002143 while (true) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002144 LexUnexpandedToken(Tok);
2145 switch (Tok.getKind()) {
2146 case tok::r_paren:
2147 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00002148 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002149 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002150 // Otherwise we have #define FOO(A,)
2151 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2152 return true;
2153 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002154 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002155 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002156 diag::warn_cxx98_compat_variadic_macro :
2157 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002158
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002159 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2160 if (LangOpts.OpenCL) {
2161 Diag(Tok, diag::err_pp_opencl_variadic_macros);
2162 return true;
2163 }
2164
Chris Lattnerf64b3522008-03-09 01:54:53 +00002165 // Lex the token after the identifier.
2166 LexUnexpandedToken(Tok);
2167 if (Tok.isNot(tok::r_paren)) {
2168 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2169 return true;
2170 }
2171 // Add the __VA_ARGS__ identifier as an argument.
2172 Arguments.push_back(Ident__VA_ARGS__);
2173 MI->setIsC99Varargs();
Faisal Valiac506d72017-07-17 17:18:43 +00002174 MI->setParameterList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002175 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002176 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002177 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2178 return true;
2179 default:
2180 // Handle keywords and identifiers here to accept things like
2181 // #define Foo(for) for.
2182 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002183 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002184 // #define X(1
2185 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2186 return true;
2187 }
2188
2189 // If this is already used as an argument, it is used multiple times (e.g.
2190 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00002191 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00002192 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002193 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002194 return true;
2195 }
Mike Stump11289f42009-09-09 15:08:12 +00002196
Chris Lattnerf64b3522008-03-09 01:54:53 +00002197 // Add the argument to the macro info.
2198 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chris Lattnerf64b3522008-03-09 01:54:53 +00002200 // Lex the token after the identifier.
2201 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002202
Chris Lattnerf64b3522008-03-09 01:54:53 +00002203 switch (Tok.getKind()) {
2204 default: // #define X(A B
2205 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2206 return true;
2207 case tok::r_paren: // #define X(A)
Faisal Valiac506d72017-07-17 17:18:43 +00002208 MI->setParameterList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002209 return false;
2210 case tok::comma: // #define X(A,
2211 break;
2212 case tok::ellipsis: // #define X(A... -> GCC extension
2213 // Diagnose extension.
2214 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002215
Chris Lattnerf64b3522008-03-09 01:54:53 +00002216 // Lex the token after the identifier.
2217 LexUnexpandedToken(Tok);
2218 if (Tok.isNot(tok::r_paren)) {
2219 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2220 return true;
2221 }
Mike Stump11289f42009-09-09 15:08:12 +00002222
Chris Lattnerf64b3522008-03-09 01:54:53 +00002223 MI->setIsGNUVarargs();
Faisal Valiac506d72017-07-17 17:18:43 +00002224 MI->setParameterList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002225 return false;
2226 }
2227 }
2228 }
2229}
2230
Serge Pavlov07c0f042014-12-18 11:14:21 +00002231static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2232 const LangOptions &LOptions) {
2233 if (MI->getNumTokens() == 1) {
2234 const Token &Value = MI->getReplacementToken(0);
2235
2236 // Macro that is identity, like '#define inline inline' is a valid pattern.
2237 if (MacroName.getKind() == Value.getKind())
2238 return true;
2239
2240 // Macro that maps a keyword to the same keyword decorated with leading/
2241 // trailing underscores is a valid pattern:
2242 // #define inline __inline
2243 // #define inline __inline__
2244 // #define inline _inline (in MS compatibility mode)
2245 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2246 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2247 if (!II->isKeyword(LOptions))
2248 return false;
2249 StringRef ValueText = II->getName();
2250 StringRef TrimmedValue = ValueText;
2251 if (!ValueText.startswith("__")) {
2252 if (ValueText.startswith("_"))
2253 TrimmedValue = TrimmedValue.drop_front(1);
2254 else
2255 return false;
2256 } else {
2257 TrimmedValue = TrimmedValue.drop_front(2);
2258 if (TrimmedValue.endswith("__"))
2259 TrimmedValue = TrimmedValue.drop_back(2);
2260 }
2261 return TrimmedValue.equals(MacroText);
2262 } else {
2263 return false;
2264 }
2265 }
2266
2267 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002268 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2269 tok::kw_const) &&
2270 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002271}
2272
Faisal Valiac506d72017-07-17 17:18:43 +00002273// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2274// entire line) of the macro's tokens and adds them to MacroInfo, and while
2275// doing so performs certain validity checks including (but not limited to):
2276// - # (stringization) is followed by a macro parameter
2277//
2278// Returns a nullptr if an invalid sequence of tokens is encountered or returns
2279// a pointer to a MacroInfo object.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002280
Faisal Valiac506d72017-07-17 17:18:43 +00002281MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2282 const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002283
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002284 Token LastTok = MacroNameTok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002285 // Create the new macro.
Faisal Valiac506d72017-07-17 17:18:43 +00002286 MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002287
Chris Lattnerf64b3522008-03-09 01:54:53 +00002288 Token Tok;
2289 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002290
Faisal Vali6bf67912017-07-25 03:15:36 +00002291 // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2292 // within their appropriate context.
2293 VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2294
Chris Lattnerf64b3522008-03-09 01:54:53 +00002295 // If this is a function-like macro definition, parse the argument list,
2296 // marking each of the identifiers as being used as macro arguments. Also,
2297 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002298 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002299 if (ImmediatelyAfterHeaderGuard) {
2300 // Save this macro information since it may part of a header guard.
2301 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2302 MacroNameTok.getLocation());
2303 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002304 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002305 } else if (Tok.hasLeadingSpace()) {
2306 // This is a normal token with leading space. Clear the leading space
2307 // marker on the first token to get proper expansion.
2308 Tok.clearFlag(Token::LeadingSpace);
2309 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002310 // This is a function-like macro definition. Read the argument list.
2311 MI->setIsFunctionLike();
Faisal Valiac506d72017-07-17 17:18:43 +00002312 if (ReadMacroParameterList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002313 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002314 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002315 DiscardUntilEndOfDirective();
Faisal Valiac506d72017-07-17 17:18:43 +00002316 return nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002317 }
2318
Faisal Vali6bf67912017-07-25 03:15:36 +00002319 // If this is a definition of an ISO C/C++ variadic function-like macro (not
2320 // using the GNU named varargs extension) inform our variadic scope guard
2321 // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2322 // allowed only within the definition of a variadic macro.
Mike Stump11289f42009-09-09 15:08:12 +00002323
Faisal Vali6bf67912017-07-25 03:15:36 +00002324 if (MI->isC99Varargs()) {
2325 VariadicMacroScopeGuard.enterScope();
2326 }
Mike Stump11289f42009-09-09 15:08:12 +00002327
Chris Lattnerf64b3522008-03-09 01:54:53 +00002328 // Read the first token after the arg list for down below.
2329 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002330 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002331 // C99 requires whitespace between the macro definition and the body. Emit
2332 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002333 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002334 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002335 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2336 // first character of a replacement list is not a character required by
2337 // subclause 5.2.1, then there shall be white-space separation between the
2338 // identifier and the replacement list.". 5.2.1 lists this set:
2339 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2340 // is irrelevant here.
2341 bool isInvalid = false;
2342 if (Tok.is(tok::at)) // @ is not in the list above.
2343 isInvalid = true;
2344 else if (Tok.is(tok::unknown)) {
2345 // If we have an unknown token, it is something strange like "`". Since
2346 // all of valid characters would have lexed into a single character
2347 // token of some sort, we know this is not a valid case.
2348 isInvalid = true;
2349 }
2350 if (isInvalid)
2351 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2352 else
2353 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002354 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002355
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002356 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002357 LastTok = Tok;
2358
Chris Lattnerf64b3522008-03-09 01:54:53 +00002359 // Read the rest of the macro body.
2360 if (MI->isObjectLike()) {
2361 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002362 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002363 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002364 MI->AddTokenToBody(Tok);
2365 // Get the next token of the macro.
2366 LexUnexpandedToken(Tok);
2367 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002368 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002369 // Otherwise, read the body of a function-like macro. While we are at it,
2370 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2371 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002372 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002373 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002374
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002375 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002376 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002377
Chris Lattnerf64b3522008-03-09 01:54:53 +00002378 // Get the next token of the macro.
2379 LexUnexpandedToken(Tok);
2380 continue;
2381 }
Mike Stump11289f42009-09-09 15:08:12 +00002382
Richard Smith701a3522013-07-09 01:00:29 +00002383 // If we're in -traditional mode, then we should ignore stringification
2384 // and token pasting. Mark the tokens as unknown so as not to confuse
2385 // things.
2386 if (getLangOpts().TraditionalCPP) {
2387 Tok.setKind(tok::unknown);
2388 MI->AddTokenToBody(Tok);
2389
2390 // Get the next token of the macro.
2391 LexUnexpandedToken(Tok);
2392 continue;
2393 }
2394
Eli Friedman14d3c792012-11-14 02:18:46 +00002395 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002396 // If we see token pasting, check if it looks like the gcc comma
2397 // pasting extension. We'll use this information to suppress
2398 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002399
Eli Friedman14d3c792012-11-14 02:18:46 +00002400 // Get the next token of the macro.
2401 LexUnexpandedToken(Tok);
2402
2403 if (Tok.is(tok::eod)) {
2404 MI->AddTokenToBody(LastTok);
2405 break;
2406 }
2407
2408 unsigned NumTokens = MI->getNumTokens();
2409 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2410 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2411 MI->setHasCommaPasting();
2412
David Majnemer76faf1f2013-11-05 09:30:17 +00002413 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002414 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002415 continue;
2416 }
2417
Chris Lattnerf64b3522008-03-09 01:54:53 +00002418 // Get the next token of the macro.
2419 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002420
Chris Lattner83bd8282009-05-25 17:16:10 +00002421 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002422 if (Tok.getIdentifierInfo() == nullptr ||
Faisal Valiac506d72017-07-17 17:18:43 +00002423 MI->getParameterNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002424
2425 // If this is assembler-with-cpp mode, we accept random gibberish after
2426 // the '#' because '#' is often a comment character. However, change
2427 // the kind of the token to tok::unknown so that the preprocessor isn't
2428 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002429 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002430 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002431 MI->AddTokenToBody(LastTok);
2432 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002433 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002434 Diag(Tok, diag::err_pp_stringize_not_parameter)
2435 << LastTok.is(tok::hashat);
Faisal Valiac506d72017-07-17 17:18:43 +00002436 return nullptr;
Chris Lattner83bd8282009-05-25 17:16:10 +00002437 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002438 }
Mike Stump11289f42009-09-09 15:08:12 +00002439
Chris Lattner83bd8282009-05-25 17:16:10 +00002440 // Things look ok, add the '#' and param name tokens to the macro.
2441 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002442 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002443 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002444
Chris Lattnerf64b3522008-03-09 01:54:53 +00002445 // Get the next token of the macro.
2446 LexUnexpandedToken(Tok);
2447 }
2448 }
Faisal Valiac506d72017-07-17 17:18:43 +00002449 MI->setDefinitionEndLoc(LastTok.getLocation());
Faisal Valiac506d72017-07-17 17:18:43 +00002450 return MI;
2451}
2452/// HandleDefineDirective - Implements \#define. This consumes the entire macro
2453/// line then lets the caller lex the next real token.
2454void Preprocessor::HandleDefineDirective(
2455 Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2456 ++NumDefined;
2457
2458 Token MacroNameTok;
2459 bool MacroShadowsKeyword;
2460 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2461
2462 // Error reading macro name? If so, diagnostic already issued.
2463 if (MacroNameTok.is(tok::eod))
2464 return;
2465
2466 // If we are supposed to keep comments in #defines, reenable comment saving
2467 // mode.
2468 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2469
2470 MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2471 MacroNameTok, ImmediatelyAfterHeaderGuard);
2472
2473 if (!MI) return;
Mike Stump11289f42009-09-09 15:08:12 +00002474
Serge Pavlov07c0f042014-12-18 11:14:21 +00002475 if (MacroShadowsKeyword &&
2476 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2477 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
Faisal Valiac506d72017-07-17 17:18:43 +00002478 }
Chris Lattner57540c52011-04-15 05:22:18 +00002479 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002480 // replacement list.
2481 unsigned NumTokens = MI->getNumTokens();
2482 if (NumTokens != 0) {
2483 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2484 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002485 return;
2486 }
2487 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2488 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002489 return;
2490 }
2491 }
Mike Stump11289f42009-09-09 15:08:12 +00002492
Faisal Valiac506d72017-07-17 17:18:43 +00002493
Mike Stump11289f42009-09-09 15:08:12 +00002494
Chris Lattnerf64b3522008-03-09 01:54:53 +00002495 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002496 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002497 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002498 // In Objective-C, ignore attempts to directly redefine the builtin
2499 // definitions of the ownership qualifiers. It's still possible to
2500 // #undef them.
2501 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2502 return II->isStr("__strong") ||
2503 II->isStr("__weak") ||
2504 II->isStr("__unsafe_unretained") ||
2505 II->isStr("__autoreleasing");
2506 };
2507 if (getLangOpts().ObjC1 &&
2508 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2509 == getPredefinesFileID() &&
2510 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2511 // Warn if it changes the tokens.
2512 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2513 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2514 !MI->isIdenticalTo(*OtherMI, *this,
2515 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2516 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2517 }
2518 assert(!OtherMI->isWarnIfUnused());
2519 return;
2520 }
2521
Chris Lattner5244f342009-01-16 19:50:11 +00002522 // It is very common for system headers to have tons of macro redefinitions
2523 // and for warnings to be disabled in system headers. If this is the case,
2524 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002525 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002526 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002527 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002528 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002529
Taewook Oh755e4d22016-06-13 21:55:33 +00002530 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002531 // C++ [cpp.predefined]p4, but allow it as an extension.
2532 if (OtherMI->isBuiltinMacro())
2533 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002534 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002535 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002536 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002537 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002538 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2539 << MacroNameTok.getIdentifierInfo();
2540 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2541 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002542 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002543 if (OtherMI->isWarnIfUnused())
2544 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002545 }
Mike Stump11289f42009-09-09 15:08:12 +00002546
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002547 DefMacroDirective *MD =
2548 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002549
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002550 assert(!MI->isUsed());
2551 // If we need warning for not using the macro, add its location in the
2552 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002553 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002554 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002555 MI->setIsWarnIfUnused(true);
2556 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2557 }
2558
Chris Lattner928e9092009-04-12 01:39:54 +00002559 // If the callbacks want to know, tell them about the macro definition.
2560 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002561 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002562}
2563
James Dennettf6333ac2012-06-22 05:46:07 +00002564/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002565///
Erik Verbruggen4bddef92016-10-26 08:52:41 +00002566void Preprocessor::HandleUndefDirective() {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002567 ++NumUndefined;
2568
2569 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002570 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002571
Chris Lattnerf64b3522008-03-09 01:54:53 +00002572 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002573 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002574 return;
Mike Stump11289f42009-09-09 15:08:12 +00002575
Chris Lattnerf64b3522008-03-09 01:54:53 +00002576 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002577 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002578
Richard Smith20e883e2015-04-29 23:20:19 +00002579 // Okay, we have a valid identifier to undef.
2580 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002581 auto MD = getMacroDefinition(II);
Vedant Kumar349a6242017-04-26 21:05:44 +00002582 UndefMacroDirective *Undef = nullptr;
2583
2584 // If the macro is not defined, this is a noop undef.
2585 if (const MacroInfo *MI = MD.getMacroInfo()) {
2586 if (!MI->isUsed() && MI->isWarnIfUnused())
2587 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2588
2589 if (MI->isWarnIfUnused())
2590 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2591
2592 Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
2593 }
Mike Stump11289f42009-09-09 15:08:12 +00002594
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002595 // If the callbacks want to know, tell them about the macro #undef.
2596 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002597 if (Callbacks)
Vedant Kumar349a6242017-04-26 21:05:44 +00002598 Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002599
Vedant Kumar349a6242017-04-26 21:05:44 +00002600 if (Undef)
2601 appendMacroDirective(II, Undef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002602}
2603
Chris Lattnerf64b3522008-03-09 01:54:53 +00002604//===----------------------------------------------------------------------===//
2605// Preprocessor Conditional Directive Handling.
2606//===----------------------------------------------------------------------===//
2607
James Dennettf6333ac2012-06-22 05:46:07 +00002608/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2609/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2610/// true if any tokens have been returned or pp-directives activated before this
2611/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002612///
Vedant Kumar3919a502017-09-11 20:47:42 +00002613void Preprocessor::HandleIfdefDirective(Token &Result,
2614 const Token &HashToken,
2615 bool isIfndef,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002616 bool ReadAnyTokensBeforeDirective) {
2617 ++NumIf;
2618 Token DirectiveTok = Result;
2619
2620 Token MacroNameTok;
2621 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002622
Chris Lattnerf64b3522008-03-09 01:54:53 +00002623 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002624 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002625 // Skip code until we get to #endif. This helps with recovery by not
2626 // emitting an error when the #endif is reached.
Vedant Kumar3919a502017-09-11 20:47:42 +00002627 SkipExcludedConditionalBlock(HashToken, DirectiveTok.getLocation(),
2628 /*Foundnonskip*/ false, /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002629 return;
2630 }
Mike Stump11289f42009-09-09 15:08:12 +00002631
Chris Lattnerf64b3522008-03-09 01:54:53 +00002632 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002633 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002634
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002635 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002636 auto MD = getMacroDefinition(MII);
2637 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002638
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002639 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002640 // If the start of a top-level #ifdef and if the macro is not defined,
2641 // inform MIOpt that this might be the start of a proper include guard.
2642 // Otherwise it is some other form of unknown conditional which we can't
2643 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002644 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002645 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002646 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002647 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002648 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002649 }
2650
Chris Lattnerf64b3522008-03-09 01:54:53 +00002651 // If there is a macro, process it.
2652 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002653 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002654
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002655 if (Callbacks) {
2656 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002657 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002658 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002659 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002660 }
2661
Chris Lattnerf64b3522008-03-09 01:54:53 +00002662 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002663 if (PPOpts->SingleFileParseMode && !MI) {
2664 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2665 // the directive blocks.
2666 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002667 /*wasskip*/false, /*foundnonskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002668 /*foundelse*/false);
2669 } else if (!MI == isIfndef) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002670 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002671 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2672 /*wasskip*/false, /*foundnonskip*/true,
2673 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002674 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002675 // No, skip the contents of this block.
Vedant Kumar3919a502017-09-11 20:47:42 +00002676 SkipExcludedConditionalBlock(HashToken, DirectiveTok.getLocation(),
2677 /*Foundnonskip*/ false,
2678 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002679 }
2680}
2681
James Dennettf6333ac2012-06-22 05:46:07 +00002682/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002683///
2684void Preprocessor::HandleIfDirective(Token &IfToken,
Vedant Kumar3919a502017-09-11 20:47:42 +00002685 const Token &HashToken,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002686 bool ReadAnyTokensBeforeDirective) {
2687 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002688
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002689 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002690 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002691 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002692 const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
2693 const bool ConditionalTrue = DER.Conditional;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002694 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002695
2696 // If this condition is equivalent to #ifndef X, and if this is the first
2697 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002698 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002699 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002700 // FIXME: Pass in the location of the macro name, not the 'if' token.
2701 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002702 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002703 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002704 }
2705
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002706 if (Callbacks)
2707 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002708 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002709 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002710
Chris Lattnerf64b3522008-03-09 01:54:53 +00002711 // Should we include the stuff contained by this directive?
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002712 if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
2713 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2714 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002715 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002716 /*foundnonskip*/false, /*foundelse*/false);
2717 } else if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002718 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002719 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002720 /*foundnonskip*/true, /*foundelse*/false);
2721 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002722 // No, skip the contents of this block.
Vedant Kumar3919a502017-09-11 20:47:42 +00002723 SkipExcludedConditionalBlock(HashToken, IfToken.getLocation(),
2724 /*Foundnonskip*/ false,
2725 /*FoundElse*/ false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002726 }
2727}
2728
James Dennettf6333ac2012-06-22 05:46:07 +00002729/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002730///
2731void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2732 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002733
Chris Lattnerf64b3522008-03-09 01:54:53 +00002734 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002735 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002736
Chris Lattnerf64b3522008-03-09 01:54:53 +00002737 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002738 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002739 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002740 Diag(EndifToken, diag::err_pp_endif_without_if);
2741 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002742 }
Mike Stump11289f42009-09-09 15:08:12 +00002743
Chris Lattnerf64b3522008-03-09 01:54:53 +00002744 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002745 if (CurPPLexer->getConditionalStackDepth() == 0)
2746 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002747
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002748 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002749 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002750
2751 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002752 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002753}
2754
James Dennettf6333ac2012-06-22 05:46:07 +00002755/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002756///
Vedant Kumar3919a502017-09-11 20:47:42 +00002757void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002758 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002759
Chris Lattnerf64b3522008-03-09 01:54:53 +00002760 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002761 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002762
Chris Lattnerf64b3522008-03-09 01:54:53 +00002763 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002764 if (CurPPLexer->popConditionalLevel(CI)) {
2765 Diag(Result, diag::pp_err_else_without_if);
2766 return;
2767 }
Mike Stump11289f42009-09-09 15:08:12 +00002768
Chris Lattnerf64b3522008-03-09 01:54:53 +00002769 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002770 if (CurPPLexer->getConditionalStackDepth() == 0)
2771 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002772
2773 // If this is a #else with a #else before it, report the error.
2774 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002775
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002776 if (Callbacks)
2777 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2778
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002779 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002780 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2781 // the directive blocks.
2782 CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002783 /*foundnonskip*/false, /*foundelse*/true);
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002784 return;
2785 }
2786
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002787 // Finally, skip the rest of the contents of this block.
Vedant Kumar3919a502017-09-11 20:47:42 +00002788 SkipExcludedConditionalBlock(HashToken, CI.IfLoc, /*Foundnonskip*/ true,
2789 /*FoundElse*/ true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002790}
2791
James Dennettf6333ac2012-06-22 05:46:07 +00002792/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002793///
Vedant Kumar3919a502017-09-11 20:47:42 +00002794void Preprocessor::HandleElifDirective(Token &ElifToken,
2795 const Token &HashToken) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002796 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002797
Chris Lattnerf64b3522008-03-09 01:54:53 +00002798 // #elif directive in a non-skipping conditional... start skipping.
2799 // We don't care what the condition is, because we will always skip it (since
2800 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002801 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002802 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002803 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002804
2805 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002806 if (CurPPLexer->popConditionalLevel(CI)) {
2807 Diag(ElifToken, diag::pp_err_elif_without_if);
2808 return;
2809 }
Mike Stump11289f42009-09-09 15:08:12 +00002810
Chris Lattnerf64b3522008-03-09 01:54:53 +00002811 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002812 if (CurPPLexer->getConditionalStackDepth() == 0)
2813 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002814
Chris Lattnerf64b3522008-03-09 01:54:53 +00002815 // If this is a #elif with a #else before it, report the error.
2816 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Taewook Oh755e4d22016-06-13 21:55:33 +00002817
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002818 if (Callbacks)
2819 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002820 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002821 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002822
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002823 if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) {
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002824 // In 'single-file-parse mode' undefined identifiers trigger parsing of all
2825 // the directive blocks.
Argyrios Kyrtzidisd750e1c2017-06-21 18:52:44 +00002826 CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
Argyrios Kyrtzidisad870f82017-06-20 14:36:58 +00002827 /*foundnonskip*/false, /*foundelse*/false);
2828 return;
2829 }
2830
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002831 // Finally, skip the rest of the contents of this block.
Vedant Kumar3919a502017-09-11 20:47:42 +00002832 SkipExcludedConditionalBlock(HashToken, CI.IfLoc, /*Foundnonskip*/ true,
2833 /*FoundElse*/ CI.FoundElse,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002834 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002835}