blob: 3bfbf16ae3bf79928aec913a518e5db6434325c3 [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"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/Lex/PTHLexer.h"
34#include "clang/Lex/Token.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/SmallVector.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000038#include "llvm/ADT/STLExtras.h"
Taewook Ohf42103c2016-06-13 20:40:21 +000039#include "llvm/ADT/StringSwitch.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "llvm/ADT/StringRef.h"
41#include "llvm/Support/AlignOf.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000042#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaf6002232014-08-08 21:31:04 +000043#include "llvm/Support/Path.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000044#include <algorithm>
45#include <cassert>
46#include <cstring>
47#include <new>
48#include <string>
49#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000050
Chris Lattnerf64b3522008-03-09 01:54:53 +000051using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Utility Methods for Preprocessor Directive Handling.
55//===----------------------------------------------------------------------===//
56
Chris Lattnerc0a585d2010-08-17 15:55:45 +000057MacroInfo *Preprocessor::AllocateMacroInfo() {
Richard Smithee0c4c12014-07-24 01:13:23 +000058 MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>();
Ted Kremenekc8456f82010-10-19 22:15:20 +000059 MIChain->Next = MIChainHead;
Ted Kremenekc8456f82010-10-19 22:15:20 +000060 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000061 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000062}
63
64MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
65 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000066 new (MI) MacroInfo(L);
67 return MI;
68}
69
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000070MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
71 unsigned SubModuleID) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +000072 static_assert(alignof(MacroInfo) >= sizeof(SubModuleID),
Chandler Carruth06dde922014-03-02 13:02:01 +000073 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000074 DeserializedMacroInfoChain *MIChain =
75 BP.Allocate<DeserializedMacroInfoChain>();
76 MIChain->Next = DeserialMIChainHead;
77 DeserialMIChainHead = MIChain;
78
79 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000080 new (MI) MacroInfo(L);
81 MI->FromASTFile = true;
82 MI->setOwningModuleID(SubModuleID);
83 return MI;
84}
85
Richard Smith50474bf2015-04-23 23:29:05 +000086DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
87 SourceLocation Loc) {
Richard Smith713369b2015-04-23 20:40:50 +000088 return new (BP) DefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000089}
90
91UndefMacroDirective *
Richard Smith50474bf2015-04-23 23:29:05 +000092Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
Richard Smith713369b2015-04-23 20:40:50 +000093 return new (BP) UndefMacroDirective(UndefLoc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000094}
95
96VisibilityMacroDirective *
97Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
98 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000099 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000100}
101
James Dennettf6333ac2012-06-22 05:46:07 +0000102/// \brief Read and discard all tokens remaining on the current line until
103/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000104void Preprocessor::DiscardUntilEndOfDirective() {
105 Token Tmp;
106 do {
107 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000108 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000109 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000110}
111
Serge Pavlov07c0f042014-12-18 11:14:21 +0000112/// \brief Enumerates possible cases of #define/#undef a reserved identifier.
113enum MacroDiag {
114 MD_NoWarn, //> Not a reserved identifier
115 MD_KeywordDef, //> Macro hides keyword, enabled by default
116 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
117};
118
119/// \brief Checks if the specified identifier is reserved in the specified
120/// language.
121/// This function does not check if the identifier is a keyword.
122static bool isReservedId(StringRef Text, const LangOptions &Lang) {
123 // C++ [macro.names], C11 7.1.3:
124 // All identifiers that begin with an underscore and either an uppercase
125 // letter or another underscore are always reserved for any use.
126 if (Text.size() >= 2 && Text[0] == '_' &&
127 (isUppercase(Text[1]) || Text[1] == '_'))
128 return true;
129 // C++ [global.names]
130 // Each name that contains a double underscore ... is reserved to the
131 // implementation for any use.
132 if (Lang.CPlusPlus) {
133 if (Text.find("__") != StringRef::npos)
134 return true;
135 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000136 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000137}
138
Serge Pavlov07c0f042014-12-18 11:14:21 +0000139static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
140 const LangOptions &Lang = PP.getLangOpts();
141 StringRef Text = II->getName();
142 if (isReservedId(Text, Lang))
143 return MD_ReservedMacro;
144 if (II->isKeyword(Lang))
145 return MD_KeywordDef;
146 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
147 return MD_KeywordDef;
148 return MD_NoWarn;
149}
150
151static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
152 const LangOptions &Lang = PP.getLangOpts();
153 StringRef Text = II->getName();
154 // Do not warn on keyword undef. It is generally harmless and widely used.
155 if (isReservedId(Text, Lang))
156 return MD_ReservedMacro;
157 return MD_NoWarn;
158}
159
Taewook Ohf42103c2016-06-13 20:40:21 +0000160// Return true if we want to issue a diagnostic by default if we
161// encounter this name in a #include with the wrong case. For now,
162// this includes the standard C and C++ headers, Posix headers,
163// and Boost headers. Improper case for these #includes is a
164// potential portability issue.
165static bool warnByDefaultOnWrongCase(StringRef Include) {
166 // If the first component of the path is "boost", treat this like a standard header
167 // for the purposes of diagnostics.
168 if (::llvm::sys::path::begin(Include)->equals_lower("boost"))
169 return true;
170
171 // "condition_variable" is the longest standard header name at 18 characters.
172 // If the include file name is longer than that, it can't be a standard header.
Taewook Oh755e4d22016-06-13 21:55:33 +0000173 static const size_t MaxStdHeaderNameLen = 18u;
Taewook Ohf42103c2016-06-13 20:40:21 +0000174 if (Include.size() > MaxStdHeaderNameLen)
175 return false;
176
177 // Lowercase and normalize the search string.
178 SmallString<32> LowerInclude{Include};
179 for (char &Ch : LowerInclude) {
180 // In the ASCII range?
George Burgess IV5d3bd932016-06-16 02:30:33 +0000181 if (static_cast<unsigned char>(Ch) > 0x7f)
Taewook Ohf42103c2016-06-13 20:40:21 +0000182 return false; // Can't be a standard header
183 // ASCII lowercase:
184 if (Ch >= 'A' && Ch <= 'Z')
185 Ch += 'a' - 'A';
186 // Normalize path separators for comparison purposes.
187 else if (::llvm::sys::path::is_separator(Ch))
188 Ch = '/';
189 }
190
191 // The standard C/C++ and Posix headers
192 return llvm::StringSwitch<bool>(LowerInclude)
193 // C library headers
194 .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
195 .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
196 .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
197 .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
198 .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
199 .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
200
201 // C++ headers for C library facilities
202 .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
203 .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
204 .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
205 .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
206 .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
207 .Case("cwctype", true)
208
209 // C++ library headers
210 .Cases("algorithm", "fstream", "list", "regex", "thread", true)
211 .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
212 .Cases("atomic", "future", "map", "set", "type_traits", true)
213 .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
214 .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
215 .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
216 .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
217 .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
218 .Cases("deque", "istream", "queue", "string", "valarray", true)
219 .Cases("exception", "iterator", "random", "strstream", "vector", true)
220 .Cases("forward_list", "limits", "ratio", "system_error", true)
221
222 // POSIX headers (which aren't also C headers)
223 .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
224 .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
225 .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
226 .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
227 .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
228 .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
229 .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
230 .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
231 .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
232 .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
233 .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
234 .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
235 .Default(false);
236}
237
Serge Pavlov07c0f042014-12-18 11:14:21 +0000238bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
239 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000240 // Missing macro name?
241 if (MacroNameTok.is(tok::eod))
242 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
243
244 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
245 if (!II) {
246 bool Invalid = false;
247 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
248 if (Invalid)
249 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000250 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000251
Alp Tokerf33619c2014-05-31 03:38:08 +0000252 if (!II->isCPlusPlusOperatorKeyword())
253 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000254
Alp Tokere03e9e12014-05-31 16:32:22 +0000255 // C++ 2.5p2: Alternative tokens behave the same as its primary token
256 // except for their spellings.
257 Diag(MacroNameTok, getLangOpts().MicrosoftExt
258 ? diag::ext_pp_operator_used_as_macro_name
259 : diag::err_pp_operator_used_as_macro_name)
260 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000261
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000262 // Allow #defining |and| and friends for Microsoft compatibility or
263 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000264 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000265 }
266
Serge Pavlovd024f522014-10-24 17:31:32 +0000267 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000268 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
269 return Diag(MacroNameTok, diag::err_defined_macro_name);
270 }
271
Richard Smith20e883e2015-04-29 23:20:19 +0000272 if (isDefineUndef == MU_Undef) {
273 auto *MI = getMacroInfo(II);
274 if (MI && MI->isBuiltinMacro()) {
275 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
276 // and C++ [cpp.predefined]p4], but allow it as an extension.
277 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
278 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000279 }
280
Serge Pavlov07c0f042014-12-18 11:14:21 +0000281 // If defining/undefining reserved identifier or a keyword, we need to issue
282 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000283 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000284 if (ShadowFlag)
285 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000286 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
Mehdi Amini99d1b292016-10-01 16:38:28 +0000287 (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000288 MacroDiag D = MD_NoWarn;
289 if (isDefineUndef == MU_Define) {
290 D = shouldWarnOnMacroDef(*this, II);
291 }
292 else if (isDefineUndef == MU_Undef)
293 D = shouldWarnOnMacroUndef(*this, II);
294 if (D == MD_KeywordDef) {
295 // We do not want to warn on some patterns widely used in configuration
296 // scripts. This requires analyzing next tokens, so do not issue warnings
297 // now, only inform caller.
298 if (ShadowFlag)
299 *ShadowFlag = true;
300 }
301 if (D == MD_ReservedMacro)
302 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000303 }
304
Alp Tokerb05e0b52014-05-21 06:13:51 +0000305 // Okay, we got a good identifier.
306 return false;
307}
308
James Dennettf6333ac2012-06-22 05:46:07 +0000309/// \brief Lex and validate a macro name, which occurs after a
310/// \#define or \#undef.
311///
Serge Pavlovd024f522014-10-24 17:31:32 +0000312/// This sets the token kind to eod and discards the rest of the macro line if
313/// the macro name is invalid.
314///
315/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000316/// \param isDefineUndef Context in which macro is used.
317/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
318void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
319 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000320 // Read the token, don't allow macro expansion on it.
321 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000322
Douglas Gregor12785102010-08-24 20:21:13 +0000323 if (MacroNameTok.is(tok::code_completion)) {
324 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000325 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000326 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000327 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000328 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000329
Serge Pavlov07c0f042014-12-18 11:14:21 +0000330 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000331 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000332
333 // Invalid macro name, read and discard the rest of the line and set the
334 // token kind to tok::eod if necessary.
335 if (MacroNameTok.isNot(tok::eod)) {
336 MacroNameTok.setKind(tok::eod);
337 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000338 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000339}
340
James Dennettf6333ac2012-06-22 05:46:07 +0000341/// \brief Ensure that the next token is a tok::eod token.
342///
343/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000344/// true, then we consider macros that expand to zero tokens as being ok.
345void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000346 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000347 // Lex unexpanded tokens for most directives: macros might expand to zero
348 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
349 // #line) allow empty macros.
350 if (EnableMacros)
351 Lex(Tmp);
352 else
353 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000354
Chris Lattnerf64b3522008-03-09 01:54:53 +0000355 // There should be no tokens after the directive, but we allow them as an
356 // extension.
357 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
358 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000359
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000360 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000361 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000362 // or if this is a macro-style preprocessing directive, because it is more
363 // trouble than it is worth to insert /**/ and check that there is no /**/
364 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000365 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000366 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000367 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000368 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
369 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000370 DiscardUntilEndOfDirective();
371 }
372}
373
James Dennettf6333ac2012-06-22 05:46:07 +0000374/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
375/// decided that the subsequent tokens are in the \#if'd out portion of the
376/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000377/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000378/// this \#if directive, so \#else/\#elif blocks should never be entered.
379/// If ElseOk is true, then \#else directives are ok, if not, then we have
380/// already seen one so a \#else directive is a duplicate. When this returns,
381/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000382void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
383 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000384 bool FoundElse,
385 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000387 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000388
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000389 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000390 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000391
Ted Kremenek56572ab2008-12-12 18:34:08 +0000392 if (CurPTHLexer) {
393 PTHSkipExcludedConditionalBlock();
394 return;
395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattnerf64b3522008-03-09 01:54:53 +0000397 // Enter raw mode to disable identifier lookup (and thus macro expansion),
398 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000399 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000400 Token Tok;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000401 while (true) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000402 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000403
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000404 if (Tok.is(tok::code_completion)) {
405 if (CodeComplete)
406 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000407 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000408 continue;
409 }
Taewook Oh755e4d22016-06-13 21:55:33 +0000410
Chris Lattnerf64b3522008-03-09 01:54:53 +0000411 // If this is the end of the buffer, we have an error.
412 if (Tok.is(tok::eof)) {
413 // Emit errors for each unterminated conditional on the stack, including
414 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000415 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000416 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000417 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
418 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000419 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000420 }
421
Chris Lattnerf64b3522008-03-09 01:54:53 +0000422 // Just return and let the caller lex after this #include.
423 break;
424 }
Mike Stump11289f42009-09-09 15:08:12 +0000425
Chris Lattnerf64b3522008-03-09 01:54:53 +0000426 // If this token is not a preprocessor directive, just skip it.
427 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
428 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattnerf64b3522008-03-09 01:54:53 +0000430 // We just parsed a # character at the start of a line, so we're in
431 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000432 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000433 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000434 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000435
Mike Stump11289f42009-09-09 15:08:12 +0000436
Chris Lattnerf64b3522008-03-09 01:54:53 +0000437 // Read the next token, the directive flavor.
438 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000439
Chris Lattnerf64b3522008-03-09 01:54:53 +0000440 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
441 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000442 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000443 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000444 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000445 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000446 continue;
447 }
448
449 // If the first letter isn't i or e, it isn't intesting to us. We know that
450 // this is safe in the face of spelling differences, because there is no way
451 // to spell an i/e in a strange way that is another letter. Skipping this
452 // allows us to avoid looking up the identifier info for #define/#undef and
453 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000454 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000455
Alp Toker2d57cea2014-05-17 04:53:25 +0000456 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000457 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000458 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000459 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000460 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000461 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000462 continue;
463 }
Mike Stump11289f42009-09-09 15:08:12 +0000464
Chris Lattnerf64b3522008-03-09 01:54:53 +0000465 // Get the identifier name without trigraphs or embedded newlines. Note
466 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
467 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000468 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000469 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000470 if (!Tok.needsCleaning() && RI.size() < 20) {
471 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000472 } else {
473 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000474 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000475 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000476 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000477 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000478 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000479 continue;
480 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000481 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000482 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000483 }
Mike Stump11289f42009-09-09 15:08:12 +0000484
Benjamin Kramer144884642009-12-31 13:32:38 +0000485 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000486 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000487 if (Sub.empty() || // "if"
488 Sub == "def" || // "ifdef"
489 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000490 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
491 // bother parsing the condition.
492 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000493 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000494 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000495 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000496 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000497 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000499 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000500 PPConditionalInfo CondInfo;
501 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000502 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000503 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000504 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000505
Chris Lattnerf64b3522008-03-09 01:54:53 +0000506 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000507 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000508 // Restore the value of LexingRawMode so that trailing comments
509 // are handled correctly, if we've reached the outermost block.
510 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000511 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000512 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000513 if (Callbacks)
514 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000515 break;
Richard Smithd0124572012-06-21 00:35:03 +0000516 } else {
517 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000518 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000519 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000520 // #else directive in a skipping conditional. If not in some other
521 // skipping conditional, and if #else hasn't already been seen, enter it
522 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000523 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000524
Chris Lattnerf64b3522008-03-09 01:54:53 +0000525 // If this is a #else with a #else before it, report the error.
526 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattnerf64b3522008-03-09 01:54:53 +0000528 // Note that we've seen a #else in this conditional.
529 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000530
Chris Lattnerf64b3522008-03-09 01:54:53 +0000531 // If the conditional is at the top level, and the #if block wasn't
532 // entered, enter the #else block now.
533 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
534 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000535 // Restore the value of LexingRawMode so that trailing comments
536 // are handled correctly.
537 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000538 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000539 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000540 if (Callbacks)
541 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000542 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000543 } else {
544 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000545 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000546 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000547 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000548
John Thompson17c35732013-12-04 20:19:30 +0000549 // If this is a #elif with a #else before it, report the error.
550 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
551
Chris Lattnerf64b3522008-03-09 01:54:53 +0000552 // If this is in a skipping block or if we're already handled this #if
553 // block, don't bother parsing the condition.
554 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
555 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000556 } else {
John Thompson17c35732013-12-04 20:19:30 +0000557 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000558 // Restore the value of LexingRawMode so that identifiers are
559 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000560 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
561 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000562 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000563 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000564 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000565 if (Callbacks) {
566 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000567 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000568 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000569 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000570 }
571 // If this condition is true, enter it!
572 if (CondValue) {
573 CondInfo.FoundNonSkip = true;
574 break;
575 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000576 }
577 }
578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000580 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000581 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000582 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000583 }
584
585 // Finally, if we are out of the conditional (saw an #endif or ran off the end
586 // of the file, just stop skipping and return to lexing whatever came after
587 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000588 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000589
590 if (Callbacks) {
591 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
592 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
593 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000594}
595
Ted Kremenek56572ab2008-12-12 18:34:08 +0000596void Preprocessor::PTHSkipExcludedConditionalBlock() {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000597 while (true) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000598 assert(CurPTHLexer);
599 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000600
Ted Kremenek56572ab2008-12-12 18:34:08 +0000601 // Skip to the next '#else', '#elif', or #endif.
602 if (CurPTHLexer->SkipBlock()) {
603 // We have reached an #endif. Both the '#' and 'endif' tokens
604 // have been consumed by the PTHLexer. Just pop off the condition level.
605 PPConditionalInfo CondInfo;
606 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000607 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000608 assert(!InCond && "Can't be skipping if not in a conditional!");
609 break;
610 }
Mike Stump11289f42009-09-09 15:08:12 +0000611
Ted Kremenek56572ab2008-12-12 18:34:08 +0000612 // We have reached a '#else' or '#elif'. Lex the next token to get
613 // the directive flavor.
614 Token Tok;
615 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000616
Ted Kremenek56572ab2008-12-12 18:34:08 +0000617 // We can actually look up the IdentifierInfo here since we aren't in
618 // raw mode.
619 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
620
621 if (K == tok::pp_else) {
622 // #else: Enter the else condition. We aren't in a nested condition
623 // since we skip those. We're always in the one matching the last
624 // blocked we skipped.
625 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
626 // Note that we've seen a #else in this conditional.
627 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000628
Ted Kremenek56572ab2008-12-12 18:34:08 +0000629 // If the #if block wasn't entered then enter the #else block now.
630 if (!CondInfo.FoundNonSkip) {
631 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000632
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000633 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000634 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000635 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000636 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000637
Ted Kremenek56572ab2008-12-12 18:34:08 +0000638 break;
639 }
Mike Stump11289f42009-09-09 15:08:12 +0000640
Ted Kremenek56572ab2008-12-12 18:34:08 +0000641 // Otherwise skip this block.
642 continue;
643 }
Mike Stump11289f42009-09-09 15:08:12 +0000644
Ted Kremenek56572ab2008-12-12 18:34:08 +0000645 assert(K == tok::pp_elif);
646 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
647
648 // If this is a #elif with a #else before it, report the error.
649 if (CondInfo.FoundElse)
650 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000651
Ted Kremenek56572ab2008-12-12 18:34:08 +0000652 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000653 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000654 if (CondInfo.FoundNonSkip)
655 continue;
656
657 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000658 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000659 CurPTHLexer->ParsingPreprocessorDirective = true;
660 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
661 CurPTHLexer->ParsingPreprocessorDirective = false;
662
663 // If this condition is true, enter it!
664 if (ShouldEnter) {
665 CondInfo.FoundNonSkip = true;
666 break;
667 }
668
669 // Otherwise, skip this block and go to the next one.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000670 }
671}
672
Richard Smith2a553082015-04-23 22:58:06 +0000673Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000674 if (!SourceMgr.isInMainFile(Loc)) {
675 // Try to determine the module of the include directive.
676 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
677 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
678 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
679 // The include comes from an included file.
680 return HeaderInfo.getModuleMap()
681 .findModuleForHeader(EntryOfIncl)
682 .getModule();
683 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000684 }
Richard Smith7e82e012016-02-19 22:25:36 +0000685
686 // This is either in the main file or not in a file at all. It belongs
687 // to the current module, if there is one.
688 return getLangOpts().CurrentModule.empty()
689 ? nullptr
690 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000691}
692
Richard Smith2a553082015-04-23 22:58:06 +0000693Module *Preprocessor::getModuleContainingLocation(SourceLocation Loc) {
694 return HeaderInfo.getModuleMap().inferModuleFromLocation(
695 FullSourceLoc(Loc, SourceMgr));
696}
697
Richard Smith4eb83932016-04-27 21:57:05 +0000698const FileEntry *
699Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
700 SourceLocation Loc) {
701 // If we have a module import syntax, we shouldn't include a header to
702 // make a particular module visible.
703 if (getLangOpts().ObjC2)
704 return nullptr;
705
706 // Figure out which module we'd want to import.
707 Module *M = getModuleContainingLocation(Loc);
708 if (!M)
709 return nullptr;
710
711 Module *TopM = M->getTopLevelModule();
712 Module *IncM = getModuleForLocation(IncLoc);
713
714 // Walk up through the include stack, looking through textual headers of M
715 // until we hit a non-textual header that we can #include. (We assume textual
716 // headers of a module with non-textual headers aren't meant to be used to
717 // import entities from the module.)
718 auto &SM = getSourceManager();
719 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
720 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
721 auto *FE = SM.getFileEntryForID(ID);
722
723 bool InTextualHeader = false;
724 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
725 if (!Header.getModule()->isSubModuleOf(TopM))
726 continue;
727
728 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
729 // If this is an accessible, non-textual header of M's top-level module
730 // that transitively includes the given location and makes the
731 // corresponding module visible, this is the thing to #include.
732 if (Header.isAccessibleFrom(IncM))
733 return FE;
734
735 // It's in a private header; we can't #include it.
736 // FIXME: If there's a public header in some module that re-exports it,
737 // then we could suggest including that, but it's not clear that's the
738 // expected way to make this entity visible.
739 continue;
740 }
741
742 InTextualHeader = true;
743 }
744
745 if (!InTextualHeader)
746 break;
747
748 Loc = SM.getIncludeLoc(ID);
749 }
750
751 return nullptr;
752}
753
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000754const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000755 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000756 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000757 bool isAngled,
758 const DirectoryLookup *FromDir,
Richard Smith25d50752014-10-20 00:15:49 +0000759 const FileEntry *FromFile,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000760 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000761 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000762 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000763 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000764 bool SkipCache) {
Taewook Oh755e4d22016-06-13 21:55:33 +0000765 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000766 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000767
Will Wilson0fafd342013-12-27 19:46:16 +0000768 // If the header lookup mechanism may be relative to the current inclusion
769 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000770 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
771 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000772 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000773 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000774 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000775 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000776
Chris Lattner022923a2009-02-04 19:45:07 +0000777 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000778 // predefines buffer or the module includes buffer. Any other file is not
779 // lexed with a normal lexer, so it won't be scanned for preprocessor
780 // directives.
781 //
782 // If we have the predefines buffer, resolve #include references (which come
783 // from the -include command line argument) from the current working
784 // directory instead of relative to the main file.
785 //
786 // If we have the module includes buffer, resolve #include references (which
787 // come from header declarations in the module map) relative to the module
788 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000789 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000790 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000791 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000792 BuildSystemModule = getCurrentModule()->IsSystem;
793 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000794 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000795 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
796 } else {
797 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
798 }
Will Wilson0fafd342013-12-27 19:46:16 +0000799
800 // MSVC searches the current include stack from top to bottom for
801 // headers included by quoted include directives.
802 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000803 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000804 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
805 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
806 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000807 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000808 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000809 }
Chris Lattner022923a2009-02-04 19:45:07 +0000810 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000811 }
Mike Stump11289f42009-09-09 15:08:12 +0000812
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000813 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000814
815 if (FromFile) {
816 // We're supposed to start looking from after a particular file. Search
817 // the include path until we find that file or run out of files.
818 const DirectoryLookup *TmpCurDir = CurDir;
819 const DirectoryLookup *TmpFromDir = nullptr;
820 while (const FileEntry *FE = HeaderInfo.LookupFile(
821 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000822 Includers, SearchPath, RelativePath, RequestingModule,
823 SuggestedModule, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000824 // Keep looking as if this file did a #include_next.
825 TmpFromDir = TmpCurDir;
826 ++TmpFromDir;
827 if (FE == FromFile) {
828 // Found it.
829 FromDir = TmpFromDir;
830 CurDir = TmpCurDir;
831 break;
832 }
833 }
834 }
835
836 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000837 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000838 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Manman Rene4a5d372016-05-17 02:15:12 +0000839 RelativePath, RequestingModule, SuggestedModule, SkipCache,
840 BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000841 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000842 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000843 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000844 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
845 Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000846 return FE;
847 }
Mike Stump11289f42009-09-09 15:08:12 +0000848
Will Wilson0fafd342013-12-27 19:46:16 +0000849 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000850 // Otherwise, see if this is a subframework header. If so, this is relative
851 // to one of the headers on the #include stack. Walk the list of the current
852 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000853 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000854 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000855 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000856 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000857 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000858 SuggestedModule))) {
859 if (SuggestedModule && !LangOpts.AsmPreprocessor)
860 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000861 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
862 Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000863 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000864 }
865 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000866 }
Mike Stump11289f42009-09-09 15:08:12 +0000867
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000868 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
869 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000870 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000871 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000872 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000873 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000874 RequestingModule, SuggestedModule))) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000875 if (SuggestedModule && !LangOpts.AsmPreprocessor)
876 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000877 RequestingModule, RequestingModuleIsModuleInterface,
878 FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000879 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000880 }
881 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000882 }
883 }
Mike Stump11289f42009-09-09 15:08:12 +0000884
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000885 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000886 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000887}
888
Chris Lattnerf64b3522008-03-09 01:54:53 +0000889//===----------------------------------------------------------------------===//
890// Preprocessor Directive Handling.
891//===----------------------------------------------------------------------===//
892
David Blaikied5321242012-06-06 18:52:13 +0000893class Preprocessor::ResetMacroExpansionHelper {
894public:
895 ResetMacroExpansionHelper(Preprocessor *pp)
896 : PP(pp), save(pp->DisableMacroExpansion) {
897 if (pp->MacroExpansionInDirectivesOverride)
898 pp->DisableMacroExpansion = false;
899 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000900
David Blaikied5321242012-06-06 18:52:13 +0000901 ~ResetMacroExpansionHelper() {
902 PP->DisableMacroExpansion = save;
903 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000904
David Blaikied5321242012-06-06 18:52:13 +0000905private:
906 Preprocessor *PP;
907 bool save;
908};
909
Chris Lattnerf64b3522008-03-09 01:54:53 +0000910/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000911/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000912/// lexer/preprocessor state, and advances the lexer(s) so that the next token
913/// read is the correct one.
914void Preprocessor::HandleDirective(Token &Result) {
915 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000916
Chris Lattnerf64b3522008-03-09 01:54:53 +0000917 // We just parsed a # character at the start of a line, so we're in directive
918 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000919 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000920 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000921 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000922
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000923 bool ImmediatelyAfterTopLevelIfndef =
924 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
925 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
926
Chris Lattnerf64b3522008-03-09 01:54:53 +0000927 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000928
Chris Lattnerf64b3522008-03-09 01:54:53 +0000929 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000930 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000931 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000932 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000933
Chris Lattner2d17ab72009-03-18 21:00:25 +0000934 // Save the '#' token in case we need to return it later.
935 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000936
Chris Lattnerf64b3522008-03-09 01:54:53 +0000937 // Read the next token, the directive flavor. This isn't expanded due to
938 // C99 6.10.3p8.
939 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattnerf64b3522008-03-09 01:54:53 +0000941 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
942 // #define A(x) #x
943 // A(abc
944 // #warning blah
945 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000946 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
947 // not support this for #include-like directives, since that can result in
948 // terrible diagnostics, and does not work in GCC.
949 if (InMacroArgs) {
950 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
951 switch (II->getPPKeywordID()) {
952 case tok::pp_include:
953 case tok::pp_import:
954 case tok::pp_include_next:
955 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000956 case tok::pp_pragma:
957 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000958 DiscardUntilEndOfDirective();
959 return;
960 default:
961 break;
962 }
963 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000964 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000965 }
Mike Stump11289f42009-09-09 15:08:12 +0000966
David Blaikied5321242012-06-06 18:52:13 +0000967 // Temporarily enable macro expansion if set so
968 // and reset to previous state when returning from this function.
969 ResetMacroExpansionHelper helper(this);
970
Chris Lattnerf64b3522008-03-09 01:54:53 +0000971 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000972 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000973 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000974 case tok::code_completion:
975 if (CodeComplete)
976 CodeComplete->CodeCompleteDirective(
977 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000978 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000979 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000980 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000981 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000982 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000983 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000984 default:
985 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000986 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000987
Chris Lattnerf64b3522008-03-09 01:54:53 +0000988 // Ask what the preprocessor keyword ID is.
989 switch (II->getPPKeywordID()) {
990 default: break;
991 // C99 6.10.1 - Conditional Inclusion.
992 case tok::pp_if:
993 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
994 case tok::pp_ifdef:
995 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
996 case tok::pp_ifndef:
997 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
998 case tok::pp_elif:
999 return HandleElifDirective(Result);
1000 case tok::pp_else:
1001 return HandleElseDirective(Result);
1002 case tok::pp_endif:
1003 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001004
Chris Lattnerf64b3522008-03-09 01:54:53 +00001005 // C99 6.10.2 - Source File Inclusion.
1006 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001007 // Handle #include.
1008 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +00001009 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001010 // Handle -imacros.
Taewook Oh755e4d22016-06-13 21:55:33 +00001011 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00001012
Chris Lattnerf64b3522008-03-09 01:54:53 +00001013 // C99 6.10.3 - Macro Replacement.
1014 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001015 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001016 case tok::pp_undef:
1017 return HandleUndefDirective(Result);
1018
1019 // C99 6.10.4 - Line Control.
1020 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +00001021 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattnerf64b3522008-03-09 01:54:53 +00001023 // C99 6.10.5 - Error Directive.
1024 case tok::pp_error:
1025 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +00001026
Chris Lattnerf64b3522008-03-09 01:54:53 +00001027 // C99 6.10.6 - Pragma Directive.
1028 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +00001029 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +00001030
Chris Lattnerf64b3522008-03-09 01:54:53 +00001031 // GNU Extensions.
1032 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001033 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001034 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001035 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00001036
Chris Lattnerf64b3522008-03-09 01:54:53 +00001037 case tok::pp_warning:
1038 Diag(Result, diag::ext_pp_warning_directive);
1039 return HandleUserDiagnosticDirective(Result, true);
1040 case tok::pp_ident:
1041 return HandleIdentSCCSDirective(Result);
1042 case tok::pp_sccs:
1043 return HandleIdentSCCSDirective(Result);
1044 case tok::pp_assert:
1045 //isExtension = true; // FIXME: implement #assert
1046 break;
1047 case tok::pp_unassert:
1048 //isExtension = true; // FIXME: implement #unassert
1049 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001050
Douglas Gregor663b48f2012-01-03 19:48:16 +00001051 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001052 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001053 return HandleMacroPublicDirective(Result);
1054 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001055
Douglas Gregor663b48f2012-01-03 19:48:16 +00001056 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001057 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001058 return HandleMacroPrivateDirective(Result);
1059 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001060 }
1061 break;
1062 }
Mike Stump11289f42009-09-09 15:08:12 +00001063
Chris Lattner2d17ab72009-03-18 21:00:25 +00001064 // If this is a .S file, treat unknown # directives as non-preprocessor
1065 // directives. This is important because # may be a comment or introduce
1066 // various pseudo-ops. Just return the # token and push back the following
1067 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001068 if (getLangOpts().AsmPreprocessor) {
David Blaikie2eabcc92016-02-09 18:52:09 +00001069 auto Toks = llvm::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001070 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001071 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001072 Toks[1] = Result;
Taewook Oh755e4d22016-06-13 21:55:33 +00001073
Chris Lattner56f64c12011-01-06 05:01:51 +00001074 // If the second token is a hashhash token, then we need to translate it to
1075 // unknown so the token lexer doesn't try to perform token pasting.
1076 if (Result.is(tok::hashhash))
1077 Toks[1].setKind(tok::unknown);
Taewook Oh755e4d22016-06-13 21:55:33 +00001078
Chris Lattner2d17ab72009-03-18 21:00:25 +00001079 // Enter this token stream so that we re-lex the tokens. Make sure to
1080 // enable macro expansion, in case the token after the # is an identifier
1081 // that is expanded.
David Blaikie2eabcc92016-02-09 18:52:09 +00001082 EnterTokenStream(std::move(Toks), 2, false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001083 return;
1084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
Chris Lattnerf64b3522008-03-09 01:54:53 +00001086 // If we reached here, the preprocessing token is not valid!
1087 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001088
Chris Lattnerf64b3522008-03-09 01:54:53 +00001089 // Read the rest of the PP line.
1090 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001091
Chris Lattnerf64b3522008-03-09 01:54:53 +00001092 // Okay, we're done parsing the directive.
1093}
1094
Chris Lattner76e68962009-01-26 06:19:46 +00001095/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1096/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1097static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001098 unsigned DiagID, Preprocessor &PP,
1099 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001100 if (DigitTok.isNot(tok::numeric_constant)) {
1101 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001102
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001103 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001104 PP.DiscardUntilEndOfDirective();
1105 return true;
1106 }
Mike Stump11289f42009-09-09 15:08:12 +00001107
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001108 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001109 IntegerBuffer.resize(DigitTok.getLength());
1110 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001111 bool Invalid = false;
1112 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1113 if (Invalid)
1114 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001115
Chris Lattnerd66f1722009-04-18 18:35:15 +00001116 // Verify that we have a simple digit-sequence, and compute the value. This
1117 // is always a simple digit string computed in decimal, so we do this manually
1118 // here.
1119 Val = 0;
1120 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001121 // C++1y [lex.fcon]p1:
1122 // Optional separating single quotes in a digit-sequence are ignored
1123 if (DigitTokBegin[i] == '\'')
1124 continue;
1125
Jordan Rosea7d03842013-02-08 22:30:41 +00001126 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001127 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001128 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001129 PP.DiscardUntilEndOfDirective();
1130 return true;
1131 }
Mike Stump11289f42009-09-09 15:08:12 +00001132
Chris Lattnerd66f1722009-04-18 18:35:15 +00001133 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1134 if (NextVal < Val) { // overflow.
1135 PP.Diag(DigitTok, DiagID);
1136 PP.DiscardUntilEndOfDirective();
1137 return true;
1138 }
1139 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001140 }
Mike Stump11289f42009-09-09 15:08:12 +00001141
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001142 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001143 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1144 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001145
Chris Lattner76e68962009-01-26 06:19:46 +00001146 return false;
1147}
1148
James Dennettf6333ac2012-06-22 05:46:07 +00001149/// \brief Handle a \#line directive: C99 6.10.4.
1150///
1151/// The two acceptable forms are:
1152/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001153/// # line digit-sequence
1154/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001155/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001156void Preprocessor::HandleLineDirective(Token &Tok) {
1157 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1158 // expanded.
1159 Token DigitTok;
1160 Lex(DigitTok);
1161
Chris Lattner100c65e2009-01-26 05:29:08 +00001162 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001163 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001164 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001165 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001166
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001167 if (LineNo == 0)
1168 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001169
Chris Lattner76e68962009-01-26 06:19:46 +00001170 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1171 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001172 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001173 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001174 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001175 if (LineNo >= LineLimit)
1176 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001177 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001178 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001179
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001180 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001181 Token StrTok;
1182 Lex(StrTok);
1183
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001184 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1185 // string followed by eod.
1186 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001187 ; // ok
1188 else if (StrTok.isNot(tok::string_literal)) {
1189 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001190 return DiscardUntilEndOfDirective();
1191 } else if (StrTok.hasUDSuffix()) {
1192 Diag(StrTok, diag::err_invalid_string_udl);
1193 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001194 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001195 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001196 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001197 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001198 if (Literal.hadError)
1199 return DiscardUntilEndOfDirective();
1200 if (Literal.Pascal) {
1201 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1202 return DiscardUntilEndOfDirective();
1203 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001204 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001205
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001206 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001207 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1208 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001209 }
Mike Stump11289f42009-09-09 15:08:12 +00001210
Chris Lattner1eaa70a2009-02-03 21:52:55 +00001211 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +00001212
Chris Lattner839150e2009-03-27 17:13:49 +00001213 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001214 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1215 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +00001216 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +00001217}
1218
Chris Lattner76e68962009-01-26 06:19:46 +00001219/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1220/// marker directive.
1221static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1222 bool &IsSystemHeader, bool &IsExternCHeader,
1223 Preprocessor &PP) {
1224 unsigned FlagVal;
1225 Token FlagTok;
1226 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001227 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001228 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1229 return true;
1230
1231 if (FlagVal == 1) {
1232 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001233
Chris Lattner76e68962009-01-26 06:19:46 +00001234 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001235 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001236 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1237 return true;
1238 } else if (FlagVal == 2) {
1239 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001240
Chris Lattner1c967782009-02-04 06:25:26 +00001241 SourceManager &SM = PP.getSourceManager();
1242 // If we are leaving the current presumed file, check to make sure the
1243 // presumed include stack isn't empty!
1244 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001245 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001246 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001247 if (PLoc.isInvalid())
1248 return true;
Taewook Oh755e4d22016-06-13 21:55:33 +00001249
Chris Lattner1c967782009-02-04 06:25:26 +00001250 // If there is no include loc (main file) or if the include loc is in a
1251 // different physical file, then we aren't in a "1" line marker flag region.
1252 SourceLocation IncLoc = PLoc.getIncludeLoc();
1253 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001254 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001255 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1256 PP.DiscardUntilEndOfDirective();
1257 return true;
1258 }
Mike Stump11289f42009-09-09 15:08:12 +00001259
Chris Lattner76e68962009-01-26 06:19:46 +00001260 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001261 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001262 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1263 return true;
1264 }
1265
1266 // We must have 3 if there are still flags.
1267 if (FlagVal != 3) {
1268 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001269 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001270 return true;
1271 }
Mike Stump11289f42009-09-09 15:08:12 +00001272
Chris Lattner76e68962009-01-26 06:19:46 +00001273 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001274
Chris Lattner76e68962009-01-26 06:19:46 +00001275 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001276 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001277 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001278 return true;
1279
1280 // We must have 4 if there is yet another flag.
1281 if (FlagVal != 4) {
1282 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001283 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001284 return true;
1285 }
Mike Stump11289f42009-09-09 15:08:12 +00001286
Chris Lattner76e68962009-01-26 06:19:46 +00001287 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001288
Chris Lattner76e68962009-01-26 06:19:46 +00001289 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001290 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001291
1292 // There are no more valid flags here.
1293 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001294 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001295 return true;
1296}
1297
1298/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1299/// one of the following forms:
1300///
1301/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001302/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001303/// # 42 "file" ('1' | '2')? '3' '4'?
1304///
1305void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1306 // Validate the number and convert it to an unsigned. GNU does not have a
1307 // line # limit other than it fit in 32-bits.
1308 unsigned LineNo;
1309 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001310 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001311 return;
Mike Stump11289f42009-09-09 15:08:12 +00001312
Chris Lattner76e68962009-01-26 06:19:46 +00001313 Token StrTok;
1314 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001315
Chris Lattner76e68962009-01-26 06:19:46 +00001316 bool IsFileEntry = false, IsFileExit = false;
1317 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001318 int FilenameID = -1;
1319
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001320 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1321 // string followed by eod.
1322 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001323 ; // ok
1324 else if (StrTok.isNot(tok::string_literal)) {
1325 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001326 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001327 } else if (StrTok.hasUDSuffix()) {
1328 Diag(StrTok, diag::err_invalid_string_udl);
1329 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001330 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001331 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001332 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001333 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001334 if (Literal.hadError)
1335 return DiscardUntilEndOfDirective();
1336 if (Literal.Pascal) {
1337 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1338 return DiscardUntilEndOfDirective();
1339 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001340 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001341
Chris Lattner76e68962009-01-26 06:19:46 +00001342 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001343 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001344 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001345 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001346 }
Mike Stump11289f42009-09-09 15:08:12 +00001347
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001348 // Create a line note with this information.
1349 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001350 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001351 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001352
Chris Lattner839150e2009-03-27 17:13:49 +00001353 // If the preprocessor has callbacks installed, notify them of the #line
1354 // change. This is used so that the line marker comes out in -E mode for
1355 // example.
1356 if (Callbacks) {
1357 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1358 if (IsFileEntry)
1359 Reason = PPCallbacks::EnterFile;
1360 else if (IsFileExit)
1361 Reason = PPCallbacks::ExitFile;
1362 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1363 if (IsExternCHeader)
1364 FileKind = SrcMgr::C_ExternCSystem;
1365 else if (IsSystemHeader)
1366 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001367
Chris Lattnerc745cec2010-04-14 04:28:50 +00001368 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001369 }
Chris Lattner76e68962009-01-26 06:19:46 +00001370}
1371
Chris Lattner38d7fd22009-01-26 05:30:54 +00001372/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1373///
Mike Stump11289f42009-09-09 15:08:12 +00001374void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001375 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001376 // PTH doesn't emit #warning or #error directives.
1377 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001378 return CurPTHLexer->DiscardToEndOfLine();
1379
Chris Lattnerf64b3522008-03-09 01:54:53 +00001380 // Read the rest of the line raw. We do this because we don't want macros
1381 // to be expanded and we don't require that the tokens be valid preprocessing
1382 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1383 // collapse multiple consequtive white space between tokens, but this isn't
1384 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001385 SmallString<128> Message;
1386 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001387
1388 // Find the first non-whitespace character, so that we can make the
1389 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001390 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001391
Chris Lattner100c65e2009-01-26 05:29:08 +00001392 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001393 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001394 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001395 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001396}
1397
1398/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1399///
1400void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1401 // Yes, this directive is an extension.
1402 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001403
Chris Lattnerf64b3522008-03-09 01:54:53 +00001404 // Read the string argument.
1405 Token StrTok;
1406 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001407
Chris Lattnerf64b3522008-03-09 01:54:53 +00001408 // If the token kind isn't a string, it's a malformed directive.
1409 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001410 StrTok.isNot(tok::wide_string_literal)) {
1411 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001412 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001413 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001414 return;
1415 }
Mike Stump11289f42009-09-09 15:08:12 +00001416
Richard Smithd67aea22012-03-06 03:21:47 +00001417 if (StrTok.hasUDSuffix()) {
1418 Diag(StrTok, diag::err_invalid_string_udl);
1419 return DiscardUntilEndOfDirective();
1420 }
1421
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001422 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001423 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001424
Douglas Gregordc970f02010-03-16 22:30:13 +00001425 if (Callbacks) {
1426 bool Invalid = false;
1427 std::string Str = getSpelling(StrTok, &Invalid);
1428 if (!Invalid)
1429 Callbacks->Ident(Tok.getLocation(), Str);
1430 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001431}
1432
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001433/// \brief Handle a #public directive.
1434void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001435 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001436 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001437
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001438 // Error reading macro name? If so, diagnostic already issued.
1439 if (MacroNameTok.is(tok::eod))
1440 return;
1441
Douglas Gregor663b48f2012-01-03 19:48:16 +00001442 // Check to see if this is the last token on the #__public_macro line.
1443 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001444
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001445 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001446 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001447 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001448
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001449 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001450 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001451 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001452 return;
1453 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001454
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001455 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001456 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1457 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001458}
1459
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001460/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001461void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1462 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001463 ReadMacroName(MacroNameTok, MU_Undef);
Taewook Oh755e4d22016-06-13 21:55:33 +00001464
Douglas Gregorebf00492011-10-17 15:32:29 +00001465 // Error reading macro name? If so, diagnostic already issued.
1466 if (MacroNameTok.is(tok::eod))
1467 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001468
Douglas Gregor663b48f2012-01-03 19:48:16 +00001469 // Check to see if this is the last token on the #__private_macro line.
1470 CheckEndOfDirective("__private_macro");
Taewook Oh755e4d22016-06-13 21:55:33 +00001471
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001472 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001473 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001474 MacroDirective *MD = getLocalMacroDirective(II);
Taewook Oh755e4d22016-06-13 21:55:33 +00001475
Douglas Gregorebf00492011-10-17 15:32:29 +00001476 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001477 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001478 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001479 return;
1480 }
Taewook Oh755e4d22016-06-13 21:55:33 +00001481
Douglas Gregorebf00492011-10-17 15:32:29 +00001482 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001483 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1484 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001485}
1486
Chris Lattnerf64b3522008-03-09 01:54:53 +00001487//===----------------------------------------------------------------------===//
1488// Preprocessor Include Directive Handling.
1489//===----------------------------------------------------------------------===//
1490
1491/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001492/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001493/// true if the input filename was in <>'s or false if it were in ""'s. The
1494/// caller is expected to provide a buffer that is large enough to hold the
1495/// spelling of the filename, but is also expected to handle the case when
1496/// this method decides to use a different buffer.
1497bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001498 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001499 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001500 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001501
Chris Lattnerf64b3522008-03-09 01:54:53 +00001502 // Make sure the filename is <x> or "x".
1503 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001504 if (Buffer[0] == '<') {
1505 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001506 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001507 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001508 return true;
1509 }
1510 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001511 } else if (Buffer[0] == '"') {
1512 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001513 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001514 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001515 return true;
1516 }
1517 isAngled = false;
1518 } else {
1519 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001520 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001521 return true;
1522 }
Mike Stump11289f42009-09-09 15:08:12 +00001523
Chris Lattnerf64b3522008-03-09 01:54:53 +00001524 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001525 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001526 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001527 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001528 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001529 }
Mike Stump11289f42009-09-09 15:08:12 +00001530
Chris Lattnerf64b3522008-03-09 01:54:53 +00001531 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001532 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001533 return isAngled;
1534}
1535
James Dennett4a4f72d2013-11-27 01:27:40 +00001536// \brief Handle cases where the \#include name is expanded from a macro
1537// as multiple tokens, which need to be glued together.
1538//
1539// This occurs for code like:
1540// \code
1541// \#define FOO <a/b.h>
1542// \#include FOO
1543// \endcode
1544// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1545//
1546// This code concatenates and consumes tokens up to the '>' token. It returns
1547// false if the > was found, otherwise it returns true if it finds and consumes
1548// the EOD marker.
1549bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001550 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001551 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001552
John Thompsonb5353522009-10-30 13:49:06 +00001553 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001554 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001555 End = CurTok.getLocation();
Taewook Oh755e4d22016-06-13 21:55:33 +00001556
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001557 // FIXME: Provide code completion for #includes.
1558 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001559 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001560 Lex(CurTok);
1561 continue;
1562 }
1563
Chris Lattnerf64b3522008-03-09 01:54:53 +00001564 // Append the spelling of this token to the buffer. If there was a space
1565 // before it, add it now.
1566 if (CurTok.hasLeadingSpace())
1567 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001568
Chris Lattnerf64b3522008-03-09 01:54:53 +00001569 // Get the spelling of the token, directly into FilenameBuffer if possible.
1570 unsigned PreAppendSize = FilenameBuffer.size();
1571 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattnerf64b3522008-03-09 01:54:53 +00001573 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001574 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001575
Chris Lattnerf64b3522008-03-09 01:54:53 +00001576 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1577 if (BufPtr != &FilenameBuffer[PreAppendSize])
1578 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001579
Chris Lattnerf64b3522008-03-09 01:54:53 +00001580 // Resize FilenameBuffer to the correct size.
1581 if (CurTok.getLength() != ActualLen)
1582 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001583
Chris Lattnerf64b3522008-03-09 01:54:53 +00001584 // If we found the '>' marker, return success.
1585 if (CurTok.is(tok::greater))
1586 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001587
John Thompsonb5353522009-10-30 13:49:06 +00001588 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001589 }
1590
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001591 // If we hit the eod marker, emit an error and return true so that the caller
1592 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001593 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001594 return true;
1595}
1596
Richard Smith34f30512013-11-23 04:06:09 +00001597/// \brief Push a token onto the token stream containing an annotation.
1598static void EnterAnnotationToken(Preprocessor &PP,
1599 SourceLocation Begin, SourceLocation End,
1600 tok::TokenKind Kind, void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001601 // FIXME: Produce this as the current token directly, rather than
1602 // allocating a new token for it.
David Blaikie2eabcc92016-02-09 18:52:09 +00001603 auto Tok = llvm::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001604 Tok[0].startToken();
1605 Tok[0].setKind(Kind);
1606 Tok[0].setLocation(Begin);
1607 Tok[0].setAnnotationEndLoc(End);
1608 Tok[0].setAnnotationValue(AnnotationVal);
David Blaikie2eabcc92016-02-09 18:52:09 +00001609 PP.EnterTokenStream(std::move(Tok), 1, true);
Richard Smith34f30512013-11-23 04:06:09 +00001610}
1611
Richard Smith63b6fce2015-05-18 04:45:41 +00001612/// \brief Produce a diagnostic informing the user that a #include or similar
1613/// was implicitly treated as a module import.
1614static void diagnoseAutoModuleImport(
1615 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1616 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1617 SourceLocation PathEnd) {
1618 assert(PP.getLangOpts().ObjC2 && "no import syntax available");
1619
1620 SmallString<128> PathString;
1621 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1622 if (I)
1623 PathString += '.';
1624 PathString += Path[I].first->getName();
1625 }
1626 int IncludeKind = 0;
Taewook Oh755e4d22016-06-13 21:55:33 +00001627
Richard Smith63b6fce2015-05-18 04:45:41 +00001628 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1629 case tok::pp_include:
1630 IncludeKind = 0;
1631 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001632
Richard Smith63b6fce2015-05-18 04:45:41 +00001633 case tok::pp_import:
1634 IncludeKind = 1;
Taewook Oh755e4d22016-06-13 21:55:33 +00001635 break;
1636
Richard Smith63b6fce2015-05-18 04:45:41 +00001637 case tok::pp_include_next:
1638 IncludeKind = 2;
1639 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001640
Richard Smith63b6fce2015-05-18 04:45:41 +00001641 case tok::pp___include_macros:
1642 IncludeKind = 3;
1643 break;
Taewook Oh755e4d22016-06-13 21:55:33 +00001644
Richard Smith63b6fce2015-05-18 04:45:41 +00001645 default:
1646 llvm_unreachable("unknown include directive kind");
1647 }
1648
1649 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1650 /*IsTokenRange=*/false);
1651 PP.Diag(HashLoc, diag::warn_auto_module_import)
1652 << IncludeKind << PathString
1653 << FixItHint::CreateReplacement(ReplaceRange,
1654 ("@import " + PathString + ";").str());
1655}
1656
Taewook Ohf42103c2016-06-13 20:40:21 +00001657// Given a vector of path components and a string containing the real
1658// path to the file, build a properly-cased replacement in the vector,
1659// and return true if the replacement should be suggested.
1660static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1661 StringRef RealPathName) {
1662 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1663 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1664 int Cnt = 0;
1665 bool SuggestReplacement = false;
1666 // Below is a best-effort to handle ".." in paths. It is admittedly
1667 // not 100% correct in the presence of symlinks.
1668 for (auto &Component : llvm::reverse(Components)) {
1669 if ("." == Component) {
1670 } else if (".." == Component) {
1671 ++Cnt;
1672 } else if (Cnt) {
1673 --Cnt;
1674 } else if (RealPathComponentIter != RealPathComponentEnd) {
1675 if (Component != *RealPathComponentIter) {
1676 // If these path components differ by more than just case, then we
1677 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1678 // noisy false positives.
1679 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1680 if (!SuggestReplacement)
1681 break;
1682 Component = *RealPathComponentIter;
1683 }
1684 ++RealPathComponentIter;
1685 }
1686 }
1687 return SuggestReplacement;
1688}
1689
James Dennettf6333ac2012-06-22 05:46:07 +00001690/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1691/// the file to be included from the lexer, then include it! This is a common
1692/// routine with functionality shared between \#include, \#include_next and
1693/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001694/// specifies the file to start searching from.
Taewook Oh755e4d22016-06-13 21:55:33 +00001695void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001696 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001697 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001698 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001699 bool isImport) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001700 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001701 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001702
Chris Lattnerf64b3522008-03-09 01:54:53 +00001703 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001704 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001705 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001706 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001707 SourceLocation CharEnd; // the end of this directive, in characters
Taewook Oh755e4d22016-06-13 21:55:33 +00001708
Chris Lattnerf64b3522008-03-09 01:54:53 +00001709 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001710 case tok::eod:
1711 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001712 return;
Mike Stump11289f42009-09-09 15:08:12 +00001713
Chris Lattnerf64b3522008-03-09 01:54:53 +00001714 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001715 case tok::string_literal:
1716 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001717 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001718 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001719 break;
Mike Stump11289f42009-09-09 15:08:12 +00001720
Chris Lattnerf64b3522008-03-09 01:54:53 +00001721 case tok::less:
1722 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1723 // case, glue the tokens together into FilenameBuffer and interpret those.
1724 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001725 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001726 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001727 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001728 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001729 break;
1730 default:
1731 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1732 DiscardUntilEndOfDirective();
1733 return;
1734 }
Mike Stump11289f42009-09-09 15:08:12 +00001735
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001736 CharSourceRange FilenameRange
1737 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001738 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001739 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001740 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001741 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1742 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001743 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001744 DiscardUntilEndOfDirective();
1745 return;
1746 }
Mike Stump11289f42009-09-09 15:08:12 +00001747
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001748 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001749 // we allow macros that expand to nothing after the filename, because this
1750 // falls into the category of "#include pp-tokens new-line" specified in
1751 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001752 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001753
1754 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001755 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1756 Diag(FilenameTok, diag::err_pp_include_too_deep);
1757 return;
1758 }
Mike Stump11289f42009-09-09 15:08:12 +00001759
John McCall32f5fe12011-09-30 05:12:12 +00001760 // Complain about attempts to #include files in an audit pragma.
1761 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1762 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1763 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1764
1765 // Immediately leave the pragma.
1766 PragmaARCCFCodeAuditedLoc = SourceLocation();
1767 }
1768
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001769 // Complain about attempts to #include files in an assume-nonnull pragma.
1770 if (PragmaAssumeNonNullLoc.isValid()) {
1771 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1772 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1773
1774 // Immediately leave the pragma.
1775 PragmaAssumeNonNullLoc = SourceLocation();
1776 }
1777
Aaron Ballman611306e2012-03-02 22:51:54 +00001778 if (HeaderInfo.HasIncludeAliasMap()) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001779 // Map the filename with the brackets still attached. If the name doesn't
1780 // map to anything, fall back on the filename we've already gotten the
Aaron Ballman611306e2012-03-02 22:51:54 +00001781 // spelling for.
1782 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1783 if (!NewName.empty())
1784 Filename = NewName;
1785 }
1786
Chris Lattnerf64b3522008-03-09 01:54:53 +00001787 // Search include directories.
1788 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001789 SmallString<1024> SearchPath;
1790 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001791 // We get the raw path only if we have 'Callbacks' to which we later pass
1792 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001793 ModuleMap::KnownHeader SuggestedModule;
1794 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001795 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001796 if (LangOpts.MSVCCompat) {
1797 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001798#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001799 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001800#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001801 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001802 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001803 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001804 isAngled, LookupFrom, LookupFromFile, CurDir,
1805 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001806 &SuggestedModule);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001807
Richard Smithdbbc5232015-05-14 02:25:44 +00001808 if (!File) {
1809 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001810 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001811 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001812 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1813 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1814 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001815 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001816 HeaderInfo.AddSearchPath(DL, isAngled);
Taewook Oh755e4d22016-06-13 21:55:33 +00001817
Douglas Gregor11729f02011-11-30 18:12:06 +00001818 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001819 File = LookupFile(
1820 FilenameLoc,
1821 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1822 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001823 &SuggestedModule, /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001824 }
1825 }
1826 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001827
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001828 if (!SuppressIncludeNotFoundError) {
Taewook Oh755e4d22016-06-13 21:55:33 +00001829 // If the file could not be located and it was included via angle
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001830 // brackets, we can attempt a lookup as though it were a quoted path to
1831 // provide the user with a possible fixit.
1832 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001833 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001834 FilenameLoc,
1835 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1836 LookupFrom, LookupFromFile, CurDir,
1837 Callbacks ? &SearchPath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001838 Callbacks ? &RelativePath : nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001839 &SuggestedModule);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001840 if (File) {
1841 SourceRange Range(FilenameTok.getLocation(), CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001842 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1843 Filename <<
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001844 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1845 }
1846 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001847
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001848 // If the file is still not found, just go with the vanilla diagnostic
1849 if (!File)
Erik Verbruggen45449542016-10-25 10:13:10 +00001850 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename
1851 << FilenameRange;
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001852 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001853 }
1854
Richard Smith63b6fce2015-05-18 04:45:41 +00001855 // Should we enter the source file? Set to false if either the source file is
1856 // known to have no effect beyond its effect on module visibility -- that is,
1857 // if it's got an include guard that is already defined or is a modular header
1858 // we've imported or already built.
1859 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001860
Richard Smith63b6fce2015-05-18 04:45:41 +00001861 // Determine whether we should try to import the module for this #include, if
1862 // there is one. Don't do so if precompiled module support is disabled or we
1863 // are processing this module textually (because we're building the module).
1864 if (File && SuggestedModule && getLangOpts().Modules &&
1865 SuggestedModule.getModule()->getTopLevelModuleName() !=
Richard Smith7e82e012016-02-19 22:25:36 +00001866 getLangOpts().CurrentModule) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001867 // If this include corresponds to a module but that module is
1868 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001869 // FIXME: Remove this; loadModule does the same check (but produces
1870 // slightly worse diagnostics).
1871 if (!SuggestedModule.getModule()->isAvailable() &&
Richard Smith68935702016-04-12 20:20:33 +00001872 !SuggestedModule.getModule()
1873 ->getTopLevelModule()
1874 ->HasIncompatibleModuleFile) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001875 Module::Requirement Requirement;
1876 Module::UnresolvedHeaderDirective MissingHeader;
Sean Silva8b7c0392015-08-17 16:39:30 +00001877 Module *M = SuggestedModule.getModule();
1878 // Identify the cause.
1879 (void)M->isAvailable(getLangOpts(), getTargetInfo(), Requirement,
1880 MissingHeader);
1881 if (MissingHeader.FileNameLoc.isValid()) {
1882 Diag(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1883 << MissingHeader.IsUmbrella << MissingHeader.FileName;
1884 } else {
1885 Diag(M->DefinitionLoc, diag::err_module_unavailable)
1886 << M->getFullModuleName() << Requirement.second << Requirement.first;
1887 }
1888 Diag(FilenameTok.getLocation(),
1889 diag::note_implicit_top_level_module_import_here)
1890 << M->getTopLevelModuleName();
1891 return;
1892 }
1893
Douglas Gregor71944202011-11-30 00:36:36 +00001894 // Compute the module access path corresponding to this module.
1895 // FIXME: Should we have a second loadModule() overload to avoid this
1896 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001897 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001898 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001899 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1900 FilenameTok.getLocation()));
1901 std::reverse(Path.begin(), Path.end());
1902
Douglas Gregor41e115a2011-11-30 18:02:36 +00001903 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001904 // We only do this in Objective-C, where we have a module-import syntax.
1905 if (getLangOpts().ObjC2)
1906 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Taewook Oh755e4d22016-06-13 21:55:33 +00001907
Richard Smith10434f32015-05-02 02:08:26 +00001908 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001909 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001910 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1911 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001912 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1913 IncludeTok.getLocation(), Path, Module::Hidden,
1914 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001915 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001916 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001917
Richard Smith63b6fce2015-05-18 04:45:41 +00001918 if (Imported)
1919 ShouldEnter = false;
1920 else if (Imported.isMissingExpected()) {
1921 // We failed to find a submodule that we assumed would exist (because it
1922 // was in the directory of an umbrella header, for instance), but no
1923 // actual module exists for it (because the umbrella header is
1924 // incomplete). Treat this as a textual inclusion.
1925 SuggestedModule = ModuleMap::KnownHeader();
1926 } else {
1927 // We hit an error processing the import. Bail out.
1928 if (hadModuleLoaderFatalFailure()) {
1929 // With a fatal failure in the module loader, we abort parsing.
1930 Token &Result = IncludeTok;
1931 if (CurLexer) {
1932 Result.startToken();
1933 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1934 CurLexer->cutOffLexing();
1935 } else {
1936 assert(CurPTHLexer && "#include but no current lexer set!");
1937 CurPTHLexer->getEOF(Result);
1938 }
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001939 }
1940 return;
1941 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001942 }
1943
Richard Smith63b6fce2015-05-18 04:45:41 +00001944 if (Callbacks) {
1945 // Notify the callback object that we've seen an inclusion directive.
1946 Callbacks->InclusionDirective(
1947 HashLoc, IncludeTok,
1948 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1949 FilenameRange, File, SearchPath, RelativePath,
1950 ShouldEnter ? nullptr : SuggestedModule.getModule());
Douglas Gregor97eec242011-09-15 22:00:41 +00001951 }
Richard Smith63b6fce2015-05-18 04:45:41 +00001952
1953 if (!File)
1954 return;
Taewook Oh755e4d22016-06-13 21:55:33 +00001955
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001956 // The #included file will be considered to be a system header if either it is
1957 // in a system include directory, or if the #includer is a system include
1958 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001959 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001960 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001961 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001962
Richard Smith54ef4c32015-05-19 19:58:11 +00001963 // FIXME: If we have a suggested module, and we've already visited this file,
1964 // don't bother entering it again. We know it has no further effect.
1965
Taewook Ohf42103c2016-06-13 20:40:21 +00001966 // Issue a diagnostic if the name of the file on disk has a different case
1967 // than the one we're about to open.
1968 const bool CheckIncludePathPortability =
1969 File && !File->tryGetRealPathName().empty();
1970
1971 if (CheckIncludePathPortability) {
1972 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
1973 StringRef RealPathName = File->tryGetRealPathName();
1974 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
1975 llvm::sys::path::end(Name));
1976
1977 if (trySimplifyPath(Components, RealPathName)) {
1978 SmallString<128> Path;
1979 Path.reserve(Name.size()+2);
1980 Path.push_back(isAngled ? '<' : '"');
1981 for (auto Component : Components) {
1982 Path.append(Component);
1983 // Append the separator the user used, or the close quote
1984 Path.push_back(
1985 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
1986 (isAngled ? '>' : '"'));
1987 }
1988 auto Replacement = Path.str().str();
1989 // For user files and known standard headers, by default we issue a diagnostic.
1990 // For other system headers, we don't. They can be controlled separately.
1991 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
1992 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
1993 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1994 Diag(FilenameTok, DiagId) << Replacement <<
1995 FixItHint::CreateReplacement(Range, Replacement);
1996 }
1997 }
1998
Chris Lattner72286d62010-04-19 20:44:31 +00001999 // Ask HeaderInfo if we should enter this #include file. If not, #including
Richard Smith54ef4c32015-05-19 19:58:11 +00002000 // this file will have no effect.
Richard Smith63b6fce2015-05-18 04:45:41 +00002001 if (ShouldEnter &&
Richard Smith035f6dc2015-07-01 01:51:38 +00002002 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
2003 SuggestedModule.getModule())) {
Richard Smith63b6fce2015-05-18 04:45:41 +00002004 ShouldEnter = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00002005 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00002006 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Richard Smith63b6fce2015-05-18 04:45:41 +00002007 }
Richard Smithdbbc5232015-05-14 02:25:44 +00002008
Richard Smith63b6fce2015-05-18 04:45:41 +00002009 // If we don't need to enter the file, stop now.
2010 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00002011 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00002012 if (auto *M = SuggestedModule.getModule()) {
2013 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00002014
2015 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
2016 tok::pp___include_macros)
Richard Smitha0aafa32015-05-18 03:52:30 +00002017 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00002018 }
Chris Lattner72286d62010-04-19 20:44:31 +00002019 return;
2020 }
2021
Chris Lattnerf64b3522008-03-09 01:54:53 +00002022 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002023 SourceLocation IncludePos = End;
2024 // If the filename string was the result of macro expansions, set the include
2025 // position on the file where it will be included and after the expansions.
2026 if (IncludePos.isMacroID())
2027 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
2028 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002029 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002030
Richard Smith34f30512013-11-23 04:06:09 +00002031 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002032 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
2033 return;
Richard Smith34f30512013-11-23 04:06:09 +00002034
Richard Smitha0aafa32015-05-18 03:52:30 +00002035 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002036 if (auto *M = SuggestedModule.getModule()) {
Richard Smith67294e22014-01-31 20:47:44 +00002037 assert(!CurSubmodule && "should not have marked this as a module yet");
Richard Smitha0aafa32015-05-18 03:52:30 +00002038 CurSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002039
Richard Smitha0aafa32015-05-18 03:52:30 +00002040 // Let the macro handling code know that any future macros are within
2041 // the new submodule.
2042 EnterSubmodule(M, HashLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002043
Richard Smitha0aafa32015-05-18 03:52:30 +00002044 // Let the parser know that any future declarations are within the new
2045 // submodule.
2046 // FIXME: There's no point doing this if we're handling a #__include_macros
2047 // directive.
2048 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00002049 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002050}
2051
James Dennettf6333ac2012-06-22 05:46:07 +00002052/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002053///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002054void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2055 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002056 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002057
Chris Lattnerf64b3522008-03-09 01:54:53 +00002058 // #include_next is like #include, except that we start searching after
2059 // the current found directory. If we can't do this, issue a
2060 // diagnostic.
2061 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002062 const FileEntry *LookupFromFile = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002063 if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002064 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002065 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00002066 } else if (CurSubmodule) {
2067 // Start looking up in the directory *after* the one in which the current
2068 // file would be found, if any.
2069 assert(CurPPLexer && "#include_next directive in macro?");
2070 LookupFromFile = CurPPLexer->getFileEntry();
2071 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002072 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002073 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2074 } else {
2075 // Start looking up in the next directory.
2076 ++Lookup;
2077 }
Mike Stump11289f42009-09-09 15:08:12 +00002078
Richard Smith25d50752014-10-20 00:15:49 +00002079 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2080 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002081}
2082
James Dennettf6333ac2012-06-22 05:46:07 +00002083/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002084void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2085 // The Microsoft #import directive takes a type library and generates header
2086 // files from it, and includes those. This is beyond the scope of what clang
2087 // does, so we ignore it and error out. However, #import can optionally have
2088 // trailing attributes that span multiple lines. We're going to eat those
2089 // so we can continue processing from there.
2090 Diag(Tok, diag::err_pp_import_directive_ms );
2091
Taewook Oh755e4d22016-06-13 21:55:33 +00002092 // Read tokens until we get to the end of the directive. Note that the
Aaron Ballman0467f552012-03-18 03:10:37 +00002093 // directive can be split over multiple lines using the backslash character.
2094 DiscardUntilEndOfDirective();
2095}
2096
James Dennettf6333ac2012-06-22 05:46:07 +00002097/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002098///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002099void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2100 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00002101 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002102 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002103 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002104 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002105 }
Richard Smith25d50752014-10-20 00:15:49 +00002106 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002107}
2108
Chris Lattner58a1eb02009-04-08 18:46:40 +00002109/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2110/// pseudo directive in the predefines buffer. This handles it by sucking all
2111/// tokens through the preprocessor and discarding them (only keeping the side
2112/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002113void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2114 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002115 // This directive should only occur in the predefines buffer. If not, emit an
2116 // error and reject it.
2117 SourceLocation Loc = IncludeMacrosTok.getLocation();
Mehdi Amini99d1b292016-10-01 16:38:28 +00002118 if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002119 Diag(IncludeMacrosTok.getLocation(),
2120 diag::pp_include_macros_out_of_predefines);
2121 DiscardUntilEndOfDirective();
2122 return;
2123 }
Mike Stump11289f42009-09-09 15:08:12 +00002124
Chris Lattnere01d82b2009-04-08 20:53:24 +00002125 // Treat this as a normal #include for checking purposes. If this is
2126 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002127 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002128
Chris Lattnere01d82b2009-04-08 20:53:24 +00002129 Token TmpTok;
2130 do {
2131 Lex(TmpTok);
2132 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2133 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002134}
2135
Chris Lattnerf64b3522008-03-09 01:54:53 +00002136//===----------------------------------------------------------------------===//
2137// Preprocessor Macro Directive Handling.
2138//===----------------------------------------------------------------------===//
2139
2140/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
2141/// definition has just been read. Lex the rest of the arguments and the
2142/// closing ), updating MI with what we learn. Return true if an error occurs
2143/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002144bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002145 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00002146
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002147 while (true) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002148 LexUnexpandedToken(Tok);
2149 switch (Tok.getKind()) {
2150 case tok::r_paren:
2151 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00002152 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002153 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002154 // Otherwise we have #define FOO(A,)
2155 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2156 return true;
2157 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002158 if (!LangOpts.C99)
Taewook Oh755e4d22016-06-13 21:55:33 +00002159 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002160 diag::warn_cxx98_compat_variadic_macro :
2161 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002162
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002163 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2164 if (LangOpts.OpenCL) {
2165 Diag(Tok, diag::err_pp_opencl_variadic_macros);
2166 return true;
2167 }
2168
Chris Lattnerf64b3522008-03-09 01:54:53 +00002169 // Lex the token after the identifier.
2170 LexUnexpandedToken(Tok);
2171 if (Tok.isNot(tok::r_paren)) {
2172 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2173 return true;
2174 }
2175 // Add the __VA_ARGS__ identifier as an argument.
2176 Arguments.push_back(Ident__VA_ARGS__);
2177 MI->setIsC99Varargs();
Craig Topperd96b3f92015-10-22 04:59:52 +00002178 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002179 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002180 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002181 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2182 return true;
2183 default:
2184 // Handle keywords and identifiers here to accept things like
2185 // #define Foo(for) for.
2186 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002187 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002188 // #define X(1
2189 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2190 return true;
2191 }
2192
2193 // If this is already used as an argument, it is used multiple times (e.g.
2194 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00002195 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00002196 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002197 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002198 return true;
2199 }
Mike Stump11289f42009-09-09 15:08:12 +00002200
Chris Lattnerf64b3522008-03-09 01:54:53 +00002201 // Add the argument to the macro info.
2202 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002203
Chris Lattnerf64b3522008-03-09 01:54:53 +00002204 // Lex the token after the identifier.
2205 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002206
Chris Lattnerf64b3522008-03-09 01:54:53 +00002207 switch (Tok.getKind()) {
2208 default: // #define X(A B
2209 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2210 return true;
2211 case tok::r_paren: // #define X(A)
Craig Topperd96b3f92015-10-22 04:59:52 +00002212 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002213 return false;
2214 case tok::comma: // #define X(A,
2215 break;
2216 case tok::ellipsis: // #define X(A... -> GCC extension
2217 // Diagnose extension.
2218 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002219
Chris Lattnerf64b3522008-03-09 01:54:53 +00002220 // Lex the token after the identifier.
2221 LexUnexpandedToken(Tok);
2222 if (Tok.isNot(tok::r_paren)) {
2223 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2224 return true;
2225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
Chris Lattnerf64b3522008-03-09 01:54:53 +00002227 MI->setIsGNUVarargs();
Craig Topperd96b3f92015-10-22 04:59:52 +00002228 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002229 return false;
2230 }
2231 }
2232 }
2233}
2234
Serge Pavlov07c0f042014-12-18 11:14:21 +00002235static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2236 const LangOptions &LOptions) {
2237 if (MI->getNumTokens() == 1) {
2238 const Token &Value = MI->getReplacementToken(0);
2239
2240 // Macro that is identity, like '#define inline inline' is a valid pattern.
2241 if (MacroName.getKind() == Value.getKind())
2242 return true;
2243
2244 // Macro that maps a keyword to the same keyword decorated with leading/
2245 // trailing underscores is a valid pattern:
2246 // #define inline __inline
2247 // #define inline __inline__
2248 // #define inline _inline (in MS compatibility mode)
2249 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2250 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2251 if (!II->isKeyword(LOptions))
2252 return false;
2253 StringRef ValueText = II->getName();
2254 StringRef TrimmedValue = ValueText;
2255 if (!ValueText.startswith("__")) {
2256 if (ValueText.startswith("_"))
2257 TrimmedValue = TrimmedValue.drop_front(1);
2258 else
2259 return false;
2260 } else {
2261 TrimmedValue = TrimmedValue.drop_front(2);
2262 if (TrimmedValue.endswith("__"))
2263 TrimmedValue = TrimmedValue.drop_back(2);
2264 }
2265 return TrimmedValue.equals(MacroText);
2266 } else {
2267 return false;
2268 }
2269 }
2270
2271 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002272 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2273 tok::kw_const) &&
2274 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002275}
2276
James Dennettf6333ac2012-06-22 05:46:07 +00002277/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00002278/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002279void Preprocessor::HandleDefineDirective(Token &DefineTok,
2280 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002281 ++NumDefined;
2282
2283 Token MacroNameTok;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002284 bool MacroShadowsKeyword;
2285 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
Mike Stump11289f42009-09-09 15:08:12 +00002286
Chris Lattnerf64b3522008-03-09 01:54:53 +00002287 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002288 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002289 return;
2290
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002291 Token LastTok = MacroNameTok;
2292
Chris Lattnerf64b3522008-03-09 01:54:53 +00002293 // If we are supposed to keep comments in #defines, reenable comment saving
2294 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00002295 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00002296
Chris Lattnerf64b3522008-03-09 01:54:53 +00002297 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002298 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002299
Chris Lattnerf64b3522008-03-09 01:54:53 +00002300 Token Tok;
2301 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002302
Chris Lattnerf64b3522008-03-09 01:54:53 +00002303 // If this is a function-like macro definition, parse the argument list,
2304 // marking each of the identifiers as being used as macro arguments. Also,
2305 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002306 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002307 if (ImmediatelyAfterHeaderGuard) {
2308 // Save this macro information since it may part of a header guard.
2309 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2310 MacroNameTok.getLocation());
2311 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002312 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002313 } else if (Tok.hasLeadingSpace()) {
2314 // This is a normal token with leading space. Clear the leading space
2315 // marker on the first token to get proper expansion.
2316 Tok.clearFlag(Token::LeadingSpace);
2317 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002318 // This is a function-like macro definition. Read the argument list.
2319 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002320 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002321 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002322 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002323 DiscardUntilEndOfDirective();
2324 return;
2325 }
2326
Chris Lattner249c38b2009-04-19 18:26:34 +00002327 // If this is a definition of a variadic C99 function-like macro, not using
2328 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00002329
Chris Lattner249c38b2009-04-19 18:26:34 +00002330 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2331 // This gets unpoisoned where it is allowed.
2332 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2333 if (MI->isC99Varargs())
2334 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00002335
Chris Lattnerf64b3522008-03-09 01:54:53 +00002336 // Read the first token after the arg list for down below.
2337 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002338 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002339 // C99 requires whitespace between the macro definition and the body. Emit
2340 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002341 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002342 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002343 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2344 // first character of a replacement list is not a character required by
2345 // subclause 5.2.1, then there shall be white-space separation between the
2346 // identifier and the replacement list.". 5.2.1 lists this set:
2347 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2348 // is irrelevant here.
2349 bool isInvalid = false;
2350 if (Tok.is(tok::at)) // @ is not in the list above.
2351 isInvalid = true;
2352 else if (Tok.is(tok::unknown)) {
2353 // If we have an unknown token, it is something strange like "`". Since
2354 // all of valid characters would have lexed into a single character
2355 // token of some sort, we know this is not a valid case.
2356 isInvalid = true;
2357 }
2358 if (isInvalid)
2359 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2360 else
2361 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002362 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002363
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002364 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002365 LastTok = Tok;
2366
Chris Lattnerf64b3522008-03-09 01:54:53 +00002367 // Read the rest of the macro body.
2368 if (MI->isObjectLike()) {
2369 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002370 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002371 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002372 MI->AddTokenToBody(Tok);
2373 // Get the next token of the macro.
2374 LexUnexpandedToken(Tok);
2375 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002376 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002377 // Otherwise, read the body of a function-like macro. While we are at it,
2378 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2379 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002380 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002381 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002382
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002383 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002384 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002385
Chris Lattnerf64b3522008-03-09 01:54:53 +00002386 // Get the next token of the macro.
2387 LexUnexpandedToken(Tok);
2388 continue;
2389 }
Mike Stump11289f42009-09-09 15:08:12 +00002390
Richard Smith701a3522013-07-09 01:00:29 +00002391 // If we're in -traditional mode, then we should ignore stringification
2392 // and token pasting. Mark the tokens as unknown so as not to confuse
2393 // things.
2394 if (getLangOpts().TraditionalCPP) {
2395 Tok.setKind(tok::unknown);
2396 MI->AddTokenToBody(Tok);
2397
2398 // Get the next token of the macro.
2399 LexUnexpandedToken(Tok);
2400 continue;
2401 }
2402
Eli Friedman14d3c792012-11-14 02:18:46 +00002403 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002404 // If we see token pasting, check if it looks like the gcc comma
2405 // pasting extension. We'll use this information to suppress
2406 // diagnostics later on.
Taewook Oh755e4d22016-06-13 21:55:33 +00002407
Eli Friedman14d3c792012-11-14 02:18:46 +00002408 // Get the next token of the macro.
2409 LexUnexpandedToken(Tok);
2410
2411 if (Tok.is(tok::eod)) {
2412 MI->AddTokenToBody(LastTok);
2413 break;
2414 }
2415
2416 unsigned NumTokens = MI->getNumTokens();
2417 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2418 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2419 MI->setHasCommaPasting();
2420
David Majnemer76faf1f2013-11-05 09:30:17 +00002421 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002422 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002423 continue;
2424 }
2425
Chris Lattnerf64b3522008-03-09 01:54:53 +00002426 // Get the next token of the macro.
2427 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002428
Chris Lattner83bd8282009-05-25 17:16:10 +00002429 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002430 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002431 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2432
2433 // If this is assembler-with-cpp mode, we accept random gibberish after
2434 // the '#' because '#' is often a comment character. However, change
2435 // the kind of the token to tok::unknown so that the preprocessor isn't
2436 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002437 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002438 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002439 MI->AddTokenToBody(LastTok);
2440 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002441 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002442 Diag(Tok, diag::err_pp_stringize_not_parameter)
2443 << LastTok.is(tok::hashat);
Mike Stump11289f42009-09-09 15:08:12 +00002444
Chris Lattner83bd8282009-05-25 17:16:10 +00002445 // Disable __VA_ARGS__ again.
2446 Ident__VA_ARGS__->setIsPoisoned(true);
2447 return;
2448 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002449 }
Mike Stump11289f42009-09-09 15:08:12 +00002450
Chris Lattner83bd8282009-05-25 17:16:10 +00002451 // Things look ok, add the '#' and param name tokens to the macro.
2452 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002453 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002454 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002455
Chris Lattnerf64b3522008-03-09 01:54:53 +00002456 // Get the next token of the macro.
2457 LexUnexpandedToken(Tok);
2458 }
2459 }
Mike Stump11289f42009-09-09 15:08:12 +00002460
Serge Pavlov07c0f042014-12-18 11:14:21 +00002461 if (MacroShadowsKeyword &&
2462 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2463 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2464 }
Mike Stump11289f42009-09-09 15:08:12 +00002465
Chris Lattnerf64b3522008-03-09 01:54:53 +00002466 // Disable __VA_ARGS__ again.
2467 Ident__VA_ARGS__->setIsPoisoned(true);
2468
Chris Lattner57540c52011-04-15 05:22:18 +00002469 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002470 // replacement list.
2471 unsigned NumTokens = MI->getNumTokens();
2472 if (NumTokens != 0) {
2473 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2474 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002475 return;
2476 }
2477 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2478 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002479 return;
2480 }
2481 }
Mike Stump11289f42009-09-09 15:08:12 +00002482
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002483 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002484
Chris Lattnerf64b3522008-03-09 01:54:53 +00002485 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002486 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002487 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002488 // In Objective-C, ignore attempts to directly redefine the builtin
2489 // definitions of the ownership qualifiers. It's still possible to
2490 // #undef them.
2491 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2492 return II->isStr("__strong") ||
2493 II->isStr("__weak") ||
2494 II->isStr("__unsafe_unretained") ||
2495 II->isStr("__autoreleasing");
2496 };
2497 if (getLangOpts().ObjC1 &&
2498 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2499 == getPredefinesFileID() &&
2500 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2501 // Warn if it changes the tokens.
2502 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2503 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2504 !MI->isIdenticalTo(*OtherMI, *this,
2505 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2506 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2507 }
2508 assert(!OtherMI->isWarnIfUnused());
2509 return;
2510 }
2511
Chris Lattner5244f342009-01-16 19:50:11 +00002512 // It is very common for system headers to have tons of macro redefinitions
2513 // and for warnings to be disabled in system headers. If this is the case,
2514 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002515 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002516 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002517 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002518 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002519
Taewook Oh755e4d22016-06-13 21:55:33 +00002520 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
Richard Smith7b242542013-03-06 00:46:00 +00002521 // C++ [cpp.predefined]p4, but allow it as an extension.
2522 if (OtherMI->isBuiltinMacro())
2523 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002524 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002525 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002526 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002527 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002528 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2529 << MacroNameTok.getIdentifierInfo();
2530 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2531 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002532 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002533 if (OtherMI->isWarnIfUnused())
2534 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002535 }
Mike Stump11289f42009-09-09 15:08:12 +00002536
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002537 DefMacroDirective *MD =
2538 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002539
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002540 assert(!MI->isUsed());
2541 // If we need warning for not using the macro, add its location in the
2542 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002543 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002544 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002545 MI->setIsWarnIfUnused(true);
2546 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2547 }
2548
Chris Lattner928e9092009-04-12 01:39:54 +00002549 // If the callbacks want to know, tell them about the macro definition.
2550 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002551 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002552}
2553
James Dennettf6333ac2012-06-22 05:46:07 +00002554/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002555///
2556void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2557 ++NumUndefined;
2558
2559 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002560 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002561
Chris Lattnerf64b3522008-03-09 01:54:53 +00002562 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002563 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002564 return;
Mike Stump11289f42009-09-09 15:08:12 +00002565
Chris Lattnerf64b3522008-03-09 01:54:53 +00002566 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002567 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002568
Richard Smith20e883e2015-04-29 23:20:19 +00002569 // Okay, we have a valid identifier to undef.
2570 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002571 auto MD = getMacroDefinition(II);
Mike Stump11289f42009-09-09 15:08:12 +00002572
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002573 // If the callbacks want to know, tell them about the macro #undef.
2574 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002575 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002576 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002577
Chris Lattnerf64b3522008-03-09 01:54:53 +00002578 // If the macro is not defined, this is a noop undef, just return.
Richard Smith36bd40d2015-05-04 03:15:40 +00002579 const MacroInfo *MI = MD.getMacroInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002580 if (!MI)
2581 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002582
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002583 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002584 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002585
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002586 if (MI->isWarnIfUnused())
2587 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2588
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002589 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2590 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002591}
2592
Chris Lattnerf64b3522008-03-09 01:54:53 +00002593//===----------------------------------------------------------------------===//
2594// Preprocessor Conditional Directive Handling.
2595//===----------------------------------------------------------------------===//
2596
James Dennettf6333ac2012-06-22 05:46:07 +00002597/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2598/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2599/// true if any tokens have been returned or pp-directives activated before this
2600/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002601///
2602void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2603 bool ReadAnyTokensBeforeDirective) {
2604 ++NumIf;
2605 Token DirectiveTok = Result;
2606
2607 Token MacroNameTok;
2608 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002609
Chris Lattnerf64b3522008-03-09 01:54:53 +00002610 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002611 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002612 // Skip code until we get to #endif. This helps with recovery by not
2613 // emitting an error when the #endif is reached.
2614 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2615 /*Foundnonskip*/false, /*FoundElse*/false);
2616 return;
2617 }
Mike Stump11289f42009-09-09 15:08:12 +00002618
Chris Lattnerf64b3522008-03-09 01:54:53 +00002619 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002620 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002621
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002622 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002623 auto MD = getMacroDefinition(MII);
2624 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002625
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002626 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002627 // If the start of a top-level #ifdef and if the macro is not defined,
2628 // inform MIOpt that this might be the start of a proper include guard.
2629 // Otherwise it is some other form of unknown conditional which we can't
2630 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002631 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002632 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002633 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002634 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002635 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002636 }
2637
Chris Lattnerf64b3522008-03-09 01:54:53 +00002638 // If there is a macro, process it.
2639 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002640 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002641
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002642 if (Callbacks) {
2643 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002644 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002645 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002646 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002647 }
2648
Chris Lattnerf64b3522008-03-09 01:54:53 +00002649 // Should we include the stuff contained by this directive?
2650 if (!MI == isIfndef) {
2651 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002652 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2653 /*wasskip*/false, /*foundnonskip*/true,
2654 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002655 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002656 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002657 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002658 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002659 /*FoundElse*/false);
2660 }
2661}
2662
James Dennettf6333ac2012-06-22 05:46:07 +00002663/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002664///
2665void Preprocessor::HandleIfDirective(Token &IfToken,
2666 bool ReadAnyTokensBeforeDirective) {
2667 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002668
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002669 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002670 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002671 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2672 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2673 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002674
2675 // If this condition is equivalent to #ifndef X, and if this is the first
2676 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002677 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002678 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002679 // FIXME: Pass in the location of the macro name, not the 'if' token.
2680 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002681 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002682 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002683 }
2684
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002685 if (Callbacks)
2686 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002687 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002688 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002689
Chris Lattnerf64b3522008-03-09 01:54:53 +00002690 // Should we include the stuff contained by this directive?
2691 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002692 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002693 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002694 /*foundnonskip*/true, /*foundelse*/false);
2695 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002696 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002697 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002698 /*FoundElse*/false);
2699 }
2700}
2701
James Dennettf6333ac2012-06-22 05:46:07 +00002702/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002703///
2704void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2705 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002706
Chris Lattnerf64b3522008-03-09 01:54:53 +00002707 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002708 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002709
Chris Lattnerf64b3522008-03-09 01:54:53 +00002710 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002711 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002712 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002713 Diag(EndifToken, diag::err_pp_endif_without_if);
2714 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002715 }
Mike Stump11289f42009-09-09 15:08:12 +00002716
Chris Lattnerf64b3522008-03-09 01:54:53 +00002717 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002718 if (CurPPLexer->getConditionalStackDepth() == 0)
2719 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002720
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002721 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002722 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002723
2724 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002725 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002726}
2727
James Dennettf6333ac2012-06-22 05:46:07 +00002728/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002729///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002730void Preprocessor::HandleElseDirective(Token &Result) {
2731 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002732
Chris Lattnerf64b3522008-03-09 01:54:53 +00002733 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002734 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002735
Chris Lattnerf64b3522008-03-09 01:54:53 +00002736 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002737 if (CurPPLexer->popConditionalLevel(CI)) {
2738 Diag(Result, diag::pp_err_else_without_if);
2739 return;
2740 }
Mike Stump11289f42009-09-09 15:08:12 +00002741
Chris Lattnerf64b3522008-03-09 01:54:53 +00002742 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002743 if (CurPPLexer->getConditionalStackDepth() == 0)
2744 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002745
2746 // If this is a #else with a #else before it, report the error.
2747 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002748
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002749 if (Callbacks)
2750 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2751
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002752 // Finally, skip the rest of the contents of this block.
2753 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002754 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002755}
2756
James Dennettf6333ac2012-06-22 05:46:07 +00002757/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002758///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002759void Preprocessor::HandleElifDirective(Token &ElifToken) {
2760 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002761
Chris Lattnerf64b3522008-03-09 01:54:53 +00002762 // #elif directive in a non-skipping conditional... start skipping.
2763 // We don't care what the condition is, because we will always skip it (since
2764 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002765 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002766 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002767 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002768
2769 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002770 if (CurPPLexer->popConditionalLevel(CI)) {
2771 Diag(ElifToken, diag::pp_err_elif_without_if);
2772 return;
2773 }
Mike Stump11289f42009-09-09 15:08:12 +00002774
Chris Lattnerf64b3522008-03-09 01:54:53 +00002775 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002776 if (CurPPLexer->getConditionalStackDepth() == 0)
2777 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002778
Chris Lattnerf64b3522008-03-09 01:54:53 +00002779 // If this is a #elif with a #else before it, report the error.
2780 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Taewook Oh755e4d22016-06-13 21:55:33 +00002781
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002782 if (Callbacks)
2783 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002784 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002785 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002786
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002787 // Finally, skip the rest of the contents of this block.
2788 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002789 /*FoundElse*/CI.FoundElse,
2790 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002791}