blob: 8379ca8719c1b42cf0503967118622dce450d9ee [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-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 Dennettdc201692012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattner141e71f2008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner6e290142009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/LexDiagnostic.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/ModuleLoader.h"
24#include "clang/Lex/Pragma.h"
Chris Lattner359cc442009-01-26 05:29:08 +000025#include "llvm/ADT/APInt.h"
Douglas Gregore3a82562011-11-30 18:02:36 +000026#include "llvm/Support/ErrorHandling.h"
Aaron Ballman31672b12013-01-16 19:32:21 +000027#include "llvm/Support/SaveAndRestore.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000028using namespace clang;
29
30//===----------------------------------------------------------------------===//
31// Utility Methods for Preprocessor Directive Handling.
32//===----------------------------------------------------------------------===//
33
Chris Lattnerf47724b2010-08-17 15:55:45 +000034MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenek9714a232010-10-19 22:15:20 +000035 MacroInfoChain *MIChain;
Mike Stump1eb44332009-09-09 15:08:12 +000036
Ted Kremenek9714a232010-10-19 22:15:20 +000037 if (MICache) {
38 MIChain = MICache;
39 MICache = MICache->Next;
Ted Kremenekaf8fa252010-10-19 18:16:54 +000040 }
Ted Kremenek9714a232010-10-19 22:15:20 +000041 else {
42 MIChain = BP.Allocate<MacroInfoChain>();
43 }
44
45 MIChain->Next = MIChainHead;
46 MIChain->Prev = 0;
47 if (MIChainHead)
48 MIChainHead->Prev = MIChain;
49 MIChainHead = MIChain;
50
51 return &(MIChain->MI);
Chris Lattnerf47724b2010-08-17 15:55:45 +000052}
53
54MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
55 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000056 new (MI) MacroInfo(L);
57 return MI;
58}
59
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000060MacroDirective *Preprocessor::AllocateMacroDirective(MacroInfo *MI,
61 SourceLocation Loc,
62 bool isImported) {
63 MacroDirective *MD = BP.Allocate<MacroDirective>();
64 new (MD) MacroDirective(MI, Loc, isImported);
65 return MD;
Chris Lattnerf47724b2010-08-17 15:55:45 +000066}
67
James Dennettdc201692012-06-22 05:46:07 +000068/// \brief Release the specified MacroInfo to be reused for allocating
69/// new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000070void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenek9714a232010-10-19 22:15:20 +000071 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
72 if (MacroInfoChain *Prev = MIChain->Prev) {
73 MacroInfoChain *Next = MIChain->Next;
74 Prev->Next = Next;
75 if (Next)
76 Next->Prev = Prev;
77 }
78 else {
79 assert(MIChainHead == MIChain);
80 MIChainHead = MIChain->Next;
81 MIChainHead->Prev = 0;
82 }
83 MIChain->Next = MICache;
84 MICache = MIChain;
Chris Lattner0301b3f2009-02-20 22:19:20 +000085
Ted Kremenek9714a232010-10-19 22:15:20 +000086 MI->Destroy();
87}
Chris Lattner0301b3f2009-02-20 22:19:20 +000088
James Dennettdc201692012-06-22 05:46:07 +000089/// \brief Read and discard all tokens remaining on the current line until
90/// the tok::eod token is found.
Chris Lattner141e71f2008-03-09 01:54:53 +000091void Preprocessor::DiscardUntilEndOfDirective() {
92 Token Tmp;
93 do {
94 LexUnexpandedToken(Tmp);
Peter Collingbournea5ef5842011-02-22 13:49:06 +000095 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne84021552011-02-28 02:37:51 +000096 } while (Tmp.isNot(tok::eod));
Chris Lattner141e71f2008-03-09 01:54:53 +000097}
98
James Dennettdc201692012-06-22 05:46:07 +000099/// \brief Lex and validate a macro name, which occurs after a
100/// \#define or \#undef.
101///
102/// This sets the token kind to eod and discards the rest
103/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
104/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
105/// else (e.g. \#ifdef).
Chris Lattner141e71f2008-03-09 01:54:53 +0000106void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
107 // Read the token, don't allow macro expansion on it.
108 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000110 if (MacroNameTok.is(tok::code_completion)) {
111 if (CodeComplete)
112 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000113 setCodeCompletionReached();
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000114 LexUnexpandedToken(MacroNameTok);
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000115 }
116
Chris Lattner141e71f2008-03-09 01:54:53 +0000117 // Missing macro name?
Peter Collingbourne84021552011-02-28 02:37:51 +0000118 if (MacroNameTok.is(tok::eod)) {
Chris Lattner3692b092008-11-18 07:59:24 +0000119 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
120 return;
121 }
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Chris Lattner141e71f2008-03-09 01:54:53 +0000123 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
124 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +0000125 bool Invalid = false;
126 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
127 if (Invalid)
128 return;
Nico Weberf4fb07e2012-02-29 22:54:43 +0000129
Chris Lattner9485d232008-12-13 20:12:40 +0000130 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weberf4fb07e2012-02-29 22:54:43 +0000131
132 // Allow #defining |and| and friends in microsoft mode.
David Blaikie4e4d0842012-03-11 07:00:24 +0000133 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weberf4fb07e2012-02-29 22:54:43 +0000134 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
135 return;
136 }
137
Chris Lattner9485d232008-12-13 20:12:40 +0000138 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000139 // C++ 2.5p2: Alternative tokens behave the same as its primary token
140 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000141 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +0000142 else
143 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
144 // Fall through on error.
145 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Richard Smitheed55e62013-03-06 00:46:00 +0000146 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
Chris Lattner141e71f2008-03-09 01:54:53 +0000147 Diag(MacroNameTok, diag::err_defined_macro_name);
Richard Smitheed55e62013-03-06 00:46:00 +0000148 } else if (isDefineUndef == 2 && II->hasMacroDefinition() &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000149 getMacroInfo(II)->isBuiltinMacro()) {
Richard Smitheed55e62013-03-06 00:46:00 +0000150 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
151 // and C++ [cpp.predefined]p4], but allow it as an extension.
152 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
153 return;
Chris Lattner141e71f2008-03-09 01:54:53 +0000154 } else {
155 // Okay, we got a good identifier node. Return it.
156 return;
157 }
Mike Stump1eb44332009-09-09 15:08:12 +0000158
Chris Lattner141e71f2008-03-09 01:54:53 +0000159 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne84021552011-02-28 02:37:51 +0000160 // token kind to tok::eod.
161 MacroNameTok.setKind(tok::eod);
Chris Lattner141e71f2008-03-09 01:54:53 +0000162 return DiscardUntilEndOfDirective();
163}
164
James Dennettdc201692012-06-22 05:46:07 +0000165/// \brief Ensure that the next token is a tok::eod token.
166///
167/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattnerab82f412009-04-17 23:30:53 +0000168/// true, then we consider macros that expand to zero tokens as being ok.
169void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000170 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000171 // Lex unexpanded tokens for most directives: macros might expand to zero
172 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
173 // #line) allow empty macros.
174 if (EnableMacros)
175 Lex(Tmp);
176 else
177 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Chris Lattner141e71f2008-03-09 01:54:53 +0000179 // There should be no tokens after the directive, but we allow them as an
180 // extension.
181 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
182 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Peter Collingbourne84021552011-02-28 02:37:51 +0000184 if (Tmp.isNot(tok::eod)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000185 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000186 // or if this is a macro-style preprocessing directive, because it is more
187 // trouble than it is worth to insert /**/ and check that there is no /**/
188 // in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000189 FixItHint Hint;
David Blaikie4e4d0842012-03-11 07:00:24 +0000190 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000191 !CurTokenLexer)
Douglas Gregor849b2432010-03-31 17:46:05 +0000192 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
193 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000194 DiscardUntilEndOfDirective();
195 }
196}
197
198
199
James Dennettdc201692012-06-22 05:46:07 +0000200/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
201/// decided that the subsequent tokens are in the \#if'd out portion of the
202/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattner141e71f2008-03-09 01:54:53 +0000203/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettdc201692012-06-22 05:46:07 +0000204/// this \#if directive, so \#else/\#elif blocks should never be entered.
205/// If ElseOk is true, then \#else directives are ok, if not, then we have
206/// already seen one so a \#else directive is a duplicate. When this returns,
207/// the caller can lex the first valid token.
Chris Lattner141e71f2008-03-09 01:54:53 +0000208void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
209 bool FoundNonSkipPortion,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000210 bool FoundElse,
211 SourceLocation ElseLoc) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000212 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000213 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000214
Ted Kremenek60e45d42008-11-18 00:34:22 +0000215 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000216 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Ted Kremenek268ee702008-12-12 18:34:08 +0000218 if (CurPTHLexer) {
219 PTHSkipExcludedConditionalBlock();
220 return;
221 }
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattner141e71f2008-03-09 01:54:53 +0000223 // Enter raw mode to disable identifier lookup (and thus macro expansion),
224 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000225 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000226 Token Tok;
227 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000228 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Douglas Gregorf44e8542010-08-24 19:08:16 +0000230 if (Tok.is(tok::code_completion)) {
231 if (CodeComplete)
232 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000233 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000234 continue;
235 }
236
Chris Lattner141e71f2008-03-09 01:54:53 +0000237 // If this is the end of the buffer, we have an error.
238 if (Tok.is(tok::eof)) {
239 // Emit errors for each unterminated conditional on the stack, including
240 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000241 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000242 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000243 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
244 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000245 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000246 }
247
Chris Lattner141e71f2008-03-09 01:54:53 +0000248 // Just return and let the caller lex after this #include.
249 break;
250 }
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattner141e71f2008-03-09 01:54:53 +0000252 // If this token is not a preprocessor directive, just skip it.
253 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
254 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Chris Lattner141e71f2008-03-09 01:54:53 +0000256 // We just parsed a # character at the start of a line, so we're in
257 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne84021552011-02-28 02:37:51 +0000258 // converted into an EOD token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000259 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosec7d1ca52013-02-22 00:32:00 +0000260 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000261
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Chris Lattner141e71f2008-03-09 01:54:53 +0000263 // Read the next token, the directive flavor.
264 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Chris Lattner141e71f2008-03-09 01:54:53 +0000266 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
267 // something bogus), skip it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000268 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000269 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000270 // Restore comment saving mode.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000271 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattner141e71f2008-03-09 01:54:53 +0000272 continue;
273 }
274
275 // If the first letter isn't i or e, it isn't intesting to us. We know that
276 // this is safe in the face of spelling differences, because there is no way
277 // to spell an i/e in a strange way that is another letter. Skipping this
278 // allows us to avoid looking up the identifier info for #define/#undef and
279 // other common directives.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000280 const char *RawCharData = Tok.getRawIdentifierData();
281
Chris Lattner141e71f2008-03-09 01:54:53 +0000282 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000283 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000284 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000285 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000286 // Restore comment saving mode.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000287 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattner141e71f2008-03-09 01:54:53 +0000288 continue;
289 }
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattner141e71f2008-03-09 01:54:53 +0000291 // Get the identifier name without trigraphs or embedded newlines. Note
292 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
293 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000294 char DirectiveBuf[20];
Chris Lattner5f9e2722011-07-23 10:55:15 +0000295 StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000296 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000297 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000298 } else {
299 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000300 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000301 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000302 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 // Restore comment saving mode.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000304 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattner141e71f2008-03-09 01:54:53 +0000305 continue;
306 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000307 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000308 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000309 }
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000311 if (Directive.startswith("if")) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000312 StringRef Sub = Directive.substr(2);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000313 if (Sub.empty() || // "if"
314 Sub == "def" || // "ifdef"
315 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000316 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
317 // bother parsing the condition.
318 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000319 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000320 /*foundnonskip*/false,
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000321 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000322 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000323 } else if (Directive[0] == 'e') {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000324 StringRef Sub = Directive.substr(1);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000325 if (Sub == "ndif") { // "endif"
Chris Lattner141e71f2008-03-09 01:54:53 +0000326 PPConditionalInfo CondInfo;
327 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000328 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000329 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattner141e71f2008-03-09 01:54:53 +0000330 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattner141e71f2008-03-09 01:54:53 +0000332 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000333 if (!CondInfo.WasSkipping) {
Richard Smithbc9e5582012-06-24 23:56:26 +0000334 // Restore the value of LexingRawMode so that trailing comments
335 // are handled correctly, if we've reached the outermost block.
336 CurPPLexer->LexingRawMode = false;
Richard Smith986f3172012-06-21 00:35:03 +0000337 CheckEndOfDirective("endif");
Richard Smithbc9e5582012-06-24 23:56:26 +0000338 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000339 if (Callbacks)
340 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000341 break;
Richard Smith986f3172012-06-21 00:35:03 +0000342 } else {
343 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000344 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000345 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000346 // #else directive in a skipping conditional. If not in some other
347 // skipping conditional, and if #else hasn't already been seen, enter it
348 // as a non-skipping conditional.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000349 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Chris Lattner141e71f2008-03-09 01:54:53 +0000351 // If this is a #else with a #else before it, report the error.
352 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Chris Lattner141e71f2008-03-09 01:54:53 +0000354 // Note that we've seen a #else in this conditional.
355 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Chris Lattner141e71f2008-03-09 01:54:53 +0000357 // If the conditional is at the top level, and the #if block wasn't
358 // entered, enter the #else block now.
359 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
360 CondInfo.FoundNonSkip = true;
Richard Smithbc9e5582012-06-24 23:56:26 +0000361 // Restore the value of LexingRawMode so that trailing comments
362 // are handled correctly.
363 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000364 CheckEndOfDirective("else");
Richard Smithbc9e5582012-06-24 23:56:26 +0000365 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000366 if (Callbacks)
367 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000368 break;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000369 } else {
370 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattner141e71f2008-03-09 01:54:53 +0000371 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000372 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000373 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000374
375 bool ShouldEnter;
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000376 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +0000377 // If this is in a skipping block or if we're already handled this #if
378 // block, don't bother parsing the condition.
379 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
380 DiscardUntilEndOfDirective();
381 ShouldEnter = false;
382 } else {
383 // Restore the value of LexingRawMode so that identifiers are
384 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000385 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
386 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000387 IdentifierInfo *IfNDefMacro = 0;
388 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000389 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000390 }
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000391 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Chris Lattner141e71f2008-03-09 01:54:53 +0000393 // If this is a #elif with a #else before it, report the error.
394 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Chris Lattner141e71f2008-03-09 01:54:53 +0000396 // If this condition is true, enter it!
397 if (ShouldEnter) {
398 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000399 if (Callbacks)
400 Callbacks->Elif(Tok.getLocation(),
401 SourceRange(ConditionalBegin, ConditionalEnd),
402 CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000403 break;
404 }
405 }
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Ted Kremenek60e45d42008-11-18 00:34:22 +0000408 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000409 // Restore comment saving mode.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000410 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattner141e71f2008-03-09 01:54:53 +0000411 }
412
413 // Finally, if we are out of the conditional (saw an #endif or ran off the end
414 // of the file, just stop skipping and return to lexing whatever came after
415 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000416 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000417
418 if (Callbacks) {
419 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
420 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
421 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000422}
423
Ted Kremenek268ee702008-12-12 18:34:08 +0000424void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000425
426 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000427 assert(CurPTHLexer);
428 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Ted Kremenek268ee702008-12-12 18:34:08 +0000430 // Skip to the next '#else', '#elif', or #endif.
431 if (CurPTHLexer->SkipBlock()) {
432 // We have reached an #endif. Both the '#' and 'endif' tokens
433 // have been consumed by the PTHLexer. Just pop off the condition level.
434 PPConditionalInfo CondInfo;
435 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000436 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek268ee702008-12-12 18:34:08 +0000437 assert(!InCond && "Can't be skipping if not in a conditional!");
438 break;
439 }
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Ted Kremenek268ee702008-12-12 18:34:08 +0000441 // We have reached a '#else' or '#elif'. Lex the next token to get
442 // the directive flavor.
443 Token Tok;
444 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Ted Kremenek268ee702008-12-12 18:34:08 +0000446 // We can actually look up the IdentifierInfo here since we aren't in
447 // raw mode.
448 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
449
450 if (K == tok::pp_else) {
451 // #else: Enter the else condition. We aren't in a nested condition
452 // since we skip those. We're always in the one matching the last
453 // blocked we skipped.
454 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
455 // Note that we've seen a #else in this conditional.
456 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Ted Kremenek268ee702008-12-12 18:34:08 +0000458 // If the #if block wasn't entered then enter the #else block now.
459 if (!CondInfo.FoundNonSkip) {
460 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Peter Collingbourne84021552011-02-28 02:37:51 +0000462 // Scan until the eod token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000463 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000464 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000465 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Ted Kremenek268ee702008-12-12 18:34:08 +0000467 break;
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Ted Kremenek268ee702008-12-12 18:34:08 +0000470 // Otherwise skip this block.
471 continue;
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Ted Kremenek268ee702008-12-12 18:34:08 +0000474 assert(K == tok::pp_elif);
475 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
476
477 // If this is a #elif with a #else before it, report the error.
478 if (CondInfo.FoundElse)
479 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Ted Kremenek268ee702008-12-12 18:34:08 +0000481 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000482 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000483 if (CondInfo.FoundNonSkip)
484 continue;
485
486 // Evaluate the condition of the #elif.
487 IdentifierInfo *IfNDefMacro = 0;
488 CurPTHLexer->ParsingPreprocessorDirective = true;
489 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
490 CurPTHLexer->ParsingPreprocessorDirective = false;
491
492 // If this condition is true, enter it!
493 if (ShouldEnter) {
494 CondInfo.FoundNonSkip = true;
495 break;
496 }
497
498 // Otherwise, skip this block and go to the next one.
499 continue;
500 }
501}
502
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000503const FileEntry *Preprocessor::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000504 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000505 bool isAngled,
506 const DirectoryLookup *FromDir,
507 const DirectoryLookup *&CurDir,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000508 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000509 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000510 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000511 bool SkipCache) {
Chris Lattner10725092008-03-09 04:17:44 +0000512 // If the header lookup mechanism may be relative to the current file, pass in
513 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000514 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000515 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000516 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000517 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000519 // If there is no file entry associated with this file, it must be the
520 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000521 // it won't be scanned for preprocessor directives. If we have the
522 // predefines buffer, resolve #include references (which come from the
523 // -include command line argument) as if they came from the main file, this
524 // affects file lookup etc.
525 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000526 FID = SourceMgr.getMainFileID();
527 CurFileEnt = SourceMgr.getFileEntryForID(FID);
528 }
Chris Lattner10725092008-03-09 04:17:44 +0000529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner10725092008-03-09 04:17:44 +0000531 // Do a standard file entry lookup.
532 CurDir = CurDirLookup;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000533 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +0000534 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000535 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000536 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattner10725092008-03-09 04:17:44 +0000538 // Otherwise, see if this is a subframework header. If so, this is relative
539 // to one of the headers on the #include stack. Walk the list of the current
540 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000541 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000542 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000543 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregor1b58c742013-02-08 00:10:48 +0000544 SearchPath, RelativePath,
545 SuggestedModule)))
Chris Lattner10725092008-03-09 04:17:44 +0000546 return FE;
547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chris Lattner10725092008-03-09 04:17:44 +0000549 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
550 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000551 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000552 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000553 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek74124942011-04-26 21:50:03 +0000554 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregor1b58c742013-02-08 00:10:48 +0000555 Filename, CurFileEnt, SearchPath, RelativePath,
556 SuggestedModule)))
Chris Lattner10725092008-03-09 04:17:44 +0000557 return FE;
558 }
559 }
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Chris Lattner10725092008-03-09 04:17:44 +0000561 // Otherwise, we really couldn't find the file.
562 return 0;
563}
564
Chris Lattner141e71f2008-03-09 01:54:53 +0000565
566//===----------------------------------------------------------------------===//
567// Preprocessor Directive Handling.
568//===----------------------------------------------------------------------===//
569
David Blaikie8c0b3782012-06-06 18:52:13 +0000570class Preprocessor::ResetMacroExpansionHelper {
571public:
572 ResetMacroExpansionHelper(Preprocessor *pp)
573 : PP(pp), save(pp->DisableMacroExpansion) {
574 if (pp->MacroExpansionInDirectivesOverride)
575 pp->DisableMacroExpansion = false;
576 }
577 ~ResetMacroExpansionHelper() {
578 PP->DisableMacroExpansion = save;
579 }
580private:
581 Preprocessor *PP;
582 bool save;
583};
584
Chris Lattner141e71f2008-03-09 01:54:53 +0000585/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000586/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000587/// lexer/preprocessor state, and advances the lexer(s) so that the next token
588/// read is the correct one.
589void Preprocessor::HandleDirective(Token &Result) {
590 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattner141e71f2008-03-09 01:54:53 +0000592 // We just parsed a # character at the start of a line, so we're in directive
593 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne84021552011-02-28 02:37:51 +0000594 // EOD token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000595 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose6aad4a32013-02-21 18:53:19 +0000596 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Chris Lattner141e71f2008-03-09 01:54:53 +0000598 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000599
Chris Lattner141e71f2008-03-09 01:54:53 +0000600 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000601 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000602 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000603 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Chris Lattner42aa16c2009-03-18 21:00:25 +0000605 // Save the '#' token in case we need to return it later.
606 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Chris Lattner141e71f2008-03-09 01:54:53 +0000608 // Read the next token, the directive flavor. This isn't expanded due to
609 // C99 6.10.3p8.
610 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Chris Lattner141e71f2008-03-09 01:54:53 +0000612 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
613 // #define A(x) #x
614 // A(abc
615 // #warning blah
616 // def)
Richard Smitha3ca4d62011-12-16 22:50:01 +0000617 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
618 // not support this for #include-like directives, since that can result in
619 // terrible diagnostics, and does not work in GCC.
620 if (InMacroArgs) {
621 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
622 switch (II->getPPKeywordID()) {
623 case tok::pp_include:
624 case tok::pp_import:
625 case tok::pp_include_next:
626 case tok::pp___include_macros:
627 Diag(Result, diag::err_embedded_include) << II->getName();
628 DiscardUntilEndOfDirective();
629 return;
630 default:
631 break;
632 }
633 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000634 Diag(Result, diag::ext_embedded_directive);
Richard Smitha3ca4d62011-12-16 22:50:01 +0000635 }
Mike Stump1eb44332009-09-09 15:08:12 +0000636
David Blaikie8c0b3782012-06-06 18:52:13 +0000637 // Temporarily enable macro expansion if set so
638 // and reset to previous state when returning from this function.
639 ResetMacroExpansionHelper helper(this);
640
Chris Lattner141e71f2008-03-09 01:54:53 +0000641 switch (Result.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000642 case tok::eod:
Chris Lattner141e71f2008-03-09 01:54:53 +0000643 return; // null directive.
Douglas Gregorf44e8542010-08-24 19:08:16 +0000644 case tok::code_completion:
645 if (CodeComplete)
646 CodeComplete->CodeCompleteDirective(
647 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000648 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000649 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000650 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikie4e4d0842012-03-11 07:00:24 +0000651 if (getLangOpts().AsmPreprocessor)
Chris Lattner5f607c42009-03-18 20:41:10 +0000652 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000653 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000654 default:
655 IdentifierInfo *II = Result.getIdentifierInfo();
656 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattner141e71f2008-03-09 01:54:53 +0000658 // Ask what the preprocessor keyword ID is.
659 switch (II->getPPKeywordID()) {
660 default: break;
661 // C99 6.10.1 - Conditional Inclusion.
662 case tok::pp_if:
663 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
664 case tok::pp_ifdef:
665 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
666 case tok::pp_ifndef:
667 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
668 case tok::pp_elif:
669 return HandleElifDirective(Result);
670 case tok::pp_else:
671 return HandleElseDirective(Result);
672 case tok::pp_endif:
673 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Chris Lattner141e71f2008-03-09 01:54:53 +0000675 // C99 6.10.2 - Source File Inclusion.
676 case tok::pp_include:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000677 // Handle #include.
678 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000679 case tok::pp___include_macros:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000680 // Handle -imacros.
681 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Chris Lattner141e71f2008-03-09 01:54:53 +0000683 // C99 6.10.3 - Macro Replacement.
684 case tok::pp_define:
685 return HandleDefineDirective(Result);
686 case tok::pp_undef:
687 return HandleUndefDirective(Result);
688
689 // C99 6.10.4 - Line Control.
690 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000691 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Chris Lattner141e71f2008-03-09 01:54:53 +0000693 // C99 6.10.5 - Error Directive.
694 case tok::pp_error:
695 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattner141e71f2008-03-09 01:54:53 +0000697 // C99 6.10.6 - Pragma Directive.
698 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000699 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Chris Lattner141e71f2008-03-09 01:54:53 +0000701 // GNU Extensions.
702 case tok::pp_import:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000703 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000704 case tok::pp_include_next:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000705 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattner141e71f2008-03-09 01:54:53 +0000707 case tok::pp_warning:
708 Diag(Result, diag::ext_pp_warning_directive);
709 return HandleUserDiagnosticDirective(Result, true);
710 case tok::pp_ident:
711 return HandleIdentSCCSDirective(Result);
712 case tok::pp_sccs:
713 return HandleIdentSCCSDirective(Result);
714 case tok::pp_assert:
715 //isExtension = true; // FIXME: implement #assert
716 break;
717 case tok::pp_unassert:
718 //isExtension = true; // FIXME: implement #unassert
719 break;
Douglas Gregor7143aab2011-09-01 17:04:32 +0000720
Douglas Gregor1ac13c32012-01-03 19:48:16 +0000721 case tok::pp___public_macro:
David Blaikie4e4d0842012-03-11 07:00:24 +0000722 if (getLangOpts().Modules)
Douglas Gregor94ad28b2012-01-03 18:24:14 +0000723 return HandleMacroPublicDirective(Result);
724 break;
725
Douglas Gregor1ac13c32012-01-03 19:48:16 +0000726 case tok::pp___private_macro:
David Blaikie4e4d0842012-03-11 07:00:24 +0000727 if (getLangOpts().Modules)
Douglas Gregor94ad28b2012-01-03 18:24:14 +0000728 return HandleMacroPrivateDirective(Result);
729 break;
Chris Lattner141e71f2008-03-09 01:54:53 +0000730 }
731 break;
732 }
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Chris Lattner42aa16c2009-03-18 21:00:25 +0000734 // If this is a .S file, treat unknown # directives as non-preprocessor
735 // directives. This is important because # may be a comment or introduce
736 // various pseudo-ops. Just return the # token and push back the following
737 // token to be lexed next time.
David Blaikie4e4d0842012-03-11 07:00:24 +0000738 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000739 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000740 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000741 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000742 Toks[1] = Result;
Chris Lattnerba3ca522011-01-06 05:01:51 +0000743
744 // If the second token is a hashhash token, then we need to translate it to
745 // unknown so the token lexer doesn't try to perform token pasting.
746 if (Result.is(tok::hashhash))
747 Toks[1].setKind(tok::unknown);
748
Chris Lattner42aa16c2009-03-18 21:00:25 +0000749 // Enter this token stream so that we re-lex the tokens. Make sure to
750 // enable macro expansion, in case the token after the # is an identifier
751 // that is expanded.
752 EnterTokenStream(Toks, 2, false, true);
753 return;
754 }
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Chris Lattner141e71f2008-03-09 01:54:53 +0000756 // If we reached here, the preprocessing token is not valid!
757 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Chris Lattner141e71f2008-03-09 01:54:53 +0000759 // Read the rest of the PP line.
760 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattner141e71f2008-03-09 01:54:53 +0000762 // Okay, we're done parsing the directive.
763}
764
Chris Lattner478a18e2009-01-26 06:19:46 +0000765/// GetLineValue - Convert a numeric token into an unsigned value, emitting
766/// Diagnostic DiagID if it is invalid, and returning the value in Val.
767static bool GetLineValue(Token &DigitTok, unsigned &Val,
768 unsigned DiagID, Preprocessor &PP) {
769 if (DigitTok.isNot(tok::numeric_constant)) {
770 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Peter Collingbourne84021552011-02-28 02:37:51 +0000772 if (DigitTok.isNot(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000773 PP.DiscardUntilEndOfDirective();
774 return true;
775 }
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000777 SmallString<64> IntegerBuffer;
Chris Lattner478a18e2009-01-26 06:19:46 +0000778 IntegerBuffer.resize(DigitTok.getLength());
779 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000780 bool Invalid = false;
781 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
782 if (Invalid)
783 return true;
784
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000785 // Verify that we have a simple digit-sequence, and compute the value. This
786 // is always a simple digit string computed in decimal, so we do this manually
787 // here.
788 Val = 0;
789 for (unsigned i = 0; i != ActualLength; ++i) {
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000790 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000791 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
792 diag::err_pp_line_digit_sequence);
793 PP.DiscardUntilEndOfDirective();
794 return true;
795 }
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000797 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
798 if (NextVal < Val) { // overflow.
799 PP.Diag(DigitTok, DiagID);
800 PP.DiscardUntilEndOfDirective();
801 return true;
802 }
803 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000804 }
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Fariborz Jahanian540f9ae2012-06-26 21:19:20 +0000806 if (DigitTokBegin[0] == '0' && Val)
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000807 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Chris Lattner478a18e2009-01-26 06:19:46 +0000809 return false;
810}
811
James Dennettdc201692012-06-22 05:46:07 +0000812/// \brief Handle a \#line directive: C99 6.10.4.
813///
814/// The two acceptable forms are:
815/// \verbatim
Chris Lattner359cc442009-01-26 05:29:08 +0000816/// # line digit-sequence
817/// # line digit-sequence "s-char-sequence"
James Dennettdc201692012-06-22 05:46:07 +0000818/// \endverbatim
Chris Lattner359cc442009-01-26 05:29:08 +0000819void Preprocessor::HandleLineDirective(Token &Tok) {
820 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
821 // expanded.
822 Token DigitTok;
823 Lex(DigitTok);
824
Chris Lattner359cc442009-01-26 05:29:08 +0000825 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000826 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000827 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000828 return;
Fariborz Jahanian540f9ae2012-06-26 21:19:20 +0000829
830 if (LineNo == 0)
831 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner359cc442009-01-26 05:29:08 +0000832
Chris Lattner478a18e2009-01-26 06:19:46 +0000833 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
834 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman158ebfb2011-10-10 23:35:28 +0000835 unsigned LineLimit = 32768U;
Richard Smith80ad52f2013-01-02 11:42:31 +0000836 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman158ebfb2011-10-10 23:35:28 +0000837 LineLimit = 2147483648U;
Chris Lattner359cc442009-01-26 05:29:08 +0000838 if (LineNo >= LineLimit)
839 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith80ad52f2013-01-02 11:42:31 +0000840 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smith661a9962011-10-15 01:18:56 +0000841 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Chris Lattner5b9a5042009-01-26 07:57:50 +0000843 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000844 Token StrTok;
845 Lex(StrTok);
846
Peter Collingbourne84021552011-02-28 02:37:51 +0000847 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
848 // string followed by eod.
849 if (StrTok.is(tok::eod))
Chris Lattner359cc442009-01-26 05:29:08 +0000850 ; // ok
851 else if (StrTok.isNot(tok::string_literal)) {
852 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smith99831e42012-03-06 03:21:47 +0000853 return DiscardUntilEndOfDirective();
854 } else if (StrTok.hasUDSuffix()) {
855 Diag(StrTok, diag::err_invalid_string_udl);
856 return DiscardUntilEndOfDirective();
Chris Lattner359cc442009-01-26 05:29:08 +0000857 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000858 // Parse and validate the string, converting it into a unique ID.
859 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000860 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000861 if (Literal.hadError)
862 return DiscardUntilEndOfDirective();
863 if (Literal.Pascal) {
864 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
865 return DiscardUntilEndOfDirective();
866 }
Jay Foad65aa6882011-06-21 15:13:30 +0000867 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Peter Collingbourne84021552011-02-28 02:37:51 +0000869 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattnerab82f412009-04-17 23:30:53 +0000870 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
871 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000872 }
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Chris Lattner4c4ea172009-02-03 21:52:55 +0000874 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Chris Lattner16629382009-03-27 17:13:49 +0000876 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000877 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
878 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000879 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000880}
881
Chris Lattner478a18e2009-01-26 06:19:46 +0000882/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
883/// marker directive.
884static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
885 bool &IsSystemHeader, bool &IsExternCHeader,
886 Preprocessor &PP) {
887 unsigned FlagVal;
888 Token FlagTok;
889 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000890 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000891 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
892 return true;
893
894 if (FlagVal == 1) {
895 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattner478a18e2009-01-26 06:19:46 +0000897 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000898 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000899 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
900 return true;
901 } else if (FlagVal == 2) {
902 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner137b6a62009-02-04 06:25:26 +0000904 SourceManager &SM = PP.getSourceManager();
905 // If we are leaving the current presumed file, check to make sure the
906 // presumed include stack isn't empty!
907 FileID CurFileID =
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000908 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner137b6a62009-02-04 06:25:26 +0000909 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000910 if (PLoc.isInvalid())
911 return true;
912
Chris Lattner137b6a62009-02-04 06:25:26 +0000913 // If there is no include loc (main file) or if the include loc is in a
914 // different physical file, then we aren't in a "1" line marker flag region.
915 SourceLocation IncLoc = PLoc.getIncludeLoc();
916 if (IncLoc.isInvalid() ||
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000917 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner137b6a62009-02-04 06:25:26 +0000918 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
919 PP.DiscardUntilEndOfDirective();
920 return true;
921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Chris Lattner478a18e2009-01-26 06:19:46 +0000923 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000924 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000925 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
926 return true;
927 }
928
929 // We must have 3 if there are still flags.
930 if (FlagVal != 3) {
931 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000932 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000933 return true;
934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattner478a18e2009-01-26 06:19:46 +0000936 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Chris Lattner478a18e2009-01-26 06:19:46 +0000938 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000939 if (FlagTok.is(tok::eod)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000940 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000941 return true;
942
943 // We must have 4 if there is yet another flag.
944 if (FlagVal != 4) {
945 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000946 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000947 return true;
948 }
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Chris Lattner478a18e2009-01-26 06:19:46 +0000950 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Chris Lattner478a18e2009-01-26 06:19:46 +0000952 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000953 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000954
955 // There are no more valid flags here.
956 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000957 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000958 return true;
959}
960
961/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
962/// one of the following forms:
963///
964/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000965/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000966/// # 42 "file" ('1' | '2')? '3' '4'?
967///
968void Preprocessor::HandleDigitDirective(Token &DigitTok) {
969 // Validate the number and convert it to an unsigned. GNU does not have a
970 // line # limit other than it fit in 32-bits.
971 unsigned LineNo;
972 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
973 *this))
974 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Chris Lattner478a18e2009-01-26 06:19:46 +0000976 Token StrTok;
977 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattner478a18e2009-01-26 06:19:46 +0000979 bool IsFileEntry = false, IsFileExit = false;
980 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000981 int FilenameID = -1;
982
Peter Collingbourne84021552011-02-28 02:37:51 +0000983 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
984 // string followed by eod.
985 if (StrTok.is(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000986 ; // ok
987 else if (StrTok.isNot(tok::string_literal)) {
988 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000989 return DiscardUntilEndOfDirective();
Richard Smith99831e42012-03-06 03:21:47 +0000990 } else if (StrTok.hasUDSuffix()) {
991 Diag(StrTok, diag::err_invalid_string_udl);
992 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000993 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000994 // Parse and validate the string, converting it into a unique ID.
995 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000996 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000997 if (Literal.hadError)
998 return DiscardUntilEndOfDirective();
999 if (Literal.Pascal) {
1000 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1001 return DiscardUntilEndOfDirective();
1002 }
Jay Foad65aa6882011-06-21 15:13:30 +00001003 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Chris Lattner478a18e2009-01-26 06:19:46 +00001005 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +00001006 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +00001007 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +00001008 return;
Chris Lattner478a18e2009-01-26 06:19:46 +00001009 }
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Chris Lattner9d79eba2009-02-04 05:21:58 +00001011 // Create a line note with this information.
1012 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +00001013 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +00001014 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Chris Lattner16629382009-03-27 17:13:49 +00001016 // If the preprocessor has callbacks installed, notify them of the #line
1017 // change. This is used so that the line marker comes out in -E mode for
1018 // example.
1019 if (Callbacks) {
1020 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1021 if (IsFileEntry)
1022 Reason = PPCallbacks::EnterFile;
1023 else if (IsFileExit)
1024 Reason = PPCallbacks::ExitFile;
1025 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1026 if (IsExternCHeader)
1027 FileKind = SrcMgr::C_ExternCSystem;
1028 else if (IsSystemHeader)
1029 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Chris Lattner86d0ef72010-04-14 04:28:50 +00001031 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +00001032 }
Chris Lattner478a18e2009-01-26 06:19:46 +00001033}
1034
1035
Chris Lattner099dd052009-01-26 05:30:54 +00001036/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1037///
Mike Stump1eb44332009-09-09 15:08:12 +00001038void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001039 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +00001040 // PTH doesn't emit #warning or #error directives.
1041 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +00001042 return CurPTHLexer->DiscardToEndOfLine();
1043
Chris Lattner141e71f2008-03-09 01:54:53 +00001044 // Read the rest of the line raw. We do this because we don't want macros
1045 // to be expanded and we don't require that the tokens be valid preprocessing
1046 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1047 // collapse multiple consequtive white space between tokens, but this isn't
1048 // specified by the standard.
Benjamin Kramer3093b202012-05-18 19:32:16 +00001049 SmallString<128> Message;
1050 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek34a2c422012-02-02 00:16:13 +00001051
1052 // Find the first non-whitespace character, so that we can make the
1053 // diagnostic more succinct.
Benjamin Kramer3093b202012-05-18 19:32:16 +00001054 StringRef Msg = Message.str().ltrim(" ");
1055
Chris Lattner359cc442009-01-26 05:29:08 +00001056 if (isWarning)
Ted Kremenek34a2c422012-02-02 00:16:13 +00001057 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner359cc442009-01-26 05:29:08 +00001058 else
Ted Kremenek34a2c422012-02-02 00:16:13 +00001059 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattner141e71f2008-03-09 01:54:53 +00001060}
1061
1062/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1063///
1064void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1065 // Yes, this directive is an extension.
1066 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Chris Lattner141e71f2008-03-09 01:54:53 +00001068 // Read the string argument.
1069 Token StrTok;
1070 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Chris Lattner141e71f2008-03-09 01:54:53 +00001072 // If the token kind isn't a string, it's a malformed directive.
1073 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +00001074 StrTok.isNot(tok::wide_string_literal)) {
1075 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne84021552011-02-28 02:37:51 +00001076 if (StrTok.isNot(tok::eod))
Chris Lattner099dd052009-01-26 05:30:54 +00001077 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +00001078 return;
1079 }
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Richard Smith99831e42012-03-06 03:21:47 +00001081 if (StrTok.hasUDSuffix()) {
1082 Diag(StrTok, diag::err_invalid_string_udl);
1083 return DiscardUntilEndOfDirective();
1084 }
1085
Peter Collingbourne84021552011-02-28 02:37:51 +00001086 // Verify that there is nothing after the string, other than EOD.
Chris Lattner35410d52009-04-14 05:07:49 +00001087 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +00001088
Douglas Gregor453091c2010-03-16 22:30:13 +00001089 if (Callbacks) {
1090 bool Invalid = false;
1091 std::string Str = getSpelling(StrTok, &Invalid);
1092 if (!Invalid)
1093 Callbacks->Ident(Tok.getLocation(), Str);
1094 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001095}
1096
Douglas Gregor94ad28b2012-01-03 18:24:14 +00001097/// \brief Handle a #public directive.
1098void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor7143aab2011-09-01 17:04:32 +00001099 Token MacroNameTok;
1100 ReadMacroName(MacroNameTok, 2);
1101
1102 // Error reading macro name? If so, diagnostic already issued.
1103 if (MacroNameTok.is(tok::eod))
1104 return;
1105
Douglas Gregor1ac13c32012-01-03 19:48:16 +00001106 // Check to see if this is the last token on the #__public_macro line.
1107 CheckEndOfDirective("__public_macro");
Douglas Gregor7143aab2011-09-01 17:04:32 +00001108
1109 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001110 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Douglas Gregor7143aab2011-09-01 17:04:32 +00001111
1112 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001113 if (MD == 0) {
Douglas Gregoraa93a872011-10-17 15:32:29 +00001114 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor7143aab2011-09-01 17:04:32 +00001115 << MacroNameTok.getIdentifierInfo();
1116 return;
1117 }
1118
1119 // Note that this macro has now been exported.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001120 MD->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1121
Douglas Gregoraa93a872011-10-17 15:32:29 +00001122 // If this macro definition came from a PCH file, mark it
1123 // as having changed since serialization.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001124 if (MD->isImported())
1125 MD->setChangedAfterLoad();
Douglas Gregoraa93a872011-10-17 15:32:29 +00001126}
1127
Douglas Gregor94ad28b2012-01-03 18:24:14 +00001128/// \brief Handle a #private directive.
Douglas Gregoraa93a872011-10-17 15:32:29 +00001129void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1130 Token MacroNameTok;
1131 ReadMacroName(MacroNameTok, 2);
1132
1133 // Error reading macro name? If so, diagnostic already issued.
1134 if (MacroNameTok.is(tok::eod))
1135 return;
1136
Douglas Gregor1ac13c32012-01-03 19:48:16 +00001137 // Check to see if this is the last token on the #__private_macro line.
1138 CheckEndOfDirective("__private_macro");
Douglas Gregoraa93a872011-10-17 15:32:29 +00001139
1140 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001141 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Douglas Gregoraa93a872011-10-17 15:32:29 +00001142
1143 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001144 if (MD == 0) {
Douglas Gregoraa93a872011-10-17 15:32:29 +00001145 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1146 << MacroNameTok.getIdentifierInfo();
1147 return;
1148 }
1149
1150 // Note that this macro has now been marked private.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001151 MD->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
1152
Douglas Gregor7143aab2011-09-01 17:04:32 +00001153 // If this macro definition came from a PCH file, mark it
1154 // as having changed since serialization.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001155 if (MD->isImported())
1156 MD->setChangedAfterLoad();
Douglas Gregor7143aab2011-09-01 17:04:32 +00001157}
1158
Chris Lattner141e71f2008-03-09 01:54:53 +00001159//===----------------------------------------------------------------------===//
1160// Preprocessor Include Directive Handling.
1161//===----------------------------------------------------------------------===//
1162
1163/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettdc201692012-06-22 05:46:07 +00001164/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattner141e71f2008-03-09 01:54:53 +00001165/// true if the input filename was in <>'s or false if it were in ""'s. The
1166/// caller is expected to provide a buffer that is large enough to hold the
1167/// spelling of the filename, but is also expected to handle the case when
1168/// this method decides to use a different buffer.
1169bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001170 StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001171 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +00001172 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Chris Lattner141e71f2008-03-09 01:54:53 +00001174 // Make sure the filename is <x> or "x".
1175 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +00001176 if (Buffer[0] == '<') {
1177 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001178 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001179 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001180 return true;
1181 }
1182 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +00001183 } else if (Buffer[0] == '"') {
1184 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001185 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001186 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001187 return true;
1188 }
1189 isAngled = false;
1190 } else {
1191 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001192 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001193 return true;
1194 }
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Chris Lattner141e71f2008-03-09 01:54:53 +00001196 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +00001197 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001198 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001199 Buffer = StringRef();
Chris Lattnera1394812010-01-10 01:35:12 +00001200 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001201 }
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Chris Lattner141e71f2008-03-09 01:54:53 +00001203 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001204 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001205 return isAngled;
1206}
1207
James Dennettdc201692012-06-22 05:46:07 +00001208/// \brief Handle cases where the \#include name is expanded from a macro
1209/// as multiple tokens, which need to be glued together.
1210///
1211/// This occurs for code like:
1212/// \code
1213/// \#define FOO <a/b.h>
1214/// \#include FOO
1215/// \endcode
Chris Lattner141e71f2008-03-09 01:54:53 +00001216/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1217///
1218/// This code concatenates and consumes tokens up to the '>' token. It returns
1219/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne84021552011-02-28 02:37:51 +00001220/// the EOD marker.
John Thompsona28cc092009-10-30 13:49:06 +00001221bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001222 SmallString<128> &FilenameBuffer,
Douglas Gregorecdcb882010-10-20 22:00:55 +00001223 SourceLocation &End) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001224 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001225
John Thompsona28cc092009-10-30 13:49:06 +00001226 Lex(CurTok);
Peter Collingbourne84021552011-02-28 02:37:51 +00001227 while (CurTok.isNot(tok::eod)) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001228 End = CurTok.getLocation();
1229
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001230 // FIXME: Provide code completion for #includes.
1231 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001232 setCodeCompletionReached();
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001233 Lex(CurTok);
1234 continue;
1235 }
1236
Chris Lattner141e71f2008-03-09 01:54:53 +00001237 // Append the spelling of this token to the buffer. If there was a space
1238 // before it, add it now.
1239 if (CurTok.hasLeadingSpace())
1240 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Chris Lattner141e71f2008-03-09 01:54:53 +00001242 // Get the spelling of the token, directly into FilenameBuffer if possible.
1243 unsigned PreAppendSize = FilenameBuffer.size();
1244 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Chris Lattner141e71f2008-03-09 01:54:53 +00001246 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001247 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Chris Lattner141e71f2008-03-09 01:54:53 +00001249 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1250 if (BufPtr != &FilenameBuffer[PreAppendSize])
1251 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Chris Lattner141e71f2008-03-09 01:54:53 +00001253 // Resize FilenameBuffer to the correct size.
1254 if (CurTok.getLength() != ActualLen)
1255 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Chris Lattner141e71f2008-03-09 01:54:53 +00001257 // If we found the '>' marker, return success.
1258 if (CurTok.is(tok::greater))
1259 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001260
John Thompsona28cc092009-10-30 13:49:06 +00001261 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001262 }
1263
Peter Collingbourne84021552011-02-28 02:37:51 +00001264 // If we hit the eod marker, emit an error and return true so that the caller
1265 // knows the EOD has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001266 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001267 return true;
1268}
1269
James Dennettdc201692012-06-22 05:46:07 +00001270/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1271/// the file to be included from the lexer, then include it! This is a common
1272/// routine with functionality shared between \#include, \#include_next and
1273/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001274/// specifies the file to start searching from.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001275void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1276 Token &IncludeTok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001277 const DirectoryLookup *LookupFrom,
1278 bool isImport) {
1279
1280 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001281 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Chris Lattner141e71f2008-03-09 01:54:53 +00001283 // Reserve a buffer to get the spelling.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001284 SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001285 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001286 SourceLocation End;
Douglas Gregore3a82562011-11-30 18:02:36 +00001287 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregorecdcb882010-10-20 22:00:55 +00001288
Chris Lattner141e71f2008-03-09 01:54:53 +00001289 switch (FilenameTok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +00001290 case tok::eod:
1291 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattner141e71f2008-03-09 01:54:53 +00001292 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Chris Lattner141e71f2008-03-09 01:54:53 +00001294 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001295 case tok::string_literal:
1296 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregorecdcb882010-10-20 22:00:55 +00001297 End = FilenameTok.getLocation();
Argyrios Kyrtzidiscfa1caa2012-11-01 17:52:58 +00001298 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +00001299 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Chris Lattner141e71f2008-03-09 01:54:53 +00001301 case tok::less:
1302 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1303 // case, glue the tokens together into FilenameBuffer and interpret those.
1304 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +00001305 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne84021552011-02-28 02:37:51 +00001306 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001307 Filename = FilenameBuffer.str();
Argyrios Kyrtzidiscfa1caa2012-11-01 17:52:58 +00001308 CharEnd = End.getLocWithOffset(1);
Chris Lattner141e71f2008-03-09 01:54:53 +00001309 break;
1310 default:
1311 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1312 DiscardUntilEndOfDirective();
1313 return;
1314 }
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001316 CharSourceRange FilenameRange
1317 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman4c55c542012-03-02 22:51:54 +00001318 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001319 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001320 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001321 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1322 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001323 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001324 DiscardUntilEndOfDirective();
1325 return;
1326 }
Mike Stump1eb44332009-09-09 15:08:12 +00001327
Peter Collingbourne84021552011-02-28 02:37:51 +00001328 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001329 // we allow macros that expand to nothing after the filename, because this
1330 // falls into the category of "#include pp-tokens new-line" specified in
1331 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001332 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001333
1334 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001335 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1336 Diag(FilenameTok, diag::err_pp_include_too_deep);
1337 return;
1338 }
Mike Stump1eb44332009-09-09 15:08:12 +00001339
John McCall8dfac0b2011-09-30 05:12:12 +00001340 // Complain about attempts to #include files in an audit pragma.
1341 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1342 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1343 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1344
1345 // Immediately leave the pragma.
1346 PragmaARCCFCodeAuditedLoc = SourceLocation();
1347 }
1348
Aaron Ballman4c55c542012-03-02 22:51:54 +00001349 if (HeaderInfo.HasIncludeAliasMap()) {
1350 // Map the filename with the brackets still attached. If the name doesn't
1351 // map to anything, fall back on the filename we've already gotten the
1352 // spelling for.
1353 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1354 if (!NewName.empty())
1355 Filename = NewName;
1356 }
1357
Chris Lattner141e71f2008-03-09 01:54:53 +00001358 // Search include directories.
1359 const DirectoryLookup *CurDir;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001360 SmallString<1024> SearchPath;
1361 SmallString<1024> RelativePath;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001362 // We get the raw path only if we have 'Callbacks' to which we later pass
1363 // the path.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001364 Module *SuggestedModule = 0;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001365 const FileEntry *File = LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +00001366 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001367 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikie4e4d0842012-03-11 07:00:24 +00001368 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001369
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001370 if (Callbacks) {
1371 if (!File) {
1372 // Give the clients a chance to recover.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001373 SmallString<128> RecoveryPath;
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001374 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1375 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1376 // Add the recovery path to the list of search paths.
Daniel Dunbar1ea6bc02013-01-25 01:50:28 +00001377 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001378 HeaderInfo.AddSearchPath(DL, isAngled);
1379
1380 // Try the lookup again, skipping the cache.
1381 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikie4e4d0842012-03-11 07:00:24 +00001382 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001383 /*SkipCache*/true);
1384 }
1385 }
1386 }
1387
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001388 if (!SuggestedModule) {
1389 // Notify the callback object that we've seen an inclusion directive.
1390 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1391 FilenameRange, File,
1392 SearchPath, RelativePath,
1393 /*ImportedModule=*/0);
1394 }
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001395 }
1396
1397 if (File == 0) {
Aaron Ballmana52f5a32012-07-17 23:19:16 +00001398 if (!SuppressIncludeNotFoundError) {
1399 // If the file could not be located and it was included via angle
1400 // brackets, we can attempt a lookup as though it were a quoted path to
1401 // provide the user with a possible fixit.
1402 if (isAngled) {
1403 File = LookupFile(Filename, false, LookupFrom, CurDir,
1404 Callbacks ? &SearchPath : 0,
1405 Callbacks ? &RelativePath : 0,
1406 getLangOpts().Modules ? &SuggestedModule : 0);
1407 if (File) {
1408 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1409 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1410 Filename <<
1411 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1412 }
1413 }
1414 // If the file is still not found, just go with the vanilla diagnostic
1415 if (!File)
1416 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1417 }
1418 if (!File)
1419 return;
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001420 }
1421
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001422 // If we are supposed to import a module rather than including the header,
1423 // do so now.
Douglas Gregorc69c42e2011-11-17 22:44:56 +00001424 if (SuggestedModule) {
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001425 // Compute the module access path corresponding to this module.
1426 // FIXME: Should we have a second loadModule() overload to avoid this
1427 // extra lookup step?
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001428 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001429 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001430 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1431 FilenameTok.getLocation()));
1432 std::reverse(Path.begin(), Path.end());
1433
Douglas Gregore3a82562011-11-30 18:02:36 +00001434 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001435 SmallString<128> PathString;
Douglas Gregore3a82562011-11-30 18:02:36 +00001436 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1437 if (I)
1438 PathString += '.';
1439 PathString += Path[I].first->getName();
1440 }
1441 int IncludeKind = 0;
1442
1443 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1444 case tok::pp_include:
1445 IncludeKind = 0;
1446 break;
1447
1448 case tok::pp_import:
1449 IncludeKind = 1;
1450 break;
1451
Douglas Gregoredee9692011-11-30 18:03:26 +00001452 case tok::pp_include_next:
1453 IncludeKind = 2;
1454 break;
Douglas Gregore3a82562011-11-30 18:02:36 +00001455
1456 case tok::pp___include_macros:
1457 IncludeKind = 3;
1458 break;
1459
1460 default:
1461 llvm_unreachable("unknown include directive kind");
Douglas Gregore3a82562011-11-30 18:02:36 +00001462 }
1463
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001464 // Determine whether we are actually building the module that this
1465 // include directive maps to.
1466 bool BuildingImportedModule
David Blaikie4e4d0842012-03-11 07:00:24 +00001467 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001468
David Blaikie4e4d0842012-03-11 07:00:24 +00001469 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001470 // If we're not building the imported module, warn that we're going
1471 // to automatically turn this inclusion directive into a module import.
Douglas Gregorc13a34b2012-01-03 19:32:59 +00001472 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001473 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1474 /*IsTokenRange=*/false);
1475 Diag(HashLoc, diag::warn_auto_module_import)
1476 << IncludeKind << PathString
1477 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregor1b257af2012-12-11 22:11:52 +00001478 "@import " + PathString.str().str() + ";");
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001479 }
Douglas Gregore3a82562011-11-30 18:02:36 +00001480
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001481 // Load the module.
Douglas Gregor5e356932011-12-01 17:11:21 +00001482 // If this was an #__include_macros directive, only make macros visible.
1483 Module::NameVisibilityKind Visibility
1484 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor463d9092012-11-29 23:55:25 +00001485 ModuleLoadResult Imported
Douglas Gregor305dc3e2011-12-20 00:28:52 +00001486 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1487 /*IsIncludeDirective=*/true);
Argyrios Kyrtzidiseb788e92012-09-29 01:06:01 +00001488 assert((Imported == 0 || Imported == SuggestedModule) &&
1489 "the imported module is different than the suggested one");
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001490
1491 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001492 if (!BuildingImportedModule && Imported) {
1493 if (Callbacks) {
1494 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1495 FilenameRange, File,
1496 SearchPath, RelativePath, Imported);
1497 }
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001498 return;
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001499 }
Douglas Gregor463d9092012-11-29 23:55:25 +00001500
1501 // If we failed to find a submodule that we expected to find, we can
1502 // continue. Otherwise, there's an error in the included file, so we
1503 // don't want to include it.
1504 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1505 return;
1506 }
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001507 }
1508
1509 if (Callbacks && SuggestedModule) {
1510 // We didn't notify the callback object that we've seen an inclusion
1511 // directive before. Now that we are parsing the include normally and not
1512 // turning it to a module import, notify the callback object.
1513 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1514 FilenameRange, File,
1515 SearchPath, RelativePath,
1516 /*ImportedModule=*/0);
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001517 }
1518
Chris Lattner72181832008-09-26 20:12:23 +00001519 // The #included file will be considered to be a system header if either it is
1520 // in a system include directory, or if the #includer is a system include
1521 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001522 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001523 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001524 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001526 // Ask HeaderInfo if we should enter this #include file. If not, #including
1527 // this file will have no effect.
1528 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001529 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001530 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001531 return;
1532 }
1533
Chris Lattner141e71f2008-03-09 01:54:53 +00001534 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisdb81d382012-03-27 18:47:48 +00001535 SourceLocation IncludePos = End;
1536 // If the filename string was the result of macro expansions, set the include
1537 // position on the file where it will be included and after the expansions.
1538 if (IncludePos.isMacroID())
1539 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1540 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned57b7ff2011-06-30 16:41:03 +00001541 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattner141e71f2008-03-09 01:54:53 +00001542
1543 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001544 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001545}
1546
James Dennettdc201692012-06-22 05:46:07 +00001547/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattner141e71f2008-03-09 01:54:53 +00001548///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001549void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1550 Token &IncludeNextTok) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001551 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Chris Lattner141e71f2008-03-09 01:54:53 +00001553 // #include_next is like #include, except that we start searching after
1554 // the current found directory. If we can't do this, issue a
1555 // diagnostic.
1556 const DirectoryLookup *Lookup = CurDirLookup;
1557 if (isInPrimaryFile()) {
1558 Lookup = 0;
1559 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1560 } else if (Lookup == 0) {
1561 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1562 } else {
1563 // Start looking up in the next directory.
1564 ++Lookup;
1565 }
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Douglas Gregorecdcb882010-10-20 22:00:55 +00001567 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattner141e71f2008-03-09 01:54:53 +00001568}
1569
James Dennettdc201692012-06-22 05:46:07 +00001570/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman4207eda2012-03-18 03:10:37 +00001571void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1572 // The Microsoft #import directive takes a type library and generates header
1573 // files from it, and includes those. This is beyond the scope of what clang
1574 // does, so we ignore it and error out. However, #import can optionally have
1575 // trailing attributes that span multiple lines. We're going to eat those
1576 // so we can continue processing from there.
1577 Diag(Tok, diag::err_pp_import_directive_ms );
1578
1579 // Read tokens until we get to the end of the directive. Note that the
1580 // directive can be split over multiple lines using the backslash character.
1581 DiscardUntilEndOfDirective();
1582}
1583
James Dennettdc201692012-06-22 05:46:07 +00001584/// HandleImportDirective - Implements \#import.
Chris Lattner141e71f2008-03-09 01:54:53 +00001585///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001586void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1587 Token &ImportTok) {
Aaron Ballman4207eda2012-03-18 03:10:37 +00001588 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1589 if (LangOpts.MicrosoftMode)
1590 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001591 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman4207eda2012-03-18 03:10:37 +00001592 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00001593 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001594}
1595
Chris Lattnerde076652009-04-08 18:46:40 +00001596/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1597/// pseudo directive in the predefines buffer. This handles it by sucking all
1598/// tokens through the preprocessor and discarding them (only keeping the side
1599/// effects on the preprocessor).
Douglas Gregorecdcb882010-10-20 22:00:55 +00001600void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1601 Token &IncludeMacrosTok) {
Chris Lattnerde076652009-04-08 18:46:40 +00001602 // This directive should only occur in the predefines buffer. If not, emit an
1603 // error and reject it.
1604 SourceLocation Loc = IncludeMacrosTok.getLocation();
1605 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1606 Diag(IncludeMacrosTok.getLocation(),
1607 diag::pp_include_macros_out_of_predefines);
1608 DiscardUntilEndOfDirective();
1609 return;
1610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Chris Lattnerfd105112009-04-08 20:53:24 +00001612 // Treat this as a normal #include for checking purposes. If this is
1613 // successful, it will push a new lexer onto the include stack.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001614 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Chris Lattnerfd105112009-04-08 20:53:24 +00001616 Token TmpTok;
1617 do {
1618 Lex(TmpTok);
1619 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1620 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001621}
1622
Chris Lattner141e71f2008-03-09 01:54:53 +00001623//===----------------------------------------------------------------------===//
1624// Preprocessor Macro Directive Handling.
1625//===----------------------------------------------------------------------===//
1626
1627/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1628/// definition has just been read. Lex the rest of the arguments and the
1629/// closing ), updating MI with what we learn. Return true if an error occurs
1630/// parsing the arg list.
Abramo Bagnarae2e87682012-03-31 20:17:27 +00001631bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001632 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Chris Lattner141e71f2008-03-09 01:54:53 +00001634 while (1) {
1635 LexUnexpandedToken(Tok);
1636 switch (Tok.getKind()) {
1637 case tok::r_paren:
1638 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001639 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001640 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001641 // Otherwise we have #define FOO(A,)
1642 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1643 return true;
1644 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikie4e4d0842012-03-11 07:00:24 +00001645 if (!LangOpts.C99)
Richard Smith80ad52f2013-01-02 11:42:31 +00001646 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smith661a9962011-10-15 01:18:56 +00001647 diag::warn_cxx98_compat_variadic_macro :
1648 diag::ext_variadic_macro);
Chris Lattner141e71f2008-03-09 01:54:53 +00001649
Joey Gouly617bb312013-01-17 17:35:00 +00001650 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1651 if (LangOpts.OpenCL) {
1652 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1653 return true;
1654 }
1655
Chris Lattner141e71f2008-03-09 01:54:53 +00001656 // Lex the token after the identifier.
1657 LexUnexpandedToken(Tok);
1658 if (Tok.isNot(tok::r_paren)) {
1659 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1660 return true;
1661 }
1662 // Add the __VA_ARGS__ identifier as an argument.
1663 Arguments.push_back(Ident__VA_ARGS__);
1664 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001665 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001666 return false;
Peter Collingbourne84021552011-02-28 02:37:51 +00001667 case tok::eod: // #define X(
Chris Lattner141e71f2008-03-09 01:54:53 +00001668 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1669 return true;
1670 default:
1671 // Handle keywords and identifiers here to accept things like
1672 // #define Foo(for) for.
1673 IdentifierInfo *II = Tok.getIdentifierInfo();
1674 if (II == 0) {
1675 // #define X(1
1676 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1677 return true;
1678 }
1679
1680 // If this is already used as an argument, it is used multiple times (e.g.
1681 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001682 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001683 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001684 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001685 return true;
1686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Chris Lattner141e71f2008-03-09 01:54:53 +00001688 // Add the argument to the macro info.
1689 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Chris Lattner141e71f2008-03-09 01:54:53 +00001691 // Lex the token after the identifier.
1692 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Chris Lattner141e71f2008-03-09 01:54:53 +00001694 switch (Tok.getKind()) {
1695 default: // #define X(A B
1696 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1697 return true;
1698 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001699 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001700 return false;
1701 case tok::comma: // #define X(A,
1702 break;
1703 case tok::ellipsis: // #define X(A... -> GCC extension
1704 // Diagnose extension.
1705 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Chris Lattner141e71f2008-03-09 01:54:53 +00001707 // Lex the token after the identifier.
1708 LexUnexpandedToken(Tok);
1709 if (Tok.isNot(tok::r_paren)) {
1710 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1711 return true;
1712 }
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Chris Lattner141e71f2008-03-09 01:54:53 +00001714 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001715 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001716 return false;
1717 }
1718 }
1719 }
1720}
1721
James Dennettdc201692012-06-22 05:46:07 +00001722/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattner141e71f2008-03-09 01:54:53 +00001723/// line then lets the caller lex the next real token.
1724void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1725 ++NumDefined;
1726
1727 Token MacroNameTok;
1728 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Chris Lattner141e71f2008-03-09 01:54:53 +00001730 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001731 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001732 return;
1733
Chris Lattner2451b522009-04-21 04:46:33 +00001734 Token LastTok = MacroNameTok;
1735
Chris Lattner141e71f2008-03-09 01:54:53 +00001736 // If we are supposed to keep comments in #defines, reenable comment saving
1737 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001738 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Chris Lattner141e71f2008-03-09 01:54:53 +00001740 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001741 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Chris Lattner141e71f2008-03-09 01:54:53 +00001743 Token Tok;
1744 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Chris Lattner141e71f2008-03-09 01:54:53 +00001746 // If this is a function-like macro definition, parse the argument list,
1747 // marking each of the identifiers as being used as macro arguments. Also,
1748 // check other constraints on the first token of the macro body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001749 if (Tok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001750 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001751 } else if (Tok.hasLeadingSpace()) {
1752 // This is a normal token with leading space. Clear the leading space
1753 // marker on the first token to get proper expansion.
1754 Tok.clearFlag(Token::LeadingSpace);
1755 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001756 // This is a function-like macro definition. Read the argument list.
1757 MI->setIsFunctionLike();
Abramo Bagnarae2e87682012-03-31 20:17:27 +00001758 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001759 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001760 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001761 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001762 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001763 DiscardUntilEndOfDirective();
1764 return;
1765 }
1766
Chris Lattner8fde5972009-04-19 18:26:34 +00001767 // If this is a definition of a variadic C99 function-like macro, not using
1768 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Chris Lattner8fde5972009-04-19 18:26:34 +00001770 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1771 // This gets unpoisoned where it is allowed.
1772 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1773 if (MI->isC99Varargs())
1774 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Chris Lattner141e71f2008-03-09 01:54:53 +00001776 // Read the first token after the arg list for down below.
1777 LexUnexpandedToken(Tok);
Richard Smith80ad52f2013-01-02 11:42:31 +00001778 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001779 // C99 requires whitespace between the macro definition and the body. Emit
1780 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001781 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001782 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001783 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1784 // first character of a replacement list is not a character required by
1785 // subclause 5.2.1, then there shall be white-space separation between the
1786 // identifier and the replacement list.". 5.2.1 lists this set:
1787 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1788 // is irrelevant here.
1789 bool isInvalid = false;
1790 if (Tok.is(tok::at)) // @ is not in the list above.
1791 isInvalid = true;
1792 else if (Tok.is(tok::unknown)) {
1793 // If we have an unknown token, it is something strange like "`". Since
1794 // all of valid characters would have lexed into a single character
1795 // token of some sort, we know this is not a valid case.
1796 isInvalid = true;
1797 }
1798 if (isInvalid)
1799 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1800 else
1801 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001802 }
Chris Lattner2451b522009-04-21 04:46:33 +00001803
Peter Collingbourne84021552011-02-28 02:37:51 +00001804 if (!Tok.is(tok::eod))
Chris Lattner2451b522009-04-21 04:46:33 +00001805 LastTok = Tok;
1806
Chris Lattner141e71f2008-03-09 01:54:53 +00001807 // Read the rest of the macro body.
1808 if (MI->isObjectLike()) {
1809 // Object-like macros are very simple, just read their body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001810 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001811 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001812 MI->AddTokenToBody(Tok);
1813 // Get the next token of the macro.
1814 LexUnexpandedToken(Tok);
1815 }
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Chris Lattner141e71f2008-03-09 01:54:53 +00001817 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001818 // Otherwise, read the body of a function-like macro. While we are at it,
1819 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1820 // parameters in function-like macro expansions.
Peter Collingbourne84021552011-02-28 02:37:51 +00001821 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001822 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001823
Eli Friedman4fa4b482012-11-14 02:18:46 +00001824 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001825 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Chris Lattner141e71f2008-03-09 01:54:53 +00001827 // Get the next token of the macro.
1828 LexUnexpandedToken(Tok);
1829 continue;
1830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Eli Friedman4fa4b482012-11-14 02:18:46 +00001832 if (Tok.is(tok::hashhash)) {
1833
1834 // If we see token pasting, check if it looks like the gcc comma
1835 // pasting extension. We'll use this information to suppress
1836 // diagnostics later on.
1837
1838 // Get the next token of the macro.
1839 LexUnexpandedToken(Tok);
1840
1841 if (Tok.is(tok::eod)) {
1842 MI->AddTokenToBody(LastTok);
1843 break;
1844 }
1845
1846 unsigned NumTokens = MI->getNumTokens();
1847 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1848 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1849 MI->setHasCommaPasting();
1850
1851 // Things look ok, add the '##' and param name tokens to the macro.
1852 MI->AddTokenToBody(LastTok);
1853 MI->AddTokenToBody(Tok);
1854 LastTok = Tok;
1855
1856 // Get the next token of the macro.
1857 LexUnexpandedToken(Tok);
1858 continue;
1859 }
1860
Chris Lattner141e71f2008-03-09 01:54:53 +00001861 // Get the next token of the macro.
1862 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Chris Lattner32404692009-05-25 17:16:10 +00001864 // Check for a valid macro arg identifier.
1865 if (Tok.getIdentifierInfo() == 0 ||
1866 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1867
1868 // If this is assembler-with-cpp mode, we accept random gibberish after
1869 // the '#' because '#' is often a comment character. However, change
1870 // the kind of the token to tok::unknown so that the preprocessor isn't
1871 // confused.
David Blaikie4e4d0842012-03-11 07:00:24 +00001872 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner32404692009-05-25 17:16:10 +00001873 LastTok.setKind(tok::unknown);
1874 } else {
1875 Diag(Tok, diag::err_pp_stringize_not_parameter);
1876 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Chris Lattner32404692009-05-25 17:16:10 +00001878 // Disable __VA_ARGS__ again.
1879 Ident__VA_ARGS__->setIsPoisoned(true);
1880 return;
1881 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001882 }
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Chris Lattner32404692009-05-25 17:16:10 +00001884 // Things look ok, add the '#' and param name tokens to the macro.
1885 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001886 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001887 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Chris Lattner141e71f2008-03-09 01:54:53 +00001889 // Get the next token of the macro.
1890 LexUnexpandedToken(Tok);
1891 }
1892 }
Mike Stump1eb44332009-09-09 15:08:12 +00001893
1894
Chris Lattner141e71f2008-03-09 01:54:53 +00001895 // Disable __VA_ARGS__ again.
1896 Ident__VA_ARGS__->setIsPoisoned(true);
1897
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001898 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattner141e71f2008-03-09 01:54:53 +00001899 // replacement list.
1900 unsigned NumTokens = MI->getNumTokens();
1901 if (NumTokens != 0) {
1902 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1903 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001904 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001905 return;
1906 }
1907 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1908 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001909 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001910 return;
1911 }
1912 }
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Chris Lattner2451b522009-04-21 04:46:33 +00001914 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Chris Lattner141e71f2008-03-09 01:54:53 +00001916 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8a64bb52012-08-29 00:20:03 +00001917 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001918 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001919 // It is very common for system headers to have tons of macro redefinitions
1920 // and for warnings to be disabled in system headers. If this is the case,
1921 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001922 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001923 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001924 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner41c3ae12009-01-16 19:50:11 +00001925 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001926
Richard Smitheed55e62013-03-06 00:46:00 +00001927 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
1928 // C++ [cpp.predefined]p4, but allow it as an extension.
1929 if (OtherMI->isBuiltinMacro())
1930 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerf47724b2010-08-17 15:55:45 +00001931 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001932 // separation must be the same. C99 6.10.3.2.
Richard Smitheed55e62013-03-06 00:46:00 +00001933 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
1934 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001935 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1936 << MacroNameTok.getIdentifierInfo();
1937 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1938 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001939 }
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001940 if (OtherMI->isWarnIfUnused())
1941 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattner141e71f2008-03-09 01:54:53 +00001942 }
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00001944 MacroDirective *MD = setMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001946 assert(!MI->isUsed());
1947 // If we need warning for not using the macro, add its location in the
1948 // warn-because-unused-macro set. If it gets used it will be removed from set.
1949 if (isInPrimaryFile() && // don't warn for include'd macros.
1950 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikied6471f72011-09-25 23:23:43 +00001951 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001952 MI->setIsWarnIfUnused(true);
1953 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1954 }
1955
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001956 // If the callbacks want to know, tell them about the macro definition.
1957 if (Callbacks)
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00001958 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattner141e71f2008-03-09 01:54:53 +00001959}
1960
James Dennettdc201692012-06-22 05:46:07 +00001961/// HandleUndefDirective - Implements \#undef.
Chris Lattner141e71f2008-03-09 01:54:53 +00001962///
1963void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1964 ++NumUndefined;
1965
1966 Token MacroNameTok;
1967 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Chris Lattner141e71f2008-03-09 01:54:53 +00001969 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001970 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001971 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Chris Lattner141e71f2008-03-09 01:54:53 +00001973 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001974 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Chris Lattner141e71f2008-03-09 01:54:53 +00001976 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001977 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
1978 const MacroInfo *MI = MD ? MD->getInfo() : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Argyrios Kyrtzidis36845472013-01-16 16:52:44 +00001980 // If the callbacks want to know, tell them about the macro #undef.
1981 // Note: no matter if the macro was defined or not.
1982 if (Callbacks)
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00001983 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis36845472013-01-16 16:52:44 +00001984
Chris Lattner141e71f2008-03-09 01:54:53 +00001985 // If the macro is not defined, this is a noop undef, just return.
1986 if (MI == 0) return;
1987
Argyrios Kyrtzidis1f8dcfc2011-07-11 20:39:47 +00001988 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattner141e71f2008-03-09 01:54:53 +00001989 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001990
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001991 if (MI->isWarnIfUnused())
1992 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1993
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001994 UndefineMacro(MacroNameTok.getIdentifierInfo(), MD,
Douglas Gregora8235d62012-10-09 23:05:51 +00001995 MacroNameTok.getLocation());
1996}
1997
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001998void Preprocessor::UndefineMacro(IdentifierInfo *II, MacroDirective *MD,
Douglas Gregora8235d62012-10-09 23:05:51 +00001999 SourceLocation UndefLoc) {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002000 MD->setUndefLoc(UndefLoc);
2001 if (MD->isImported()) {
2002 MD->setChangedAfterLoad();
Douglas Gregora8235d62012-10-09 23:05:51 +00002003 if (Listener)
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002004 Listener->UndefinedMacro(MD);
Douglas Gregora8235d62012-10-09 23:05:51 +00002005 }
2006
2007 clearMacroInfo(II);
Chris Lattner141e71f2008-03-09 01:54:53 +00002008}
2009
2010
2011//===----------------------------------------------------------------------===//
2012// Preprocessor Conditional Directive Handling.
2013//===----------------------------------------------------------------------===//
2014
James Dennettdc201692012-06-22 05:46:07 +00002015/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2016/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2017/// true if any tokens have been returned or pp-directives activated before this
2018/// \#ifndef has been lexed.
Chris Lattner141e71f2008-03-09 01:54:53 +00002019///
2020void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2021 bool ReadAnyTokensBeforeDirective) {
2022 ++NumIf;
2023 Token DirectiveTok = Result;
2024
2025 Token MacroNameTok;
2026 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Chris Lattner141e71f2008-03-09 01:54:53 +00002028 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00002029 if (MacroNameTok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002030 // Skip code until we get to #endif. This helps with recovery by not
2031 // emitting an error when the #endif is reached.
2032 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2033 /*Foundnonskip*/false, /*FoundElse*/false);
2034 return;
2035 }
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Chris Lattner141e71f2008-03-09 01:54:53 +00002037 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00002038 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00002039
Chris Lattner13d283d2010-02-12 08:03:27 +00002040 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00002041 MacroDirective *MD = getMacroDirective(MII);
2042 MacroInfo *MI = MD ? MD->getInfo() : 0;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002043
Ted Kremenek60e45d42008-11-18 00:34:22 +00002044 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00002045 // If the start of a top-level #ifdef and if the macro is not defined,
2046 // inform MIOpt that this might be the start of a proper include guard.
2047 // Otherwise it is some other form of unknown conditional which we can't
2048 // handle.
2049 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002050 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00002051 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00002052 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00002053 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00002054 }
2055
Chris Lattner141e71f2008-03-09 01:54:53 +00002056 // If there is a macro, process it.
2057 if (MI) // Mark it used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002058 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002060 if (Callbacks) {
2061 if (isIfndef)
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00002062 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002063 else
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00002064 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002065 }
2066
Chris Lattner141e71f2008-03-09 01:54:53 +00002067 // Should we include the stuff contained by this directive?
2068 if (!MI == isIfndef) {
2069 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00002070 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2071 /*wasskip*/false, /*foundnonskip*/true,
2072 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00002073 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00002074 // No, skip the contents of this block.
Chris Lattner141e71f2008-03-09 01:54:53 +00002075 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002076 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002077 /*FoundElse*/false);
2078 }
2079}
2080
James Dennettdc201692012-06-22 05:46:07 +00002081/// HandleIfDirective - Implements the \#if directive.
Chris Lattner141e71f2008-03-09 01:54:53 +00002082///
2083void Preprocessor::HandleIfDirective(Token &IfToken,
2084 bool ReadAnyTokensBeforeDirective) {
Aaron Ballman31672b12013-01-16 19:32:21 +00002085 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00002086 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Craig Silverstein08985b92010-11-06 01:19:03 +00002088 // Parse and evaluate the conditional expression.
Chris Lattner141e71f2008-03-09 01:54:53 +00002089 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein08985b92010-11-06 01:19:03 +00002090 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2091 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2092 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes0049db62008-06-01 18:31:24 +00002093
2094 // If this condition is equivalent to #ifndef X, and if this is the first
2095 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002096 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00002097 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00002098 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00002099 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00002100 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00002101 }
2102
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002103 if (Callbacks)
2104 Callbacks->If(IfToken.getLocation(),
2105 SourceRange(ConditionalBegin, ConditionalEnd));
2106
Chris Lattner141e71f2008-03-09 01:54:53 +00002107 // Should we include the stuff contained by this directive?
2108 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002109 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002110 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002111 /*foundnonskip*/true, /*foundelse*/false);
2112 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00002113 // No, skip the contents of this block.
Mike Stump1eb44332009-09-09 15:08:12 +00002114 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002115 /*FoundElse*/false);
2116 }
2117}
2118
James Dennettdc201692012-06-22 05:46:07 +00002119/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattner141e71f2008-03-09 01:54:53 +00002120///
2121void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2122 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Chris Lattner141e71f2008-03-09 01:54:53 +00002124 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00002125 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Chris Lattner141e71f2008-03-09 01:54:53 +00002127 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00002128 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002129 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00002130 Diag(EndifToken, diag::err_pp_endif_without_if);
2131 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00002132 }
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Chris Lattner141e71f2008-03-09 01:54:53 +00002134 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002135 if (CurPPLexer->getConditionalStackDepth() == 0)
2136 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Ted Kremenek60e45d42008-11-18 00:34:22 +00002138 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00002139 "This code should only be reachable in the non-skipping case!");
Craig Silverstein08985b92010-11-06 01:19:03 +00002140
2141 if (Callbacks)
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002142 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +00002143}
2144
James Dennettdc201692012-06-22 05:46:07 +00002145/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein08985b92010-11-06 01:19:03 +00002146///
Chris Lattner141e71f2008-03-09 01:54:53 +00002147void Preprocessor::HandleElseDirective(Token &Result) {
2148 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Chris Lattner141e71f2008-03-09 01:54:53 +00002150 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00002151 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Chris Lattner141e71f2008-03-09 01:54:53 +00002153 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00002154 if (CurPPLexer->popConditionalLevel(CI)) {
2155 Diag(Result, diag::pp_err_else_without_if);
2156 return;
2157 }
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Chris Lattner141e71f2008-03-09 01:54:53 +00002159 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002160 if (CurPPLexer->getConditionalStackDepth() == 0)
2161 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00002162
2163 // If this is a #else with a #else before it, report the error.
2164 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002166 if (Callbacks)
2167 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2168
Craig Silverstein08985b92010-11-06 01:19:03 +00002169 // Finally, skip the rest of the contents of this block.
2170 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00002171 /*FoundElse*/true, Result.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00002172}
2173
James Dennettdc201692012-06-22 05:46:07 +00002174/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein08985b92010-11-06 01:19:03 +00002175///
Chris Lattner141e71f2008-03-09 01:54:53 +00002176void Preprocessor::HandleElifDirective(Token &ElifToken) {
Aaron Ballman31672b12013-01-16 19:32:21 +00002177 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00002178 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Chris Lattner141e71f2008-03-09 01:54:53 +00002180 // #elif directive in a non-skipping conditional... start skipping.
2181 // We don't care what the condition is, because we will always skip it (since
2182 // the block immediately before it was included).
Craig Silverstein08985b92010-11-06 01:19:03 +00002183 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00002184 DiscardUntilEndOfDirective();
Craig Silverstein08985b92010-11-06 01:19:03 +00002185 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00002186
2187 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00002188 if (CurPPLexer->popConditionalLevel(CI)) {
2189 Diag(ElifToken, diag::pp_err_elif_without_if);
2190 return;
2191 }
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Chris Lattner141e71f2008-03-09 01:54:53 +00002193 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002194 if (CurPPLexer->getConditionalStackDepth() == 0)
2195 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00002196
Chris Lattner141e71f2008-03-09 01:54:53 +00002197 // If this is a #elif with a #else before it, report the error.
2198 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002199
2200 if (Callbacks)
2201 Callbacks->Elif(ElifToken.getLocation(),
2202 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +00002203
Craig Silverstein08985b92010-11-06 01:19:03 +00002204 // Finally, skip the rest of the contents of this block.
2205 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00002206 /*FoundElse*/CI.FoundElse,
2207 ElifToken.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00002208}