blob: c8e1f4fc3e297927c6022e9aa52a513c8413b85b [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
Chris Lattnerf47724b2010-08-17 15:55:45 +000060MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
61 MacroInfo *MI = AllocateMacroInfo();
62 new (MI) MacroInfo(MacroToClone, BP);
63 return MI;
64}
65
James Dennettdc201692012-06-22 05:46:07 +000066/// \brief Release the specified MacroInfo to be reused for allocating
67/// new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000068void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenek9714a232010-10-19 22:15:20 +000069 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
70 if (MacroInfoChain *Prev = MIChain->Prev) {
71 MacroInfoChain *Next = MIChain->Next;
72 Prev->Next = Next;
73 if (Next)
74 Next->Prev = Prev;
75 }
76 else {
77 assert(MIChainHead == MIChain);
78 MIChainHead = MIChain->Next;
79 MIChainHead->Prev = 0;
80 }
81 MIChain->Next = MICache;
82 MICache = MIChain;
Chris Lattner0301b3f2009-02-20 22:19:20 +000083
Ted Kremenek9714a232010-10-19 22:15:20 +000084 MI->Destroy();
85}
Chris Lattner0301b3f2009-02-20 22:19:20 +000086
James Dennettdc201692012-06-22 05:46:07 +000087/// \brief Read and discard all tokens remaining on the current line until
88/// the tok::eod token is found.
Chris Lattner141e71f2008-03-09 01:54:53 +000089void Preprocessor::DiscardUntilEndOfDirective() {
90 Token Tmp;
91 do {
92 LexUnexpandedToken(Tmp);
Peter Collingbournea5ef5842011-02-22 13:49:06 +000093 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne84021552011-02-28 02:37:51 +000094 } while (Tmp.isNot(tok::eod));
Chris Lattner141e71f2008-03-09 01:54:53 +000095}
96
James Dennettdc201692012-06-22 05:46:07 +000097/// \brief Lex and validate a macro name, which occurs after a
98/// \#define or \#undef.
99///
100/// This sets the token kind to eod and discards the rest
101/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
102/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
103/// else (e.g. \#ifdef).
Chris Lattner141e71f2008-03-09 01:54:53 +0000104void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
105 // Read the token, don't allow macro expansion on it.
106 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000108 if (MacroNameTok.is(tok::code_completion)) {
109 if (CodeComplete)
110 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000111 setCodeCompletionReached();
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000112 LexUnexpandedToken(MacroNameTok);
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000113 }
114
Chris Lattner141e71f2008-03-09 01:54:53 +0000115 // Missing macro name?
Peter Collingbourne84021552011-02-28 02:37:51 +0000116 if (MacroNameTok.is(tok::eod)) {
Chris Lattner3692b092008-11-18 07:59:24 +0000117 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
118 return;
119 }
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattner141e71f2008-03-09 01:54:53 +0000121 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
122 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +0000123 bool Invalid = false;
124 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
125 if (Invalid)
126 return;
Nico Weberf4fb07e2012-02-29 22:54:43 +0000127
Chris Lattner9485d232008-12-13 20:12:40 +0000128 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weberf4fb07e2012-02-29 22:54:43 +0000129
130 // Allow #defining |and| and friends in microsoft mode.
David Blaikie4e4d0842012-03-11 07:00:24 +0000131 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weberf4fb07e2012-02-29 22:54:43 +0000132 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
133 return;
134 }
135
Chris Lattner9485d232008-12-13 20:12:40 +0000136 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000137 // C++ 2.5p2: Alternative tokens behave the same as its primary token
138 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000139 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +0000140 else
141 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
142 // Fall through on error.
143 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
144 // Error if defining "defined": C99 6.10.8.4.
145 Diag(MacroNameTok, diag::err_defined_macro_name);
146 } else if (isDefineUndef && II->hasMacroDefinition() &&
147 getMacroInfo(II)->isBuiltinMacro()) {
148 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
149 if (isDefineUndef == 1)
150 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
151 else
152 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
153 } else {
154 // Okay, we got a good identifier node. Return it.
155 return;
156 }
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Chris Lattner141e71f2008-03-09 01:54:53 +0000158 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne84021552011-02-28 02:37:51 +0000159 // token kind to tok::eod.
160 MacroNameTok.setKind(tok::eod);
Chris Lattner141e71f2008-03-09 01:54:53 +0000161 return DiscardUntilEndOfDirective();
162}
163
James Dennettdc201692012-06-22 05:46:07 +0000164/// \brief Ensure that the next token is a tok::eod token.
165///
166/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattnerab82f412009-04-17 23:30:53 +0000167/// true, then we consider macros that expand to zero tokens as being ok.
168void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000169 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000170 // Lex unexpanded tokens for most directives: macros might expand to zero
171 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
172 // #line) allow empty macros.
173 if (EnableMacros)
174 Lex(Tmp);
175 else
176 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Chris Lattner141e71f2008-03-09 01:54:53 +0000178 // There should be no tokens after the directive, but we allow them as an
179 // extension.
180 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
181 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Peter Collingbourne84021552011-02-28 02:37:51 +0000183 if (Tmp.isNot(tok::eod)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000184 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000185 // or if this is a macro-style preprocessing directive, because it is more
186 // trouble than it is worth to insert /**/ and check that there is no /**/
187 // in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000188 FixItHint Hint;
David Blaikie4e4d0842012-03-11 07:00:24 +0000189 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000190 !CurTokenLexer)
Douglas Gregor849b2432010-03-31 17:46:05 +0000191 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
192 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000193 DiscardUntilEndOfDirective();
194 }
195}
196
197
198
James Dennettdc201692012-06-22 05:46:07 +0000199/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
200/// decided that the subsequent tokens are in the \#if'd out portion of the
201/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattner141e71f2008-03-09 01:54:53 +0000202/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettdc201692012-06-22 05:46:07 +0000203/// this \#if directive, so \#else/\#elif blocks should never be entered.
204/// If ElseOk is true, then \#else directives are ok, if not, then we have
205/// already seen one so a \#else directive is a duplicate. When this returns,
206/// the caller can lex the first valid token.
Chris Lattner141e71f2008-03-09 01:54:53 +0000207void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
208 bool FoundNonSkipPortion,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000209 bool FoundElse,
210 SourceLocation ElseLoc) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000211 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000212 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000213
Ted Kremenek60e45d42008-11-18 00:34:22 +0000214 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000215 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Ted Kremenek268ee702008-12-12 18:34:08 +0000217 if (CurPTHLexer) {
218 PTHSkipExcludedConditionalBlock();
219 return;
220 }
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Chris Lattner141e71f2008-03-09 01:54:53 +0000222 // Enter raw mode to disable identifier lookup (and thus macro expansion),
223 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000224 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000225 Token Tok;
226 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000227 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Douglas Gregorf44e8542010-08-24 19:08:16 +0000229 if (Tok.is(tok::code_completion)) {
230 if (CodeComplete)
231 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000232 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000233 continue;
234 }
235
Chris Lattner141e71f2008-03-09 01:54:53 +0000236 // If this is the end of the buffer, we have an error.
237 if (Tok.is(tok::eof)) {
238 // Emit errors for each unterminated conditional on the stack, including
239 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000240 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000241 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000242 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
243 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000244 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000245 }
246
Chris Lattner141e71f2008-03-09 01:54:53 +0000247 // Just return and let the caller lex after this #include.
248 break;
249 }
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattner141e71f2008-03-09 01:54:53 +0000251 // If this token is not a preprocessor directive, just skip it.
252 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
253 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattner141e71f2008-03-09 01:54:53 +0000255 // We just parsed a # character at the start of a line, so we're in
256 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne84021552011-02-28 02:37:51 +0000257 // converted into an EOD token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000258 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000259 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000260
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Chris Lattner141e71f2008-03-09 01:54:53 +0000262 // Read the next token, the directive flavor.
263 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Chris Lattner141e71f2008-03-09 01:54:53 +0000265 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
266 // something bogus), skip it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000267 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000268 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000269 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000270 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000271 continue;
272 }
273
274 // If the first letter isn't i or e, it isn't intesting to us. We know that
275 // this is safe in the face of spelling differences, because there is no way
276 // to spell an i/e in a strange way that is another letter. Skipping this
277 // allows us to avoid looking up the identifier info for #define/#undef and
278 // other common directives.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000279 const char *RawCharData = Tok.getRawIdentifierData();
280
Chris Lattner141e71f2008-03-09 01:54:53 +0000281 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000282 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000283 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000284 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000285 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000286 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000287 continue;
288 }
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattner141e71f2008-03-09 01:54:53 +0000290 // Get the identifier name without trigraphs or embedded newlines. Note
291 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
292 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000293 char DirectiveBuf[20];
Chris Lattner5f9e2722011-07-23 10:55:15 +0000294 StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000295 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000296 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000297 } else {
298 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000299 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000300 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000301 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000302 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000303 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000304 continue;
305 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000306 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000307 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000308 }
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000310 if (Directive.startswith("if")) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000311 StringRef Sub = Directive.substr(2);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000312 if (Sub.empty() || // "if"
313 Sub == "def" || // "ifdef"
314 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000315 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
316 // bother parsing the condition.
317 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000318 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000319 /*foundnonskip*/false,
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000320 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000321 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000322 } else if (Directive[0] == 'e') {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000323 StringRef Sub = Directive.substr(1);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000324 if (Sub == "ndif") { // "endif"
Chris Lattner141e71f2008-03-09 01:54:53 +0000325 PPConditionalInfo CondInfo;
326 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000327 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000328 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattner141e71f2008-03-09 01:54:53 +0000329 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Chris Lattner141e71f2008-03-09 01:54:53 +0000331 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000332 if (!CondInfo.WasSkipping) {
Richard Smithbc9e5582012-06-24 23:56:26 +0000333 // Restore the value of LexingRawMode so that trailing comments
334 // are handled correctly, if we've reached the outermost block.
335 CurPPLexer->LexingRawMode = false;
Richard Smith986f3172012-06-21 00:35:03 +0000336 CheckEndOfDirective("endif");
Richard Smithbc9e5582012-06-24 23:56:26 +0000337 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000338 if (Callbacks)
339 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000340 break;
Richard Smith986f3172012-06-21 00:35:03 +0000341 } else {
342 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000343 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000344 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000345 // #else directive in a skipping conditional. If not in some other
346 // skipping conditional, and if #else hasn't already been seen, enter it
347 // as a non-skipping conditional.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000348 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Chris Lattner141e71f2008-03-09 01:54:53 +0000350 // If this is a #else with a #else before it, report the error.
351 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Chris Lattner141e71f2008-03-09 01:54:53 +0000353 // Note that we've seen a #else in this conditional.
354 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Chris Lattner141e71f2008-03-09 01:54:53 +0000356 // If the conditional is at the top level, and the #if block wasn't
357 // entered, enter the #else block now.
358 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
359 CondInfo.FoundNonSkip = true;
Richard Smithbc9e5582012-06-24 23:56:26 +0000360 // Restore the value of LexingRawMode so that trailing comments
361 // are handled correctly.
362 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000363 CheckEndOfDirective("else");
Richard Smithbc9e5582012-06-24 23:56:26 +0000364 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000365 if (Callbacks)
366 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000367 break;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000368 } else {
369 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattner141e71f2008-03-09 01:54:53 +0000370 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000371 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000372 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000373
374 bool ShouldEnter;
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000375 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +0000376 // If this is in a skipping block or if we're already handled this #if
377 // block, don't bother parsing the condition.
378 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
379 DiscardUntilEndOfDirective();
380 ShouldEnter = false;
381 } else {
382 // Restore the value of LexingRawMode so that identifiers are
383 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000384 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
385 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000386 IdentifierInfo *IfNDefMacro = 0;
387 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000388 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000389 }
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000390 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner141e71f2008-03-09 01:54:53 +0000392 // If this is a #elif with a #else before it, report the error.
393 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattner141e71f2008-03-09 01:54:53 +0000395 // If this condition is true, enter it!
396 if (ShouldEnter) {
397 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000398 if (Callbacks)
399 Callbacks->Elif(Tok.getLocation(),
400 SourceRange(ConditionalBegin, ConditionalEnd),
401 CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000402 break;
403 }
404 }
405 }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Ted Kremenek60e45d42008-11-18 00:34:22 +0000407 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000408 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000409 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000410 }
411
412 // Finally, if we are out of the conditional (saw an #endif or ran off the end
413 // of the file, just stop skipping and return to lexing whatever came after
414 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000415 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000416
417 if (Callbacks) {
418 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
419 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
420 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000421}
422
Ted Kremenek268ee702008-12-12 18:34:08 +0000423void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000424
425 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000426 assert(CurPTHLexer);
427 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Ted Kremenek268ee702008-12-12 18:34:08 +0000429 // Skip to the next '#else', '#elif', or #endif.
430 if (CurPTHLexer->SkipBlock()) {
431 // We have reached an #endif. Both the '#' and 'endif' tokens
432 // have been consumed by the PTHLexer. Just pop off the condition level.
433 PPConditionalInfo CondInfo;
434 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000435 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek268ee702008-12-12 18:34:08 +0000436 assert(!InCond && "Can't be skipping if not in a conditional!");
437 break;
438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Ted Kremenek268ee702008-12-12 18:34:08 +0000440 // We have reached a '#else' or '#elif'. Lex the next token to get
441 // the directive flavor.
442 Token Tok;
443 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Ted Kremenek268ee702008-12-12 18:34:08 +0000445 // We can actually look up the IdentifierInfo here since we aren't in
446 // raw mode.
447 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
448
449 if (K == tok::pp_else) {
450 // #else: Enter the else condition. We aren't in a nested condition
451 // since we skip those. We're always in the one matching the last
452 // blocked we skipped.
453 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
454 // Note that we've seen a #else in this conditional.
455 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Ted Kremenek268ee702008-12-12 18:34:08 +0000457 // If the #if block wasn't entered then enter the #else block now.
458 if (!CondInfo.FoundNonSkip) {
459 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Peter Collingbourne84021552011-02-28 02:37:51 +0000461 // Scan until the eod token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000462 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000463 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000464 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Ted Kremenek268ee702008-12-12 18:34:08 +0000466 break;
467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Ted Kremenek268ee702008-12-12 18:34:08 +0000469 // Otherwise skip this block.
470 continue;
471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Ted Kremenek268ee702008-12-12 18:34:08 +0000473 assert(K == tok::pp_elif);
474 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
475
476 // If this is a #elif with a #else before it, report the error.
477 if (CondInfo.FoundElse)
478 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Ted Kremenek268ee702008-12-12 18:34:08 +0000480 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000481 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000482 if (CondInfo.FoundNonSkip)
483 continue;
484
485 // Evaluate the condition of the #elif.
486 IdentifierInfo *IfNDefMacro = 0;
487 CurPTHLexer->ParsingPreprocessorDirective = true;
488 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
489 CurPTHLexer->ParsingPreprocessorDirective = false;
490
491 // If this condition is true, enter it!
492 if (ShouldEnter) {
493 CondInfo.FoundNonSkip = true;
494 break;
495 }
496
497 // Otherwise, skip this block and go to the next one.
498 continue;
499 }
500}
501
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000502const FileEntry *Preprocessor::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000503 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000504 bool isAngled,
505 const DirectoryLookup *FromDir,
506 const DirectoryLookup *&CurDir,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000507 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000508 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000509 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000510 bool SkipCache) {
Chris Lattner10725092008-03-09 04:17:44 +0000511 // If the header lookup mechanism may be relative to the current file, pass in
512 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000513 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000514 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000515 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000516 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000518 // If there is no file entry associated with this file, it must be the
519 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000520 // it won't be scanned for preprocessor directives. If we have the
521 // predefines buffer, resolve #include references (which come from the
522 // -include command line argument) as if they came from the main file, this
523 // affects file lookup etc.
524 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000525 FID = SourceMgr.getMainFileID();
526 CurFileEnt = SourceMgr.getFileEntryForID(FID);
527 }
Chris Lattner10725092008-03-09 04:17:44 +0000528 }
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Chris Lattner10725092008-03-09 04:17:44 +0000530 // Do a standard file entry lookup.
531 CurDir = CurDirLookup;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000532 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +0000533 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000534 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000535 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner10725092008-03-09 04:17:44 +0000537 // Otherwise, see if this is a subframework header. If so, this is relative
538 // to one of the headers on the #include stack. Walk the list of the current
539 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000540 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000541 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000542 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregor1b58c742013-02-08 00:10:48 +0000543 SearchPath, RelativePath,
544 SuggestedModule)))
Chris Lattner10725092008-03-09 04:17:44 +0000545 return FE;
546 }
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Chris Lattner10725092008-03-09 04:17:44 +0000548 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
549 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000550 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000551 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000552 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek74124942011-04-26 21:50:03 +0000553 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregor1b58c742013-02-08 00:10:48 +0000554 Filename, CurFileEnt, SearchPath, RelativePath,
555 SuggestedModule)))
Chris Lattner10725092008-03-09 04:17:44 +0000556 return FE;
557 }
558 }
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner10725092008-03-09 04:17:44 +0000560 // Otherwise, we really couldn't find the file.
561 return 0;
562}
563
Chris Lattner141e71f2008-03-09 01:54:53 +0000564
565//===----------------------------------------------------------------------===//
566// Preprocessor Directive Handling.
567//===----------------------------------------------------------------------===//
568
David Blaikie8c0b3782012-06-06 18:52:13 +0000569class Preprocessor::ResetMacroExpansionHelper {
570public:
571 ResetMacroExpansionHelper(Preprocessor *pp)
572 : PP(pp), save(pp->DisableMacroExpansion) {
573 if (pp->MacroExpansionInDirectivesOverride)
574 pp->DisableMacroExpansion = false;
575 }
576 ~ResetMacroExpansionHelper() {
577 PP->DisableMacroExpansion = save;
578 }
579private:
580 Preprocessor *PP;
581 bool save;
582};
583
Chris Lattner141e71f2008-03-09 01:54:53 +0000584/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000585/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000586/// lexer/preprocessor state, and advances the lexer(s) so that the next token
587/// read is the correct one.
588void Preprocessor::HandleDirective(Token &Result) {
589 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chris Lattner141e71f2008-03-09 01:54:53 +0000591 // We just parsed a # character at the start of a line, so we're in directive
592 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne84021552011-02-28 02:37:51 +0000593 // EOD token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000594 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chris Lattner141e71f2008-03-09 01:54:53 +0000596 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000597
Chris Lattner141e71f2008-03-09 01:54:53 +0000598 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000599 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000600 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000601 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Chris Lattner42aa16c2009-03-18 21:00:25 +0000603 // Save the '#' token in case we need to return it later.
604 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Chris Lattner141e71f2008-03-09 01:54:53 +0000606 // Read the next token, the directive flavor. This isn't expanded due to
607 // C99 6.10.3p8.
608 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Chris Lattner141e71f2008-03-09 01:54:53 +0000610 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
611 // #define A(x) #x
612 // A(abc
613 // #warning blah
614 // def)
Richard Smitha3ca4d62011-12-16 22:50:01 +0000615 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
616 // not support this for #include-like directives, since that can result in
617 // terrible diagnostics, and does not work in GCC.
618 if (InMacroArgs) {
619 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
620 switch (II->getPPKeywordID()) {
621 case tok::pp_include:
622 case tok::pp_import:
623 case tok::pp_include_next:
624 case tok::pp___include_macros:
625 Diag(Result, diag::err_embedded_include) << II->getName();
626 DiscardUntilEndOfDirective();
627 return;
628 default:
629 break;
630 }
631 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000632 Diag(Result, diag::ext_embedded_directive);
Richard Smitha3ca4d62011-12-16 22:50:01 +0000633 }
Mike Stump1eb44332009-09-09 15:08:12 +0000634
David Blaikie8c0b3782012-06-06 18:52:13 +0000635 // Temporarily enable macro expansion if set so
636 // and reset to previous state when returning from this function.
637 ResetMacroExpansionHelper helper(this);
638
Chris Lattner141e71f2008-03-09 01:54:53 +0000639TryAgain:
640 switch (Result.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000641 case tok::eod:
Chris Lattner141e71f2008-03-09 01:54:53 +0000642 return; // null directive.
643 case tok::comment:
644 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
645 LexUnexpandedToken(Result);
646 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000647 case tok::code_completion:
648 if (CodeComplete)
649 CodeComplete->CodeCompleteDirective(
650 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000651 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000652 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000653 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikie4e4d0842012-03-11 07:00:24 +0000654 if (getLangOpts().AsmPreprocessor)
Chris Lattner5f607c42009-03-18 20:41:10 +0000655 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000656 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000657 default:
658 IdentifierInfo *II = Result.getIdentifierInfo();
659 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Chris Lattner141e71f2008-03-09 01:54:53 +0000661 // Ask what the preprocessor keyword ID is.
662 switch (II->getPPKeywordID()) {
663 default: break;
664 // C99 6.10.1 - Conditional Inclusion.
665 case tok::pp_if:
666 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
667 case tok::pp_ifdef:
668 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
669 case tok::pp_ifndef:
670 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
671 case tok::pp_elif:
672 return HandleElifDirective(Result);
673 case tok::pp_else:
674 return HandleElseDirective(Result);
675 case tok::pp_endif:
676 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Chris Lattner141e71f2008-03-09 01:54:53 +0000678 // C99 6.10.2 - Source File Inclusion.
679 case tok::pp_include:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000680 // Handle #include.
681 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000682 case tok::pp___include_macros:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000683 // Handle -imacros.
684 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattner141e71f2008-03-09 01:54:53 +0000686 // C99 6.10.3 - Macro Replacement.
687 case tok::pp_define:
688 return HandleDefineDirective(Result);
689 case tok::pp_undef:
690 return HandleUndefDirective(Result);
691
692 // C99 6.10.4 - Line Control.
693 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000694 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Chris Lattner141e71f2008-03-09 01:54:53 +0000696 // C99 6.10.5 - Error Directive.
697 case tok::pp_error:
698 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Chris Lattner141e71f2008-03-09 01:54:53 +0000700 // C99 6.10.6 - Pragma Directive.
701 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000702 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Chris Lattner141e71f2008-03-09 01:54:53 +0000704 // GNU Extensions.
705 case tok::pp_import:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000706 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000707 case tok::pp_include_next:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000708 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattner141e71f2008-03-09 01:54:53 +0000710 case tok::pp_warning:
711 Diag(Result, diag::ext_pp_warning_directive);
712 return HandleUserDiagnosticDirective(Result, true);
713 case tok::pp_ident:
714 return HandleIdentSCCSDirective(Result);
715 case tok::pp_sccs:
716 return HandleIdentSCCSDirective(Result);
717 case tok::pp_assert:
718 //isExtension = true; // FIXME: implement #assert
719 break;
720 case tok::pp_unassert:
721 //isExtension = true; // FIXME: implement #unassert
722 break;
Douglas Gregor7143aab2011-09-01 17:04:32 +0000723
Douglas Gregor1ac13c32012-01-03 19:48:16 +0000724 case tok::pp___public_macro:
David Blaikie4e4d0842012-03-11 07:00:24 +0000725 if (getLangOpts().Modules)
Douglas Gregor94ad28b2012-01-03 18:24:14 +0000726 return HandleMacroPublicDirective(Result);
727 break;
728
Douglas Gregor1ac13c32012-01-03 19:48:16 +0000729 case tok::pp___private_macro:
David Blaikie4e4d0842012-03-11 07:00:24 +0000730 if (getLangOpts().Modules)
Douglas Gregor94ad28b2012-01-03 18:24:14 +0000731 return HandleMacroPrivateDirective(Result);
732 break;
Chris Lattner141e71f2008-03-09 01:54:53 +0000733 }
734 break;
735 }
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Chris Lattner42aa16c2009-03-18 21:00:25 +0000737 // If this is a .S file, treat unknown # directives as non-preprocessor
738 // directives. This is important because # may be a comment or introduce
739 // various pseudo-ops. Just return the # token and push back the following
740 // token to be lexed next time.
David Blaikie4e4d0842012-03-11 07:00:24 +0000741 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000742 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000743 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000744 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000745 Toks[1] = Result;
Chris Lattnerba3ca522011-01-06 05:01:51 +0000746
747 // If the second token is a hashhash token, then we need to translate it to
748 // unknown so the token lexer doesn't try to perform token pasting.
749 if (Result.is(tok::hashhash))
750 Toks[1].setKind(tok::unknown);
751
Chris Lattner42aa16c2009-03-18 21:00:25 +0000752 // Enter this token stream so that we re-lex the tokens. Make sure to
753 // enable macro expansion, in case the token after the # is an identifier
754 // that is expanded.
755 EnterTokenStream(Toks, 2, false, true);
756 return;
757 }
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Chris Lattner141e71f2008-03-09 01:54:53 +0000759 // If we reached here, the preprocessing token is not valid!
760 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattner141e71f2008-03-09 01:54:53 +0000762 // Read the rest of the PP line.
763 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner141e71f2008-03-09 01:54:53 +0000765 // Okay, we're done parsing the directive.
766}
767
Chris Lattner478a18e2009-01-26 06:19:46 +0000768/// GetLineValue - Convert a numeric token into an unsigned value, emitting
769/// Diagnostic DiagID if it is invalid, and returning the value in Val.
770static bool GetLineValue(Token &DigitTok, unsigned &Val,
771 unsigned DiagID, Preprocessor &PP) {
772 if (DigitTok.isNot(tok::numeric_constant)) {
773 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Peter Collingbourne84021552011-02-28 02:37:51 +0000775 if (DigitTok.isNot(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000776 PP.DiscardUntilEndOfDirective();
777 return true;
778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000780 SmallString<64> IntegerBuffer;
Chris Lattner478a18e2009-01-26 06:19:46 +0000781 IntegerBuffer.resize(DigitTok.getLength());
782 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000783 bool Invalid = false;
784 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
785 if (Invalid)
786 return true;
787
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000788 // Verify that we have a simple digit-sequence, and compute the value. This
789 // is always a simple digit string computed in decimal, so we do this manually
790 // here.
791 Val = 0;
792 for (unsigned i = 0; i != ActualLength; ++i) {
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000793 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000794 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
795 diag::err_pp_line_digit_sequence);
796 PP.DiscardUntilEndOfDirective();
797 return true;
798 }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000800 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
801 if (NextVal < Val) { // overflow.
802 PP.Diag(DigitTok, DiagID);
803 PP.DiscardUntilEndOfDirective();
804 return true;
805 }
806 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000807 }
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Fariborz Jahanian540f9ae2012-06-26 21:19:20 +0000809 if (DigitTokBegin[0] == '0' && Val)
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000810 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Chris Lattner478a18e2009-01-26 06:19:46 +0000812 return false;
813}
814
James Dennettdc201692012-06-22 05:46:07 +0000815/// \brief Handle a \#line directive: C99 6.10.4.
816///
817/// The two acceptable forms are:
818/// \verbatim
Chris Lattner359cc442009-01-26 05:29:08 +0000819/// # line digit-sequence
820/// # line digit-sequence "s-char-sequence"
James Dennettdc201692012-06-22 05:46:07 +0000821/// \endverbatim
Chris Lattner359cc442009-01-26 05:29:08 +0000822void Preprocessor::HandleLineDirective(Token &Tok) {
823 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
824 // expanded.
825 Token DigitTok;
826 Lex(DigitTok);
827
Chris Lattner359cc442009-01-26 05:29:08 +0000828 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000829 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000830 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000831 return;
Fariborz Jahanian540f9ae2012-06-26 21:19:20 +0000832
833 if (LineNo == 0)
834 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner359cc442009-01-26 05:29:08 +0000835
Chris Lattner478a18e2009-01-26 06:19:46 +0000836 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
837 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman158ebfb2011-10-10 23:35:28 +0000838 unsigned LineLimit = 32768U;
Richard Smith80ad52f2013-01-02 11:42:31 +0000839 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman158ebfb2011-10-10 23:35:28 +0000840 LineLimit = 2147483648U;
Chris Lattner359cc442009-01-26 05:29:08 +0000841 if (LineNo >= LineLimit)
842 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith80ad52f2013-01-02 11:42:31 +0000843 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smith661a9962011-10-15 01:18:56 +0000844 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Chris Lattner5b9a5042009-01-26 07:57:50 +0000846 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000847 Token StrTok;
848 Lex(StrTok);
849
Peter Collingbourne84021552011-02-28 02:37:51 +0000850 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
851 // string followed by eod.
852 if (StrTok.is(tok::eod))
Chris Lattner359cc442009-01-26 05:29:08 +0000853 ; // ok
854 else if (StrTok.isNot(tok::string_literal)) {
855 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smith99831e42012-03-06 03:21:47 +0000856 return DiscardUntilEndOfDirective();
857 } else if (StrTok.hasUDSuffix()) {
858 Diag(StrTok, diag::err_invalid_string_udl);
859 return DiscardUntilEndOfDirective();
Chris Lattner359cc442009-01-26 05:29:08 +0000860 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000861 // Parse and validate the string, converting it into a unique ID.
862 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000863 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000864 if (Literal.hadError)
865 return DiscardUntilEndOfDirective();
866 if (Literal.Pascal) {
867 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
868 return DiscardUntilEndOfDirective();
869 }
Jay Foad65aa6882011-06-21 15:13:30 +0000870 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Peter Collingbourne84021552011-02-28 02:37:51 +0000872 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattnerab82f412009-04-17 23:30:53 +0000873 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
874 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000875 }
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Chris Lattner4c4ea172009-02-03 21:52:55 +0000877 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Chris Lattner16629382009-03-27 17:13:49 +0000879 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000880 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
881 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000882 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000883}
884
Chris Lattner478a18e2009-01-26 06:19:46 +0000885/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
886/// marker directive.
887static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
888 bool &IsSystemHeader, bool &IsExternCHeader,
889 Preprocessor &PP) {
890 unsigned FlagVal;
891 Token FlagTok;
892 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000893 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000894 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
895 return true;
896
897 if (FlagVal == 1) {
898 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner478a18e2009-01-26 06:19:46 +0000900 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000901 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000902 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
903 return true;
904 } else if (FlagVal == 2) {
905 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Chris Lattner137b6a62009-02-04 06:25:26 +0000907 SourceManager &SM = PP.getSourceManager();
908 // If we are leaving the current presumed file, check to make sure the
909 // presumed include stack isn't empty!
910 FileID CurFileID =
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000911 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner137b6a62009-02-04 06:25:26 +0000912 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000913 if (PLoc.isInvalid())
914 return true;
915
Chris Lattner137b6a62009-02-04 06:25:26 +0000916 // If there is no include loc (main file) or if the include loc is in a
917 // different physical file, then we aren't in a "1" line marker flag region.
918 SourceLocation IncLoc = PLoc.getIncludeLoc();
919 if (IncLoc.isInvalid() ||
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000920 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner137b6a62009-02-04 06:25:26 +0000921 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
922 PP.DiscardUntilEndOfDirective();
923 return true;
924 }
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Chris Lattner478a18e2009-01-26 06:19:46 +0000926 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000927 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000928 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
929 return true;
930 }
931
932 // We must have 3 if there are still flags.
933 if (FlagVal != 3) {
934 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000935 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000936 return true;
937 }
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner478a18e2009-01-26 06:19:46 +0000939 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Chris Lattner478a18e2009-01-26 06:19:46 +0000941 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000942 if (FlagTok.is(tok::eod)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000943 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000944 return true;
945
946 // We must have 4 if there is yet another flag.
947 if (FlagVal != 4) {
948 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000949 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000950 return true;
951 }
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Chris Lattner478a18e2009-01-26 06:19:46 +0000953 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Chris Lattner478a18e2009-01-26 06:19:46 +0000955 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000956 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000957
958 // There are no more valid flags here.
959 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000960 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000961 return true;
962}
963
964/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
965/// one of the following forms:
966///
967/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000968/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000969/// # 42 "file" ('1' | '2')? '3' '4'?
970///
971void Preprocessor::HandleDigitDirective(Token &DigitTok) {
972 // Validate the number and convert it to an unsigned. GNU does not have a
973 // line # limit other than it fit in 32-bits.
974 unsigned LineNo;
975 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
976 *this))
977 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattner478a18e2009-01-26 06:19:46 +0000979 Token StrTok;
980 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Chris Lattner478a18e2009-01-26 06:19:46 +0000982 bool IsFileEntry = false, IsFileExit = false;
983 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000984 int FilenameID = -1;
985
Peter Collingbourne84021552011-02-28 02:37:51 +0000986 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
987 // string followed by eod.
988 if (StrTok.is(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000989 ; // ok
990 else if (StrTok.isNot(tok::string_literal)) {
991 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000992 return DiscardUntilEndOfDirective();
Richard Smith99831e42012-03-06 03:21:47 +0000993 } else if (StrTok.hasUDSuffix()) {
994 Diag(StrTok, diag::err_invalid_string_udl);
995 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000996 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000997 // Parse and validate the string, converting it into a unique ID.
998 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000999 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +00001000 if (Literal.hadError)
1001 return DiscardUntilEndOfDirective();
1002 if (Literal.Pascal) {
1003 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1004 return DiscardUntilEndOfDirective();
1005 }
Jay Foad65aa6882011-06-21 15:13:30 +00001006 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattner478a18e2009-01-26 06:19:46 +00001008 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +00001009 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +00001010 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +00001011 return;
Chris Lattner478a18e2009-01-26 06:19:46 +00001012 }
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Chris Lattner9d79eba2009-02-04 05:21:58 +00001014 // Create a line note with this information.
1015 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +00001016 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +00001017 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Chris Lattner16629382009-03-27 17:13:49 +00001019 // If the preprocessor has callbacks installed, notify them of the #line
1020 // change. This is used so that the line marker comes out in -E mode for
1021 // example.
1022 if (Callbacks) {
1023 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1024 if (IsFileEntry)
1025 Reason = PPCallbacks::EnterFile;
1026 else if (IsFileExit)
1027 Reason = PPCallbacks::ExitFile;
1028 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1029 if (IsExternCHeader)
1030 FileKind = SrcMgr::C_ExternCSystem;
1031 else if (IsSystemHeader)
1032 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Chris Lattner86d0ef72010-04-14 04:28:50 +00001034 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +00001035 }
Chris Lattner478a18e2009-01-26 06:19:46 +00001036}
1037
1038
Chris Lattner099dd052009-01-26 05:30:54 +00001039/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1040///
Mike Stump1eb44332009-09-09 15:08:12 +00001041void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001042 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +00001043 // PTH doesn't emit #warning or #error directives.
1044 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +00001045 return CurPTHLexer->DiscardToEndOfLine();
1046
Chris Lattner141e71f2008-03-09 01:54:53 +00001047 // Read the rest of the line raw. We do this because we don't want macros
1048 // to be expanded and we don't require that the tokens be valid preprocessing
1049 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1050 // collapse multiple consequtive white space between tokens, but this isn't
1051 // specified by the standard.
Benjamin Kramer3093b202012-05-18 19:32:16 +00001052 SmallString<128> Message;
1053 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek34a2c422012-02-02 00:16:13 +00001054
1055 // Find the first non-whitespace character, so that we can make the
1056 // diagnostic more succinct.
Benjamin Kramer3093b202012-05-18 19:32:16 +00001057 StringRef Msg = Message.str().ltrim(" ");
1058
Chris Lattner359cc442009-01-26 05:29:08 +00001059 if (isWarning)
Ted Kremenek34a2c422012-02-02 00:16:13 +00001060 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner359cc442009-01-26 05:29:08 +00001061 else
Ted Kremenek34a2c422012-02-02 00:16:13 +00001062 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattner141e71f2008-03-09 01:54:53 +00001063}
1064
1065/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1066///
1067void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1068 // Yes, this directive is an extension.
1069 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattner141e71f2008-03-09 01:54:53 +00001071 // Read the string argument.
1072 Token StrTok;
1073 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Chris Lattner141e71f2008-03-09 01:54:53 +00001075 // If the token kind isn't a string, it's a malformed directive.
1076 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +00001077 StrTok.isNot(tok::wide_string_literal)) {
1078 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne84021552011-02-28 02:37:51 +00001079 if (StrTok.isNot(tok::eod))
Chris Lattner099dd052009-01-26 05:30:54 +00001080 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +00001081 return;
1082 }
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Richard Smith99831e42012-03-06 03:21:47 +00001084 if (StrTok.hasUDSuffix()) {
1085 Diag(StrTok, diag::err_invalid_string_udl);
1086 return DiscardUntilEndOfDirective();
1087 }
1088
Peter Collingbourne84021552011-02-28 02:37:51 +00001089 // Verify that there is nothing after the string, other than EOD.
Chris Lattner35410d52009-04-14 05:07:49 +00001090 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +00001091
Douglas Gregor453091c2010-03-16 22:30:13 +00001092 if (Callbacks) {
1093 bool Invalid = false;
1094 std::string Str = getSpelling(StrTok, &Invalid);
1095 if (!Invalid)
1096 Callbacks->Ident(Tok.getLocation(), Str);
1097 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001098}
1099
Douglas Gregor94ad28b2012-01-03 18:24:14 +00001100/// \brief Handle a #public directive.
1101void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor7143aab2011-09-01 17:04:32 +00001102 Token MacroNameTok;
1103 ReadMacroName(MacroNameTok, 2);
1104
1105 // Error reading macro name? If so, diagnostic already issued.
1106 if (MacroNameTok.is(tok::eod))
1107 return;
1108
Douglas Gregor1ac13c32012-01-03 19:48:16 +00001109 // Check to see if this is the last token on the #__public_macro line.
1110 CheckEndOfDirective("__public_macro");
Douglas Gregor7143aab2011-09-01 17:04:32 +00001111
1112 // Okay, we finally have a valid identifier to undef.
1113 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1114
1115 // If the macro is not defined, this is an error.
1116 if (MI == 0) {
Douglas Gregoraa93a872011-10-17 15:32:29 +00001117 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor7143aab2011-09-01 17:04:32 +00001118 << MacroNameTok.getIdentifierInfo();
1119 return;
1120 }
1121
1122 // Note that this macro has now been exported.
Douglas Gregoraa93a872011-10-17 15:32:29 +00001123 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1124
1125 // If this macro definition came from a PCH file, mark it
1126 // as having changed since serialization.
1127 if (MI->isFromAST())
1128 MI->setChangedAfterLoad();
1129}
1130
Douglas Gregor94ad28b2012-01-03 18:24:14 +00001131/// \brief Handle a #private directive.
Douglas Gregoraa93a872011-10-17 15:32:29 +00001132void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1133 Token MacroNameTok;
1134 ReadMacroName(MacroNameTok, 2);
1135
1136 // Error reading macro name? If so, diagnostic already issued.
1137 if (MacroNameTok.is(tok::eod))
1138 return;
1139
Douglas Gregor1ac13c32012-01-03 19:48:16 +00001140 // Check to see if this is the last token on the #__private_macro line.
1141 CheckEndOfDirective("__private_macro");
Douglas Gregoraa93a872011-10-17 15:32:29 +00001142
1143 // Okay, we finally have a valid identifier to undef.
1144 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1145
1146 // If the macro is not defined, this is an error.
1147 if (MI == 0) {
1148 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1149 << MacroNameTok.getIdentifierInfo();
1150 return;
1151 }
1152
1153 // Note that this macro has now been marked private.
1154 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor7143aab2011-09-01 17:04:32 +00001155
1156 // If this macro definition came from a PCH file, mark it
1157 // as having changed since serialization.
1158 if (MI->isFromAST())
1159 MI->setChangedAfterLoad();
1160}
1161
Chris Lattner141e71f2008-03-09 01:54:53 +00001162//===----------------------------------------------------------------------===//
1163// Preprocessor Include Directive Handling.
1164//===----------------------------------------------------------------------===//
1165
1166/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettdc201692012-06-22 05:46:07 +00001167/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattner141e71f2008-03-09 01:54:53 +00001168/// true if the input filename was in <>'s or false if it were in ""'s. The
1169/// caller is expected to provide a buffer that is large enough to hold the
1170/// spelling of the filename, but is also expected to handle the case when
1171/// this method decides to use a different buffer.
1172bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001173 StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001174 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +00001175 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Chris Lattner141e71f2008-03-09 01:54:53 +00001177 // Make sure the filename is <x> or "x".
1178 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +00001179 if (Buffer[0] == '<') {
1180 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001181 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001182 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001183 return true;
1184 }
1185 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +00001186 } else if (Buffer[0] == '"') {
1187 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001188 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001189 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001190 return true;
1191 }
1192 isAngled = false;
1193 } else {
1194 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001195 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001196 return true;
1197 }
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Chris Lattner141e71f2008-03-09 01:54:53 +00001199 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +00001200 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001201 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001202 Buffer = StringRef();
Chris Lattnera1394812010-01-10 01:35:12 +00001203 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001204 }
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Chris Lattner141e71f2008-03-09 01:54:53 +00001206 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001207 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001208 return isAngled;
1209}
1210
James Dennettdc201692012-06-22 05:46:07 +00001211/// \brief Handle cases where the \#include name is expanded from a macro
1212/// as multiple tokens, which need to be glued together.
1213///
1214/// This occurs for code like:
1215/// \code
1216/// \#define FOO <a/b.h>
1217/// \#include FOO
1218/// \endcode
Chris Lattner141e71f2008-03-09 01:54:53 +00001219/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1220///
1221/// This code concatenates and consumes tokens up to the '>' token. It returns
1222/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne84021552011-02-28 02:37:51 +00001223/// the EOD marker.
John Thompsona28cc092009-10-30 13:49:06 +00001224bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001225 SmallString<128> &FilenameBuffer,
Douglas Gregorecdcb882010-10-20 22:00:55 +00001226 SourceLocation &End) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001227 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001228
John Thompsona28cc092009-10-30 13:49:06 +00001229 Lex(CurTok);
Peter Collingbourne84021552011-02-28 02:37:51 +00001230 while (CurTok.isNot(tok::eod)) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001231 End = CurTok.getLocation();
1232
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001233 // FIXME: Provide code completion for #includes.
1234 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001235 setCodeCompletionReached();
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001236 Lex(CurTok);
1237 continue;
1238 }
1239
Chris Lattner141e71f2008-03-09 01:54:53 +00001240 // Append the spelling of this token to the buffer. If there was a space
1241 // before it, add it now.
1242 if (CurTok.hasLeadingSpace())
1243 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Chris Lattner141e71f2008-03-09 01:54:53 +00001245 // Get the spelling of the token, directly into FilenameBuffer if possible.
1246 unsigned PreAppendSize = FilenameBuffer.size();
1247 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Chris Lattner141e71f2008-03-09 01:54:53 +00001249 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001250 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Chris Lattner141e71f2008-03-09 01:54:53 +00001252 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1253 if (BufPtr != &FilenameBuffer[PreAppendSize])
1254 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Chris Lattner141e71f2008-03-09 01:54:53 +00001256 // Resize FilenameBuffer to the correct size.
1257 if (CurTok.getLength() != ActualLen)
1258 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Chris Lattner141e71f2008-03-09 01:54:53 +00001260 // If we found the '>' marker, return success.
1261 if (CurTok.is(tok::greater))
1262 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001263
John Thompsona28cc092009-10-30 13:49:06 +00001264 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001265 }
1266
Peter Collingbourne84021552011-02-28 02:37:51 +00001267 // If we hit the eod marker, emit an error and return true so that the caller
1268 // knows the EOD has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001269 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001270 return true;
1271}
1272
James Dennettdc201692012-06-22 05:46:07 +00001273/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1274/// the file to be included from the lexer, then include it! This is a common
1275/// routine with functionality shared between \#include, \#include_next and
1276/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001277/// specifies the file to start searching from.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001278void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1279 Token &IncludeTok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001280 const DirectoryLookup *LookupFrom,
1281 bool isImport) {
1282
1283 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001284 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Chris Lattner141e71f2008-03-09 01:54:53 +00001286 // Reserve a buffer to get the spelling.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001287 SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001288 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001289 SourceLocation End;
Douglas Gregore3a82562011-11-30 18:02:36 +00001290 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregorecdcb882010-10-20 22:00:55 +00001291
Chris Lattner141e71f2008-03-09 01:54:53 +00001292 switch (FilenameTok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +00001293 case tok::eod:
1294 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattner141e71f2008-03-09 01:54:53 +00001295 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Chris Lattner141e71f2008-03-09 01:54:53 +00001297 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001298 case tok::string_literal:
1299 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregorecdcb882010-10-20 22:00:55 +00001300 End = FilenameTok.getLocation();
Argyrios Kyrtzidiscfa1caa2012-11-01 17:52:58 +00001301 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +00001302 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Chris Lattner141e71f2008-03-09 01:54:53 +00001304 case tok::less:
1305 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1306 // case, glue the tokens together into FilenameBuffer and interpret those.
1307 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +00001308 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne84021552011-02-28 02:37:51 +00001309 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001310 Filename = FilenameBuffer.str();
Argyrios Kyrtzidiscfa1caa2012-11-01 17:52:58 +00001311 CharEnd = End.getLocWithOffset(1);
Chris Lattner141e71f2008-03-09 01:54:53 +00001312 break;
1313 default:
1314 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1315 DiscardUntilEndOfDirective();
1316 return;
1317 }
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001319 CharSourceRange FilenameRange
1320 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman4c55c542012-03-02 22:51:54 +00001321 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001322 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001323 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001324 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1325 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001326 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001327 DiscardUntilEndOfDirective();
1328 return;
1329 }
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Peter Collingbourne84021552011-02-28 02:37:51 +00001331 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001332 // we allow macros that expand to nothing after the filename, because this
1333 // falls into the category of "#include pp-tokens new-line" specified in
1334 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001335 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001336
1337 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001338 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1339 Diag(FilenameTok, diag::err_pp_include_too_deep);
1340 return;
1341 }
Mike Stump1eb44332009-09-09 15:08:12 +00001342
John McCall8dfac0b2011-09-30 05:12:12 +00001343 // Complain about attempts to #include files in an audit pragma.
1344 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1345 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1346 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1347
1348 // Immediately leave the pragma.
1349 PragmaARCCFCodeAuditedLoc = SourceLocation();
1350 }
1351
Aaron Ballman4c55c542012-03-02 22:51:54 +00001352 if (HeaderInfo.HasIncludeAliasMap()) {
1353 // Map the filename with the brackets still attached. If the name doesn't
1354 // map to anything, fall back on the filename we've already gotten the
1355 // spelling for.
1356 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1357 if (!NewName.empty())
1358 Filename = NewName;
1359 }
1360
Chris Lattner141e71f2008-03-09 01:54:53 +00001361 // Search include directories.
1362 const DirectoryLookup *CurDir;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001363 SmallString<1024> SearchPath;
1364 SmallString<1024> RelativePath;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001365 // We get the raw path only if we have 'Callbacks' to which we later pass
1366 // the path.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001367 Module *SuggestedModule = 0;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001368 const FileEntry *File = LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +00001369 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001370 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikie4e4d0842012-03-11 07:00:24 +00001371 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001372
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001373 if (Callbacks) {
1374 if (!File) {
1375 // Give the clients a chance to recover.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001376 SmallString<128> RecoveryPath;
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001377 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1378 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1379 // Add the recovery path to the list of search paths.
Daniel Dunbar1ea6bc02013-01-25 01:50:28 +00001380 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001381 HeaderInfo.AddSearchPath(DL, isAngled);
1382
1383 // Try the lookup again, skipping the cache.
1384 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikie4e4d0842012-03-11 07:00:24 +00001385 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001386 /*SkipCache*/true);
1387 }
1388 }
1389 }
1390
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001391 if (!SuggestedModule) {
1392 // Notify the callback object that we've seen an inclusion directive.
1393 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1394 FilenameRange, File,
1395 SearchPath, RelativePath,
1396 /*ImportedModule=*/0);
1397 }
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001398 }
1399
1400 if (File == 0) {
Aaron Ballmana52f5a32012-07-17 23:19:16 +00001401 if (!SuppressIncludeNotFoundError) {
1402 // If the file could not be located and it was included via angle
1403 // brackets, we can attempt a lookup as though it were a quoted path to
1404 // provide the user with a possible fixit.
1405 if (isAngled) {
1406 File = LookupFile(Filename, false, LookupFrom, CurDir,
1407 Callbacks ? &SearchPath : 0,
1408 Callbacks ? &RelativePath : 0,
1409 getLangOpts().Modules ? &SuggestedModule : 0);
1410 if (File) {
1411 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1412 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1413 Filename <<
1414 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1415 }
1416 }
1417 // If the file is still not found, just go with the vanilla diagnostic
1418 if (!File)
1419 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1420 }
1421 if (!File)
1422 return;
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001423 }
1424
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001425 // If we are supposed to import a module rather than including the header,
1426 // do so now.
Douglas Gregorc69c42e2011-11-17 22:44:56 +00001427 if (SuggestedModule) {
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001428 // Compute the module access path corresponding to this module.
1429 // FIXME: Should we have a second loadModule() overload to avoid this
1430 // extra lookup step?
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001431 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001432 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001433 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1434 FilenameTok.getLocation()));
1435 std::reverse(Path.begin(), Path.end());
1436
Douglas Gregore3a82562011-11-30 18:02:36 +00001437 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001438 SmallString<128> PathString;
Douglas Gregore3a82562011-11-30 18:02:36 +00001439 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1440 if (I)
1441 PathString += '.';
1442 PathString += Path[I].first->getName();
1443 }
1444 int IncludeKind = 0;
1445
1446 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1447 case tok::pp_include:
1448 IncludeKind = 0;
1449 break;
1450
1451 case tok::pp_import:
1452 IncludeKind = 1;
1453 break;
1454
Douglas Gregoredee9692011-11-30 18:03:26 +00001455 case tok::pp_include_next:
1456 IncludeKind = 2;
1457 break;
Douglas Gregore3a82562011-11-30 18:02:36 +00001458
1459 case tok::pp___include_macros:
1460 IncludeKind = 3;
1461 break;
1462
1463 default:
1464 llvm_unreachable("unknown include directive kind");
Douglas Gregore3a82562011-11-30 18:02:36 +00001465 }
1466
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001467 // Determine whether we are actually building the module that this
1468 // include directive maps to.
1469 bool BuildingImportedModule
David Blaikie4e4d0842012-03-11 07:00:24 +00001470 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001471
David Blaikie4e4d0842012-03-11 07:00:24 +00001472 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001473 // If we're not building the imported module, warn that we're going
1474 // to automatically turn this inclusion directive into a module import.
Douglas Gregorc13a34b2012-01-03 19:32:59 +00001475 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001476 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1477 /*IsTokenRange=*/false);
1478 Diag(HashLoc, diag::warn_auto_module_import)
1479 << IncludeKind << PathString
1480 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregor1b257af2012-12-11 22:11:52 +00001481 "@import " + PathString.str().str() + ";");
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001482 }
Douglas Gregore3a82562011-11-30 18:02:36 +00001483
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001484 // Load the module.
Douglas Gregor5e356932011-12-01 17:11:21 +00001485 // If this was an #__include_macros directive, only make macros visible.
1486 Module::NameVisibilityKind Visibility
1487 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor463d9092012-11-29 23:55:25 +00001488 ModuleLoadResult Imported
Douglas Gregor305dc3e2011-12-20 00:28:52 +00001489 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1490 /*IsIncludeDirective=*/true);
Argyrios Kyrtzidiseb788e92012-09-29 01:06:01 +00001491 assert((Imported == 0 || Imported == SuggestedModule) &&
1492 "the imported module is different than the suggested one");
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001493
1494 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001495 if (!BuildingImportedModule && Imported) {
1496 if (Callbacks) {
1497 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1498 FilenameRange, File,
1499 SearchPath, RelativePath, Imported);
1500 }
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001501 return;
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001502 }
Douglas Gregor463d9092012-11-29 23:55:25 +00001503
1504 // If we failed to find a submodule that we expected to find, we can
1505 // continue. Otherwise, there's an error in the included file, so we
1506 // don't want to include it.
1507 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1508 return;
1509 }
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001510 }
1511
1512 if (Callbacks && SuggestedModule) {
1513 // We didn't notify the callback object that we've seen an inclusion
1514 // directive before. Now that we are parsing the include normally and not
1515 // turning it to a module import, notify the callback object.
1516 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1517 FilenameRange, File,
1518 SearchPath, RelativePath,
1519 /*ImportedModule=*/0);
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001520 }
1521
Chris Lattner72181832008-09-26 20:12:23 +00001522 // The #included file will be considered to be a system header if either it is
1523 // in a system include directory, or if the #includer is a system include
1524 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001525 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001526 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001527 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001529 // Ask HeaderInfo if we should enter this #include file. If not, #including
1530 // this file will have no effect.
1531 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001532 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001533 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001534 return;
1535 }
1536
Chris Lattner141e71f2008-03-09 01:54:53 +00001537 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisdb81d382012-03-27 18:47:48 +00001538 SourceLocation IncludePos = End;
1539 // If the filename string was the result of macro expansions, set the include
1540 // position on the file where it will be included and after the expansions.
1541 if (IncludePos.isMacroID())
1542 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1543 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned57b7ff2011-06-30 16:41:03 +00001544 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattner141e71f2008-03-09 01:54:53 +00001545
1546 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001547 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001548}
1549
James Dennettdc201692012-06-22 05:46:07 +00001550/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattner141e71f2008-03-09 01:54:53 +00001551///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001552void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1553 Token &IncludeNextTok) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001554 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Chris Lattner141e71f2008-03-09 01:54:53 +00001556 // #include_next is like #include, except that we start searching after
1557 // the current found directory. If we can't do this, issue a
1558 // diagnostic.
1559 const DirectoryLookup *Lookup = CurDirLookup;
1560 if (isInPrimaryFile()) {
1561 Lookup = 0;
1562 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1563 } else if (Lookup == 0) {
1564 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1565 } else {
1566 // Start looking up in the next directory.
1567 ++Lookup;
1568 }
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Douglas Gregorecdcb882010-10-20 22:00:55 +00001570 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattner141e71f2008-03-09 01:54:53 +00001571}
1572
James Dennettdc201692012-06-22 05:46:07 +00001573/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman4207eda2012-03-18 03:10:37 +00001574void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1575 // The Microsoft #import directive takes a type library and generates header
1576 // files from it, and includes those. This is beyond the scope of what clang
1577 // does, so we ignore it and error out. However, #import can optionally have
1578 // trailing attributes that span multiple lines. We're going to eat those
1579 // so we can continue processing from there.
1580 Diag(Tok, diag::err_pp_import_directive_ms );
1581
1582 // Read tokens until we get to the end of the directive. Note that the
1583 // directive can be split over multiple lines using the backslash character.
1584 DiscardUntilEndOfDirective();
1585}
1586
James Dennettdc201692012-06-22 05:46:07 +00001587/// HandleImportDirective - Implements \#import.
Chris Lattner141e71f2008-03-09 01:54:53 +00001588///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001589void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1590 Token &ImportTok) {
Aaron Ballman4207eda2012-03-18 03:10:37 +00001591 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1592 if (LangOpts.MicrosoftMode)
1593 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001594 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman4207eda2012-03-18 03:10:37 +00001595 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00001596 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001597}
1598
Chris Lattnerde076652009-04-08 18:46:40 +00001599/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1600/// pseudo directive in the predefines buffer. This handles it by sucking all
1601/// tokens through the preprocessor and discarding them (only keeping the side
1602/// effects on the preprocessor).
Douglas Gregorecdcb882010-10-20 22:00:55 +00001603void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1604 Token &IncludeMacrosTok) {
Chris Lattnerde076652009-04-08 18:46:40 +00001605 // This directive should only occur in the predefines buffer. If not, emit an
1606 // error and reject it.
1607 SourceLocation Loc = IncludeMacrosTok.getLocation();
1608 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1609 Diag(IncludeMacrosTok.getLocation(),
1610 diag::pp_include_macros_out_of_predefines);
1611 DiscardUntilEndOfDirective();
1612 return;
1613 }
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Chris Lattnerfd105112009-04-08 20:53:24 +00001615 // Treat this as a normal #include for checking purposes. If this is
1616 // successful, it will push a new lexer onto the include stack.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001617 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Chris Lattnerfd105112009-04-08 20:53:24 +00001619 Token TmpTok;
1620 do {
1621 Lex(TmpTok);
1622 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1623 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001624}
1625
Chris Lattner141e71f2008-03-09 01:54:53 +00001626//===----------------------------------------------------------------------===//
1627// Preprocessor Macro Directive Handling.
1628//===----------------------------------------------------------------------===//
1629
1630/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1631/// definition has just been read. Lex the rest of the arguments and the
1632/// closing ), updating MI with what we learn. Return true if an error occurs
1633/// parsing the arg list.
Abramo Bagnarae2e87682012-03-31 20:17:27 +00001634bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001635 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Chris Lattner141e71f2008-03-09 01:54:53 +00001637 while (1) {
1638 LexUnexpandedToken(Tok);
1639 switch (Tok.getKind()) {
1640 case tok::r_paren:
1641 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001642 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001643 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001644 // Otherwise we have #define FOO(A,)
1645 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1646 return true;
1647 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikie4e4d0842012-03-11 07:00:24 +00001648 if (!LangOpts.C99)
Richard Smith80ad52f2013-01-02 11:42:31 +00001649 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smith661a9962011-10-15 01:18:56 +00001650 diag::warn_cxx98_compat_variadic_macro :
1651 diag::ext_variadic_macro);
Chris Lattner141e71f2008-03-09 01:54:53 +00001652
Joey Gouly617bb312013-01-17 17:35:00 +00001653 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1654 if (LangOpts.OpenCL) {
1655 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1656 return true;
1657 }
1658
Chris Lattner141e71f2008-03-09 01:54:53 +00001659 // Lex the token after the identifier.
1660 LexUnexpandedToken(Tok);
1661 if (Tok.isNot(tok::r_paren)) {
1662 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1663 return true;
1664 }
1665 // Add the __VA_ARGS__ identifier as an argument.
1666 Arguments.push_back(Ident__VA_ARGS__);
1667 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001668 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001669 return false;
Peter Collingbourne84021552011-02-28 02:37:51 +00001670 case tok::eod: // #define X(
Chris Lattner141e71f2008-03-09 01:54:53 +00001671 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1672 return true;
1673 default:
1674 // Handle keywords and identifiers here to accept things like
1675 // #define Foo(for) for.
1676 IdentifierInfo *II = Tok.getIdentifierInfo();
1677 if (II == 0) {
1678 // #define X(1
1679 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1680 return true;
1681 }
1682
1683 // If this is already used as an argument, it is used multiple times (e.g.
1684 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001685 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001686 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001687 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001688 return true;
1689 }
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Chris Lattner141e71f2008-03-09 01:54:53 +00001691 // Add the argument to the macro info.
1692 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Chris Lattner141e71f2008-03-09 01:54:53 +00001694 // Lex the token after the identifier.
1695 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Chris Lattner141e71f2008-03-09 01:54:53 +00001697 switch (Tok.getKind()) {
1698 default: // #define X(A B
1699 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1700 return true;
1701 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001702 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001703 return false;
1704 case tok::comma: // #define X(A,
1705 break;
1706 case tok::ellipsis: // #define X(A... -> GCC extension
1707 // Diagnose extension.
1708 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Chris Lattner141e71f2008-03-09 01:54:53 +00001710 // Lex the token after the identifier.
1711 LexUnexpandedToken(Tok);
1712 if (Tok.isNot(tok::r_paren)) {
1713 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1714 return true;
1715 }
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Chris Lattner141e71f2008-03-09 01:54:53 +00001717 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001718 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001719 return false;
1720 }
1721 }
1722 }
1723}
1724
James Dennettdc201692012-06-22 05:46:07 +00001725/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattner141e71f2008-03-09 01:54:53 +00001726/// line then lets the caller lex the next real token.
1727void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1728 ++NumDefined;
1729
1730 Token MacroNameTok;
1731 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Chris Lattner141e71f2008-03-09 01:54:53 +00001733 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001734 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001735 return;
1736
Chris Lattner2451b522009-04-21 04:46:33 +00001737 Token LastTok = MacroNameTok;
1738
Chris Lattner141e71f2008-03-09 01:54:53 +00001739 // If we are supposed to keep comments in #defines, reenable comment saving
1740 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001741 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Chris Lattner141e71f2008-03-09 01:54:53 +00001743 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001744 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Chris Lattner141e71f2008-03-09 01:54:53 +00001746 Token Tok;
1747 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Chris Lattner141e71f2008-03-09 01:54:53 +00001749 // If this is a function-like macro definition, parse the argument list,
1750 // marking each of the identifiers as being used as macro arguments. Also,
1751 // check other constraints on the first token of the macro body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001752 if (Tok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001753 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001754 } else if (Tok.hasLeadingSpace()) {
1755 // This is a normal token with leading space. Clear the leading space
1756 // marker on the first token to get proper expansion.
1757 Tok.clearFlag(Token::LeadingSpace);
1758 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001759 // This is a function-like macro definition. Read the argument list.
1760 MI->setIsFunctionLike();
Abramo Bagnarae2e87682012-03-31 20:17:27 +00001761 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001762 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001763 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001764 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001765 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001766 DiscardUntilEndOfDirective();
1767 return;
1768 }
1769
Chris Lattner8fde5972009-04-19 18:26:34 +00001770 // If this is a definition of a variadic C99 function-like macro, not using
1771 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Chris Lattner8fde5972009-04-19 18:26:34 +00001773 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1774 // This gets unpoisoned where it is allowed.
1775 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1776 if (MI->isC99Varargs())
1777 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Chris Lattner141e71f2008-03-09 01:54:53 +00001779 // Read the first token after the arg list for down below.
1780 LexUnexpandedToken(Tok);
Richard Smith80ad52f2013-01-02 11:42:31 +00001781 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001782 // C99 requires whitespace between the macro definition and the body. Emit
1783 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001784 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001785 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001786 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1787 // first character of a replacement list is not a character required by
1788 // subclause 5.2.1, then there shall be white-space separation between the
1789 // identifier and the replacement list.". 5.2.1 lists this set:
1790 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1791 // is irrelevant here.
1792 bool isInvalid = false;
1793 if (Tok.is(tok::at)) // @ is not in the list above.
1794 isInvalid = true;
1795 else if (Tok.is(tok::unknown)) {
1796 // If we have an unknown token, it is something strange like "`". Since
1797 // all of valid characters would have lexed into a single character
1798 // token of some sort, we know this is not a valid case.
1799 isInvalid = true;
1800 }
1801 if (isInvalid)
1802 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1803 else
1804 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001805 }
Chris Lattner2451b522009-04-21 04:46:33 +00001806
Peter Collingbourne84021552011-02-28 02:37:51 +00001807 if (!Tok.is(tok::eod))
Chris Lattner2451b522009-04-21 04:46:33 +00001808 LastTok = Tok;
1809
Chris Lattner141e71f2008-03-09 01:54:53 +00001810 // Read the rest of the macro body.
1811 if (MI->isObjectLike()) {
1812 // Object-like macros are very simple, just read their body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001813 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001814 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001815 MI->AddTokenToBody(Tok);
1816 // Get the next token of the macro.
1817 LexUnexpandedToken(Tok);
1818 }
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Chris Lattner141e71f2008-03-09 01:54:53 +00001820 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001821 // Otherwise, read the body of a function-like macro. While we are at it,
1822 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1823 // parameters in function-like macro expansions.
Peter Collingbourne84021552011-02-28 02:37:51 +00001824 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001825 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001826
Eli Friedman4fa4b482012-11-14 02:18:46 +00001827 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001828 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Chris Lattner141e71f2008-03-09 01:54:53 +00001830 // Get the next token of the macro.
1831 LexUnexpandedToken(Tok);
1832 continue;
1833 }
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Eli Friedman4fa4b482012-11-14 02:18:46 +00001835 if (Tok.is(tok::hashhash)) {
1836
1837 // If we see token pasting, check if it looks like the gcc comma
1838 // pasting extension. We'll use this information to suppress
1839 // diagnostics later on.
1840
1841 // Get the next token of the macro.
1842 LexUnexpandedToken(Tok);
1843
1844 if (Tok.is(tok::eod)) {
1845 MI->AddTokenToBody(LastTok);
1846 break;
1847 }
1848
1849 unsigned NumTokens = MI->getNumTokens();
1850 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1851 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1852 MI->setHasCommaPasting();
1853
1854 // Things look ok, add the '##' and param name tokens to the macro.
1855 MI->AddTokenToBody(LastTok);
1856 MI->AddTokenToBody(Tok);
1857 LastTok = Tok;
1858
1859 // Get the next token of the macro.
1860 LexUnexpandedToken(Tok);
1861 continue;
1862 }
1863
Chris Lattner141e71f2008-03-09 01:54:53 +00001864 // Get the next token of the macro.
1865 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Chris Lattner32404692009-05-25 17:16:10 +00001867 // Check for a valid macro arg identifier.
1868 if (Tok.getIdentifierInfo() == 0 ||
1869 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1870
1871 // If this is assembler-with-cpp mode, we accept random gibberish after
1872 // the '#' because '#' is often a comment character. However, change
1873 // the kind of the token to tok::unknown so that the preprocessor isn't
1874 // confused.
David Blaikie4e4d0842012-03-11 07:00:24 +00001875 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner32404692009-05-25 17:16:10 +00001876 LastTok.setKind(tok::unknown);
1877 } else {
1878 Diag(Tok, diag::err_pp_stringize_not_parameter);
1879 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Chris Lattner32404692009-05-25 17:16:10 +00001881 // Disable __VA_ARGS__ again.
1882 Ident__VA_ARGS__->setIsPoisoned(true);
1883 return;
1884 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001885 }
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Chris Lattner32404692009-05-25 17:16:10 +00001887 // Things look ok, add the '#' and param name tokens to the macro.
1888 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001889 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001890 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Chris Lattner141e71f2008-03-09 01:54:53 +00001892 // Get the next token of the macro.
1893 LexUnexpandedToken(Tok);
1894 }
1895 }
Mike Stump1eb44332009-09-09 15:08:12 +00001896
1897
Chris Lattner141e71f2008-03-09 01:54:53 +00001898 // Disable __VA_ARGS__ again.
1899 Ident__VA_ARGS__->setIsPoisoned(true);
1900
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001901 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattner141e71f2008-03-09 01:54:53 +00001902 // replacement list.
1903 unsigned NumTokens = MI->getNumTokens();
1904 if (NumTokens != 0) {
1905 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1906 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001907 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001908 return;
1909 }
1910 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1911 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001912 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001913 return;
1914 }
1915 }
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Chris Lattner2451b522009-04-21 04:46:33 +00001917 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Chris Lattner141e71f2008-03-09 01:54:53 +00001919 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8a64bb52012-08-29 00:20:03 +00001920 // the macro bodies are identical, and issue diagnostics if they are not.
Chris Lattner141e71f2008-03-09 01:54:53 +00001921 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001922 // It is very common for system headers to have tons of macro redefinitions
1923 // and for warnings to be disabled in system headers. If this is the case,
1924 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001925 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001926 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001927 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner41c3ae12009-01-16 19:50:11 +00001928 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001929
Chris Lattnerf47724b2010-08-17 15:55:45 +00001930 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001931 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001932 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001933 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001934 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1935 << MacroNameTok.getIdentifierInfo();
1936 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1937 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001938 }
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001939 if (OtherMI->isWarnIfUnused())
1940 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattner141e71f2008-03-09 01:54:53 +00001941 }
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Chris Lattner141e71f2008-03-09 01:54:53 +00001943 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001945 assert(!MI->isUsed());
1946 // If we need warning for not using the macro, add its location in the
1947 // warn-because-unused-macro set. If it gets used it will be removed from set.
1948 if (isInPrimaryFile() && // don't warn for include'd macros.
1949 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikied6471f72011-09-25 23:23:43 +00001950 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001951 MI->setIsWarnIfUnused(true);
1952 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1953 }
1954
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001955 // If the callbacks want to know, tell them about the macro definition.
1956 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001957 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001958}
1959
James Dennettdc201692012-06-22 05:46:07 +00001960/// HandleUndefDirective - Implements \#undef.
Chris Lattner141e71f2008-03-09 01:54:53 +00001961///
1962void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1963 ++NumUndefined;
1964
1965 Token MacroNameTok;
1966 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Chris Lattner141e71f2008-03-09 01:54:53 +00001968 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001969 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001970 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Chris Lattner141e71f2008-03-09 01:54:53 +00001972 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001973 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Chris Lattner141e71f2008-03-09 01:54:53 +00001975 // Okay, we finally have a valid identifier to undef.
1976 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Argyrios Kyrtzidis36845472013-01-16 16:52:44 +00001978 // If the callbacks want to know, tell them about the macro #undef.
1979 // Note: no matter if the macro was defined or not.
1980 if (Callbacks)
1981 Callbacks->MacroUndefined(MacroNameTok, MI);
1982
Chris Lattner141e71f2008-03-09 01:54:53 +00001983 // If the macro is not defined, this is a noop undef, just return.
1984 if (MI == 0) return;
1985
Argyrios Kyrtzidis1f8dcfc2011-07-11 20:39:47 +00001986 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattner141e71f2008-03-09 01:54:53 +00001987 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001988
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001989 if (MI->isWarnIfUnused())
1990 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1991
Douglas Gregora8235d62012-10-09 23:05:51 +00001992 UndefineMacro(MacroNameTok.getIdentifierInfo(), MI,
1993 MacroNameTok.getLocation());
1994}
1995
1996void Preprocessor::UndefineMacro(IdentifierInfo *II, MacroInfo *MI,
1997 SourceLocation UndefLoc) {
1998 MI->setUndefLoc(UndefLoc);
1999 if (MI->isFromAST()) {
2000 MI->setChangedAfterLoad();
2001 if (Listener)
2002 Listener->UndefinedMacro(MI);
2003 }
2004
2005 clearMacroInfo(II);
Chris Lattner141e71f2008-03-09 01:54:53 +00002006}
2007
2008
2009//===----------------------------------------------------------------------===//
2010// Preprocessor Conditional Directive Handling.
2011//===----------------------------------------------------------------------===//
2012
James Dennettdc201692012-06-22 05:46:07 +00002013/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2014/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2015/// true if any tokens have been returned or pp-directives activated before this
2016/// \#ifndef has been lexed.
Chris Lattner141e71f2008-03-09 01:54:53 +00002017///
2018void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2019 bool ReadAnyTokensBeforeDirective) {
2020 ++NumIf;
2021 Token DirectiveTok = Result;
2022
2023 Token MacroNameTok;
2024 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Chris Lattner141e71f2008-03-09 01:54:53 +00002026 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00002027 if (MacroNameTok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002028 // Skip code until we get to #endif. This helps with recovery by not
2029 // emitting an error when the #endif is reached.
2030 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2031 /*Foundnonskip*/false, /*FoundElse*/false);
2032 return;
2033 }
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Chris Lattner141e71f2008-03-09 01:54:53 +00002035 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00002036 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00002037
Chris Lattner13d283d2010-02-12 08:03:27 +00002038 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2039 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002040
Ted Kremenek60e45d42008-11-18 00:34:22 +00002041 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00002042 // If the start of a top-level #ifdef and if the macro is not defined,
2043 // inform MIOpt that this might be the start of a proper include guard.
2044 // Otherwise it is some other form of unknown conditional which we can't
2045 // handle.
2046 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002047 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00002048 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00002049 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00002050 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00002051 }
2052
Chris Lattner141e71f2008-03-09 01:54:53 +00002053 // If there is a macro, process it.
2054 if (MI) // Mark it used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002055 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002057 if (Callbacks) {
2058 if (isIfndef)
Argyrios Kyrtzidis61c1c8e2012-12-08 02:21:11 +00002059 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MI);
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002060 else
Argyrios Kyrtzidis61c1c8e2012-12-08 02:21:11 +00002061 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MI);
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002062 }
2063
Chris Lattner141e71f2008-03-09 01:54:53 +00002064 // Should we include the stuff contained by this directive?
2065 if (!MI == isIfndef) {
2066 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00002067 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2068 /*wasskip*/false, /*foundnonskip*/true,
2069 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00002070 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00002071 // No, skip the contents of this block.
Chris Lattner141e71f2008-03-09 01:54:53 +00002072 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002073 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002074 /*FoundElse*/false);
2075 }
2076}
2077
James Dennettdc201692012-06-22 05:46:07 +00002078/// HandleIfDirective - Implements the \#if directive.
Chris Lattner141e71f2008-03-09 01:54:53 +00002079///
2080void Preprocessor::HandleIfDirective(Token &IfToken,
2081 bool ReadAnyTokensBeforeDirective) {
Aaron Ballman31672b12013-01-16 19:32:21 +00002082 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00002083 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Craig Silverstein08985b92010-11-06 01:19:03 +00002085 // Parse and evaluate the conditional expression.
Chris Lattner141e71f2008-03-09 01:54:53 +00002086 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein08985b92010-11-06 01:19:03 +00002087 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2088 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2089 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes0049db62008-06-01 18:31:24 +00002090
2091 // If this condition is equivalent to #ifndef X, and if this is the first
2092 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002093 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00002094 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00002095 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00002096 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00002097 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00002098 }
2099
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002100 if (Callbacks)
2101 Callbacks->If(IfToken.getLocation(),
2102 SourceRange(ConditionalBegin, ConditionalEnd));
2103
Chris Lattner141e71f2008-03-09 01:54:53 +00002104 // Should we include the stuff contained by this directive?
2105 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002106 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002107 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002108 /*foundnonskip*/true, /*foundelse*/false);
2109 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00002110 // No, skip the contents of this block.
Mike Stump1eb44332009-09-09 15:08:12 +00002111 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002112 /*FoundElse*/false);
2113 }
2114}
2115
James Dennettdc201692012-06-22 05:46:07 +00002116/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattner141e71f2008-03-09 01:54:53 +00002117///
2118void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2119 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Chris Lattner141e71f2008-03-09 01:54:53 +00002121 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00002122 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Chris Lattner141e71f2008-03-09 01:54:53 +00002124 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00002125 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002126 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00002127 Diag(EndifToken, diag::err_pp_endif_without_if);
2128 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00002129 }
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Chris Lattner141e71f2008-03-09 01:54:53 +00002131 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002132 if (CurPPLexer->getConditionalStackDepth() == 0)
2133 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Ted Kremenek60e45d42008-11-18 00:34:22 +00002135 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00002136 "This code should only be reachable in the non-skipping case!");
Craig Silverstein08985b92010-11-06 01:19:03 +00002137
2138 if (Callbacks)
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002139 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +00002140}
2141
James Dennettdc201692012-06-22 05:46:07 +00002142/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein08985b92010-11-06 01:19:03 +00002143///
Chris Lattner141e71f2008-03-09 01:54:53 +00002144void Preprocessor::HandleElseDirective(Token &Result) {
2145 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Chris Lattner141e71f2008-03-09 01:54:53 +00002147 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00002148 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Chris Lattner141e71f2008-03-09 01:54:53 +00002150 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00002151 if (CurPPLexer->popConditionalLevel(CI)) {
2152 Diag(Result, diag::pp_err_else_without_if);
2153 return;
2154 }
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Chris Lattner141e71f2008-03-09 01:54:53 +00002156 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002157 if (CurPPLexer->getConditionalStackDepth() == 0)
2158 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00002159
2160 // If this is a #else with a #else before it, report the error.
2161 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00002162
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002163 if (Callbacks)
2164 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2165
Craig Silverstein08985b92010-11-06 01:19:03 +00002166 // Finally, skip the rest of the contents of this block.
2167 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00002168 /*FoundElse*/true, Result.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00002169}
2170
James Dennettdc201692012-06-22 05:46:07 +00002171/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein08985b92010-11-06 01:19:03 +00002172///
Chris Lattner141e71f2008-03-09 01:54:53 +00002173void Preprocessor::HandleElifDirective(Token &ElifToken) {
Aaron Ballman31672b12013-01-16 19:32:21 +00002174 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00002175 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Chris Lattner141e71f2008-03-09 01:54:53 +00002177 // #elif directive in a non-skipping conditional... start skipping.
2178 // We don't care what the condition is, because we will always skip it (since
2179 // the block immediately before it was included).
Craig Silverstein08985b92010-11-06 01:19:03 +00002180 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00002181 DiscardUntilEndOfDirective();
Craig Silverstein08985b92010-11-06 01:19:03 +00002182 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00002183
2184 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00002185 if (CurPPLexer->popConditionalLevel(CI)) {
2186 Diag(ElifToken, diag::pp_err_elif_without_if);
2187 return;
2188 }
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Chris Lattner141e71f2008-03-09 01:54:53 +00002190 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002191 if (CurPPLexer->getConditionalStackDepth() == 0)
2192 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Chris Lattner141e71f2008-03-09 01:54:53 +00002194 // If this is a #elif with a #else before it, report the error.
2195 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002196
2197 if (Callbacks)
2198 Callbacks->Elif(ElifToken.getLocation(),
2199 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +00002200
Craig Silverstein08985b92010-11-06 01:19:03 +00002201 // Finally, skip the rest of the contents of this block.
2202 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00002203 /*FoundElse*/CI.FoundElse,
2204 ElifToken.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00002205}