blob: ba3291aa398dad2123a0f9ecad20994c66521029 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettdc201692012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattner141e71f2008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner6e290142009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/LexDiagnostic.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/ModuleLoader.h"
24#include "clang/Lex/Pragma.h"
Chris Lattner359cc442009-01-26 05:29:08 +000025#include "llvm/ADT/APInt.h"
Douglas Gregore3a82562011-11-30 18:02:36 +000026#include "llvm/Support/ErrorHandling.h"
Aaron Ballman31672b12013-01-16 19:32:21 +000027#include "llvm/Support/SaveAndRestore.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000028using namespace clang;
29
30//===----------------------------------------------------------------------===//
31// Utility Methods for Preprocessor Directive Handling.
32//===----------------------------------------------------------------------===//
33
Chris Lattnerf47724b2010-08-17 15:55:45 +000034MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenek9714a232010-10-19 22:15:20 +000035 MacroInfoChain *MIChain;
Mike Stump1eb44332009-09-09 15:08:12 +000036
Ted Kremenek9714a232010-10-19 22:15:20 +000037 if (MICache) {
38 MIChain = MICache;
39 MICache = MICache->Next;
Ted Kremenekaf8fa252010-10-19 18:16:54 +000040 }
Ted Kremenek9714a232010-10-19 22:15:20 +000041 else {
42 MIChain = BP.Allocate<MacroInfoChain>();
43 }
44
45 MIChain->Next = MIChainHead;
46 MIChain->Prev = 0;
47 if (MIChainHead)
48 MIChainHead->Prev = MIChain;
49 MIChainHead = MIChain;
50
51 return &(MIChain->MI);
Chris Lattnerf47724b2010-08-17 15:55:45 +000052}
53
54MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
55 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000056 new (MI) MacroInfo(L);
57 return MI;
58}
59
Argyrios Kyrtzidisbaa74bd2013-03-22 21:12:51 +000060MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
61 unsigned SubModuleID) {
62 LLVM_STATIC_ASSERT(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
63 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidis3e25b992013-04-30 05:05:35 +000064 DeserializedMacroInfoChain *MIChain =
65 BP.Allocate<DeserializedMacroInfoChain>();
66 MIChain->Next = DeserialMIChainHead;
67 DeserialMIChainHead = MIChain;
68
69 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidisbaa74bd2013-03-22 21:12:51 +000070 new (MI) MacroInfo(L);
71 MI->FromASTFile = true;
72 MI->setOwningModuleID(SubModuleID);
73 return MI;
74}
75
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +000076DefMacroDirective *
77Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc,
78 bool isImported) {
79 DefMacroDirective *MD = BP.Allocate<DefMacroDirective>();
80 new (MD) DefMacroDirective(MI, Loc, isImported);
81 return MD;
82}
83
84UndefMacroDirective *
85Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
86 UndefMacroDirective *MD = BP.Allocate<UndefMacroDirective>();
87 new (MD) UndefMacroDirective(UndefLoc);
88 return MD;
89}
90
91VisibilityMacroDirective *
92Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
93 bool isPublic) {
94 VisibilityMacroDirective *MD = BP.Allocate<VisibilityMacroDirective>();
95 new (MD) VisibilityMacroDirective(Loc, isPublic);
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000096 return MD;
Chris Lattnerf47724b2010-08-17 15:55:45 +000097}
98
James Dennettdc201692012-06-22 05:46:07 +000099/// \brief Release the specified MacroInfo to be reused for allocating
100/// new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +0000101void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenek9714a232010-10-19 22:15:20 +0000102 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
103 if (MacroInfoChain *Prev = MIChain->Prev) {
104 MacroInfoChain *Next = MIChain->Next;
105 Prev->Next = Next;
106 if (Next)
107 Next->Prev = Prev;
108 }
109 else {
110 assert(MIChainHead == MIChain);
111 MIChainHead = MIChain->Next;
112 MIChainHead->Prev = 0;
113 }
114 MIChain->Next = MICache;
115 MICache = MIChain;
Chris Lattner0301b3f2009-02-20 22:19:20 +0000116
Ted Kremenek9714a232010-10-19 22:15:20 +0000117 MI->Destroy();
118}
Chris Lattner0301b3f2009-02-20 22:19:20 +0000119
James Dennettdc201692012-06-22 05:46:07 +0000120/// \brief Read and discard all tokens remaining on the current line until
121/// the tok::eod token is found.
Chris Lattner141e71f2008-03-09 01:54:53 +0000122void Preprocessor::DiscardUntilEndOfDirective() {
123 Token Tmp;
124 do {
125 LexUnexpandedToken(Tmp);
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000126 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne84021552011-02-28 02:37:51 +0000127 } while (Tmp.isNot(tok::eod));
Chris Lattner141e71f2008-03-09 01:54:53 +0000128}
129
James Dennettdc201692012-06-22 05:46:07 +0000130/// \brief Lex and validate a macro name, which occurs after a
131/// \#define or \#undef.
132///
133/// This sets the token kind to eod and discards the rest
134/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
135/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
136/// else (e.g. \#ifdef).
Chris Lattner141e71f2008-03-09 01:54:53 +0000137void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
138 // Read the token, don't allow macro expansion on it.
139 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000141 if (MacroNameTok.is(tok::code_completion)) {
142 if (CodeComplete)
143 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000144 setCodeCompletionReached();
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000145 LexUnexpandedToken(MacroNameTok);
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000146 }
147
Chris Lattner141e71f2008-03-09 01:54:53 +0000148 // Missing macro name?
Peter Collingbourne84021552011-02-28 02:37:51 +0000149 if (MacroNameTok.is(tok::eod)) {
Chris Lattner3692b092008-11-18 07:59:24 +0000150 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
151 return;
152 }
Mike Stump1eb44332009-09-09 15:08:12 +0000153
Chris Lattner141e71f2008-03-09 01:54:53 +0000154 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
155 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +0000156 bool Invalid = false;
157 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
158 if (Invalid)
159 return;
Nico Weberf4fb07e2012-02-29 22:54:43 +0000160
Chris Lattner9485d232008-12-13 20:12:40 +0000161 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weberf4fb07e2012-02-29 22:54:43 +0000162
163 // Allow #defining |and| and friends in microsoft mode.
David Blaikie4e4d0842012-03-11 07:00:24 +0000164 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weberf4fb07e2012-02-29 22:54:43 +0000165 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
166 return;
167 }
168
Chris Lattner9485d232008-12-13 20:12:40 +0000169 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000170 // C++ 2.5p2: Alternative tokens behave the same as its primary token
171 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000172 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +0000173 else
174 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
175 // Fall through on error.
176 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Richard Smitheed55e62013-03-06 00:46:00 +0000177 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
Chris Lattner141e71f2008-03-09 01:54:53 +0000178 Diag(MacroNameTok, diag::err_defined_macro_name);
Richard Smitheed55e62013-03-06 00:46:00 +0000179 } else if (isDefineUndef == 2 && II->hasMacroDefinition() &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000180 getMacroInfo(II)->isBuiltinMacro()) {
Richard Smitheed55e62013-03-06 00:46:00 +0000181 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
182 // and C++ [cpp.predefined]p4], but allow it as an extension.
183 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
184 return;
Chris Lattner141e71f2008-03-09 01:54:53 +0000185 } else {
186 // Okay, we got a good identifier node. Return it.
187 return;
188 }
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Chris Lattner141e71f2008-03-09 01:54:53 +0000190 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne84021552011-02-28 02:37:51 +0000191 // token kind to tok::eod.
192 MacroNameTok.setKind(tok::eod);
Chris Lattner141e71f2008-03-09 01:54:53 +0000193 return DiscardUntilEndOfDirective();
194}
195
James Dennettdc201692012-06-22 05:46:07 +0000196/// \brief Ensure that the next token is a tok::eod token.
197///
198/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattnerab82f412009-04-17 23:30:53 +0000199/// true, then we consider macros that expand to zero tokens as being ok.
200void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000201 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000202 // Lex unexpanded tokens for most directives: macros might expand to zero
203 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
204 // #line) allow empty macros.
205 if (EnableMacros)
206 Lex(Tmp);
207 else
208 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Chris Lattner141e71f2008-03-09 01:54:53 +0000210 // There should be no tokens after the directive, but we allow them as an
211 // extension.
212 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
213 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Peter Collingbourne84021552011-02-28 02:37:51 +0000215 if (Tmp.isNot(tok::eod)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000216 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000217 // or if this is a macro-style preprocessing directive, because it is more
218 // trouble than it is worth to insert /**/ and check that there is no /**/
219 // in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000220 FixItHint Hint;
David Blaikie4e4d0842012-03-11 07:00:24 +0000221 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000222 !CurTokenLexer)
Douglas Gregor849b2432010-03-31 17:46:05 +0000223 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
224 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000225 DiscardUntilEndOfDirective();
226 }
227}
228
229
230
James Dennettdc201692012-06-22 05:46:07 +0000231/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
232/// decided that the subsequent tokens are in the \#if'd out portion of the
233/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattner141e71f2008-03-09 01:54:53 +0000234/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettdc201692012-06-22 05:46:07 +0000235/// this \#if directive, so \#else/\#elif blocks should never be entered.
236/// If ElseOk is true, then \#else directives are ok, if not, then we have
237/// already seen one so a \#else directive is a duplicate. When this returns,
238/// the caller can lex the first valid token.
Chris Lattner141e71f2008-03-09 01:54:53 +0000239void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
240 bool FoundNonSkipPortion,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000241 bool FoundElse,
242 SourceLocation ElseLoc) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000243 ++NumSkipped;
David Blaikie7247c882013-05-15 07:37:26 +0000244 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000245
Ted Kremenek60e45d42008-11-18 00:34:22 +0000246 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000247 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Ted Kremenek268ee702008-12-12 18:34:08 +0000249 if (CurPTHLexer) {
250 PTHSkipExcludedConditionalBlock();
251 return;
252 }
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattner141e71f2008-03-09 01:54:53 +0000254 // Enter raw mode to disable identifier lookup (and thus macro expansion),
255 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000256 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000257 Token Tok;
258 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000259 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Douglas Gregorf44e8542010-08-24 19:08:16 +0000261 if (Tok.is(tok::code_completion)) {
262 if (CodeComplete)
263 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000264 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000265 continue;
266 }
267
Chris Lattner141e71f2008-03-09 01:54:53 +0000268 // If this is the end of the buffer, we have an error.
269 if (Tok.is(tok::eof)) {
270 // Emit errors for each unterminated conditional on the stack, including
271 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000272 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000273 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000274 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
275 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000276 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000277 }
278
Chris Lattner141e71f2008-03-09 01:54:53 +0000279 // Just return and let the caller lex after this #include.
280 break;
281 }
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattner141e71f2008-03-09 01:54:53 +0000283 // If this token is not a preprocessor directive, just skip it.
284 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
285 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Chris Lattner141e71f2008-03-09 01:54:53 +0000287 // We just parsed a # character at the start of a line, so we're in
288 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne84021552011-02-28 02:37:51 +0000289 // converted into an EOD token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000290 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosec7d1ca52013-02-22 00:32:00 +0000291 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000292
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattner141e71f2008-03-09 01:54:53 +0000294 // Read the next token, the directive flavor.
295 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Chris Lattner141e71f2008-03-09 01:54:53 +0000297 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
298 // something bogus), skip it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000299 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000300 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000301 // Restore comment saving mode.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000302 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 continue;
304 }
305
306 // If the first letter isn't i or e, it isn't intesting to us. We know that
307 // this is safe in the face of spelling differences, because there is no way
308 // to spell an i/e in a strange way that is another letter. Skipping this
309 // allows us to avoid looking up the identifier info for #define/#undef and
310 // other common directives.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000311 const char *RawCharData = Tok.getRawIdentifierData();
312
Chris Lattner141e71f2008-03-09 01:54:53 +0000313 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000314 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000315 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000316 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000317 // Restore comment saving mode.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000318 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattner141e71f2008-03-09 01:54:53 +0000319 continue;
320 }
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner141e71f2008-03-09 01:54:53 +0000322 // Get the identifier name without trigraphs or embedded newlines. Note
323 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
324 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000325 char DirectiveBuf[20];
Chris Lattner5f9e2722011-07-23 10:55:15 +0000326 StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000327 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000328 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000329 } else {
330 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000331 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000332 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000333 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000334 // Restore comment saving mode.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000335 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattner141e71f2008-03-09 01:54:53 +0000336 continue;
337 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000338 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000339 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000340 }
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000342 if (Directive.startswith("if")) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000343 StringRef Sub = Directive.substr(2);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000344 if (Sub.empty() || // "if"
345 Sub == "def" || // "ifdef"
346 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000347 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
348 // bother parsing the condition.
349 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000350 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000351 /*foundnonskip*/false,
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000352 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000353 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000354 } else if (Directive[0] == 'e') {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000355 StringRef Sub = Directive.substr(1);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000356 if (Sub == "ndif") { // "endif"
Chris Lattner141e71f2008-03-09 01:54:53 +0000357 PPConditionalInfo CondInfo;
358 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000359 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000360 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattner141e71f2008-03-09 01:54:53 +0000361 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner141e71f2008-03-09 01:54:53 +0000363 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000364 if (!CondInfo.WasSkipping) {
Richard Smithbc9e5582012-06-24 23:56:26 +0000365 // Restore the value of LexingRawMode so that trailing comments
366 // are handled correctly, if we've reached the outermost block.
367 CurPPLexer->LexingRawMode = false;
Richard Smith986f3172012-06-21 00:35:03 +0000368 CheckEndOfDirective("endif");
Richard Smithbc9e5582012-06-24 23:56:26 +0000369 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000370 if (Callbacks)
371 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000372 break;
Richard Smith986f3172012-06-21 00:35:03 +0000373 } else {
374 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000375 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000376 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000377 // #else directive in a skipping conditional. If not in some other
378 // skipping conditional, and if #else hasn't already been seen, enter it
379 // as a non-skipping conditional.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000380 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner141e71f2008-03-09 01:54:53 +0000382 // If this is a #else with a #else before it, report the error.
383 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Chris Lattner141e71f2008-03-09 01:54:53 +0000385 // Note that we've seen a #else in this conditional.
386 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Chris Lattner141e71f2008-03-09 01:54:53 +0000388 // If the conditional is at the top level, and the #if block wasn't
389 // entered, enter the #else block now.
390 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
391 CondInfo.FoundNonSkip = true;
Richard Smithbc9e5582012-06-24 23:56:26 +0000392 // Restore the value of LexingRawMode so that trailing comments
393 // are handled correctly.
394 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000395 CheckEndOfDirective("else");
Richard Smithbc9e5582012-06-24 23:56:26 +0000396 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000397 if (Callbacks)
398 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000399 break;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000400 } else {
401 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattner141e71f2008-03-09 01:54:53 +0000402 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000403 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000404 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000405
406 bool ShouldEnter;
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000407 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +0000408 // If this is in a skipping block or if we're already handled this #if
409 // block, don't bother parsing the condition.
410 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
411 DiscardUntilEndOfDirective();
412 ShouldEnter = false;
413 } else {
414 // Restore the value of LexingRawMode so that identifiers are
415 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000416 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
417 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000418 IdentifierInfo *IfNDefMacro = 0;
419 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000420 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000421 }
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000422 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattner141e71f2008-03-09 01:54:53 +0000424 // If this is a #elif with a #else before it, report the error.
425 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Chris Lattner141e71f2008-03-09 01:54:53 +0000427 // If this condition is true, enter it!
428 if (ShouldEnter) {
429 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000430 if (Callbacks)
431 Callbacks->Elif(Tok.getLocation(),
432 SourceRange(ConditionalBegin, ConditionalEnd),
433 CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000434 break;
435 }
436 }
437 }
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Ted Kremenek60e45d42008-11-18 00:34:22 +0000439 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000440 // Restore comment saving mode.
Jordan Rose6aad4a32013-02-21 18:53:19 +0000441 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattner141e71f2008-03-09 01:54:53 +0000442 }
443
444 // Finally, if we are out of the conditional (saw an #endif or ran off the end
445 // of the file, just stop skipping and return to lexing whatever came after
446 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000447 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000448
449 if (Callbacks) {
450 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
451 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
452 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000453}
454
Ted Kremenek268ee702008-12-12 18:34:08 +0000455void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000456
457 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000458 assert(CurPTHLexer);
459 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Ted Kremenek268ee702008-12-12 18:34:08 +0000461 // Skip to the next '#else', '#elif', or #endif.
462 if (CurPTHLexer->SkipBlock()) {
463 // We have reached an #endif. Both the '#' and 'endif' tokens
464 // have been consumed by the PTHLexer. Just pop off the condition level.
465 PPConditionalInfo CondInfo;
466 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000467 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek268ee702008-12-12 18:34:08 +0000468 assert(!InCond && "Can't be skipping if not in a conditional!");
469 break;
470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Ted Kremenek268ee702008-12-12 18:34:08 +0000472 // We have reached a '#else' or '#elif'. Lex the next token to get
473 // the directive flavor.
474 Token Tok;
475 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Ted Kremenek268ee702008-12-12 18:34:08 +0000477 // We can actually look up the IdentifierInfo here since we aren't in
478 // raw mode.
479 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
480
481 if (K == tok::pp_else) {
482 // #else: Enter the else condition. We aren't in a nested condition
483 // since we skip those. We're always in the one matching the last
484 // blocked we skipped.
485 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
486 // Note that we've seen a #else in this conditional.
487 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Ted Kremenek268ee702008-12-12 18:34:08 +0000489 // If the #if block wasn't entered then enter the #else block now.
490 if (!CondInfo.FoundNonSkip) {
491 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Peter Collingbourne84021552011-02-28 02:37:51 +0000493 // Scan until the eod token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000494 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000495 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000496 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Ted Kremenek268ee702008-12-12 18:34:08 +0000498 break;
499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Ted Kremenek268ee702008-12-12 18:34:08 +0000501 // Otherwise skip this block.
502 continue;
503 }
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Ted Kremenek268ee702008-12-12 18:34:08 +0000505 assert(K == tok::pp_elif);
506 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
507
508 // If this is a #elif with a #else before it, report the error.
509 if (CondInfo.FoundElse)
510 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Ted Kremenek268ee702008-12-12 18:34:08 +0000512 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000513 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000514 if (CondInfo.FoundNonSkip)
515 continue;
516
517 // Evaluate the condition of the #elif.
518 IdentifierInfo *IfNDefMacro = 0;
519 CurPTHLexer->ParsingPreprocessorDirective = true;
520 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
521 CurPTHLexer->ParsingPreprocessorDirective = false;
522
523 // If this condition is true, enter it!
524 if (ShouldEnter) {
525 CondInfo.FoundNonSkip = true;
526 break;
527 }
528
529 // Otherwise, skip this block and go to the next one.
530 continue;
531 }
532}
533
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000534const FileEntry *Preprocessor::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000535 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000536 bool isAngled,
537 const DirectoryLookup *FromDir,
538 const DirectoryLookup *&CurDir,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000539 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000540 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000541 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000542 bool SkipCache) {
Chris Lattner10725092008-03-09 04:17:44 +0000543 // If the header lookup mechanism may be relative to the current file, pass in
544 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000545 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000546 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000547 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000548 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000550 // If there is no file entry associated with this file, it must be the
551 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000552 // it won't be scanned for preprocessor directives. If we have the
553 // predefines buffer, resolve #include references (which come from the
554 // -include command line argument) as if they came from the main file, this
555 // affects file lookup etc.
556 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000557 FID = SourceMgr.getMainFileID();
558 CurFileEnt = SourceMgr.getFileEntryForID(FID);
559 }
Chris Lattner10725092008-03-09 04:17:44 +0000560 }
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Chris Lattner10725092008-03-09 04:17:44 +0000562 // Do a standard file entry lookup.
563 CurDir = CurDirLookup;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000564 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +0000565 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000566 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000567 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattner10725092008-03-09 04:17:44 +0000569 // Otherwise, see if this is a subframework header. If so, this is relative
570 // to one of the headers on the #include stack. Walk the list of the current
571 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000572 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000573 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000574 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregor1b58c742013-02-08 00:10:48 +0000575 SearchPath, RelativePath,
576 SuggestedModule)))
Chris Lattner10725092008-03-09 04:17:44 +0000577 return FE;
578 }
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Chris Lattner10725092008-03-09 04:17:44 +0000580 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
581 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000582 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000583 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000584 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek74124942011-04-26 21:50:03 +0000585 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregor1b58c742013-02-08 00:10:48 +0000586 Filename, CurFileEnt, SearchPath, RelativePath,
587 SuggestedModule)))
Chris Lattner10725092008-03-09 04:17:44 +0000588 return FE;
589 }
590 }
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattner10725092008-03-09 04:17:44 +0000592 // Otherwise, we really couldn't find the file.
593 return 0;
594}
595
Chris Lattner141e71f2008-03-09 01:54:53 +0000596
597//===----------------------------------------------------------------------===//
598// Preprocessor Directive Handling.
599//===----------------------------------------------------------------------===//
600
David Blaikie8c0b3782012-06-06 18:52:13 +0000601class Preprocessor::ResetMacroExpansionHelper {
602public:
603 ResetMacroExpansionHelper(Preprocessor *pp)
604 : PP(pp), save(pp->DisableMacroExpansion) {
605 if (pp->MacroExpansionInDirectivesOverride)
606 pp->DisableMacroExpansion = false;
607 }
608 ~ResetMacroExpansionHelper() {
609 PP->DisableMacroExpansion = save;
610 }
611private:
612 Preprocessor *PP;
613 bool save;
614};
615
Chris Lattner141e71f2008-03-09 01:54:53 +0000616/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000617/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000618/// lexer/preprocessor state, and advances the lexer(s) so that the next token
619/// read is the correct one.
620void Preprocessor::HandleDirective(Token &Result) {
621 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Chris Lattner141e71f2008-03-09 01:54:53 +0000623 // We just parsed a # character at the start of a line, so we're in directive
624 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne84021552011-02-28 02:37:51 +0000625 // EOD token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000626 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose6aad4a32013-02-21 18:53:19 +0000627 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattner141e71f2008-03-09 01:54:53 +0000629 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000630
Chris Lattner141e71f2008-03-09 01:54:53 +0000631 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000632 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000633 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000634 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Chris Lattner42aa16c2009-03-18 21:00:25 +0000636 // Save the '#' token in case we need to return it later.
637 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattner141e71f2008-03-09 01:54:53 +0000639 // Read the next token, the directive flavor. This isn't expanded due to
640 // C99 6.10.3p8.
641 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Chris Lattner141e71f2008-03-09 01:54:53 +0000643 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
644 // #define A(x) #x
645 // A(abc
646 // #warning blah
647 // def)
Richard Smitha3ca4d62011-12-16 22:50:01 +0000648 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
649 // not support this for #include-like directives, since that can result in
650 // terrible diagnostics, and does not work in GCC.
651 if (InMacroArgs) {
652 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
653 switch (II->getPPKeywordID()) {
654 case tok::pp_include:
655 case tok::pp_import:
656 case tok::pp_include_next:
657 case tok::pp___include_macros:
658 Diag(Result, diag::err_embedded_include) << II->getName();
659 DiscardUntilEndOfDirective();
660 return;
661 default:
662 break;
663 }
664 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000665 Diag(Result, diag::ext_embedded_directive);
Richard Smitha3ca4d62011-12-16 22:50:01 +0000666 }
Mike Stump1eb44332009-09-09 15:08:12 +0000667
David Blaikie8c0b3782012-06-06 18:52:13 +0000668 // Temporarily enable macro expansion if set so
669 // and reset to previous state when returning from this function.
670 ResetMacroExpansionHelper helper(this);
671
Chris Lattner141e71f2008-03-09 01:54:53 +0000672 switch (Result.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000673 case tok::eod:
Chris Lattner141e71f2008-03-09 01:54:53 +0000674 return; // null directive.
Douglas Gregorf44e8542010-08-24 19:08:16 +0000675 case tok::code_completion:
676 if (CodeComplete)
677 CodeComplete->CodeCompleteDirective(
678 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000679 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000680 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000681 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikie4e4d0842012-03-11 07:00:24 +0000682 if (getLangOpts().AsmPreprocessor)
Chris Lattner5f607c42009-03-18 20:41:10 +0000683 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000684 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000685 default:
686 IdentifierInfo *II = Result.getIdentifierInfo();
687 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Chris Lattner141e71f2008-03-09 01:54:53 +0000689 // Ask what the preprocessor keyword ID is.
690 switch (II->getPPKeywordID()) {
691 default: break;
692 // C99 6.10.1 - Conditional Inclusion.
693 case tok::pp_if:
694 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
695 case tok::pp_ifdef:
696 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
697 case tok::pp_ifndef:
698 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
699 case tok::pp_elif:
700 return HandleElifDirective(Result);
701 case tok::pp_else:
702 return HandleElseDirective(Result);
703 case tok::pp_endif:
704 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Chris Lattner141e71f2008-03-09 01:54:53 +0000706 // C99 6.10.2 - Source File Inclusion.
707 case tok::pp_include:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000708 // Handle #include.
709 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000710 case tok::pp___include_macros:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000711 // Handle -imacros.
712 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattner141e71f2008-03-09 01:54:53 +0000714 // C99 6.10.3 - Macro Replacement.
715 case tok::pp_define:
716 return HandleDefineDirective(Result);
717 case tok::pp_undef:
718 return HandleUndefDirective(Result);
719
720 // C99 6.10.4 - Line Control.
721 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000722 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Chris Lattner141e71f2008-03-09 01:54:53 +0000724 // C99 6.10.5 - Error Directive.
725 case tok::pp_error:
726 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Chris Lattner141e71f2008-03-09 01:54:53 +0000728 // C99 6.10.6 - Pragma Directive.
729 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000730 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattner141e71f2008-03-09 01:54:53 +0000732 // GNU Extensions.
733 case tok::pp_import:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000734 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000735 case tok::pp_include_next:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000736 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattner141e71f2008-03-09 01:54:53 +0000738 case tok::pp_warning:
739 Diag(Result, diag::ext_pp_warning_directive);
740 return HandleUserDiagnosticDirective(Result, true);
741 case tok::pp_ident:
742 return HandleIdentSCCSDirective(Result);
743 case tok::pp_sccs:
744 return HandleIdentSCCSDirective(Result);
745 case tok::pp_assert:
746 //isExtension = true; // FIXME: implement #assert
747 break;
748 case tok::pp_unassert:
749 //isExtension = true; // FIXME: implement #unassert
750 break;
Douglas Gregor7143aab2011-09-01 17:04:32 +0000751
Douglas Gregor1ac13c32012-01-03 19:48:16 +0000752 case tok::pp___public_macro:
David Blaikie4e4d0842012-03-11 07:00:24 +0000753 if (getLangOpts().Modules)
Douglas Gregor94ad28b2012-01-03 18:24:14 +0000754 return HandleMacroPublicDirective(Result);
755 break;
756
Douglas Gregor1ac13c32012-01-03 19:48:16 +0000757 case tok::pp___private_macro:
David Blaikie4e4d0842012-03-11 07:00:24 +0000758 if (getLangOpts().Modules)
Douglas Gregor94ad28b2012-01-03 18:24:14 +0000759 return HandleMacroPrivateDirective(Result);
760 break;
Chris Lattner141e71f2008-03-09 01:54:53 +0000761 }
762 break;
763 }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner42aa16c2009-03-18 21:00:25 +0000765 // If this is a .S file, treat unknown # directives as non-preprocessor
766 // directives. This is important because # may be a comment or introduce
767 // various pseudo-ops. Just return the # token and push back the following
768 // token to be lexed next time.
David Blaikie4e4d0842012-03-11 07:00:24 +0000769 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000770 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000771 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000772 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000773 Toks[1] = Result;
Chris Lattnerba3ca522011-01-06 05:01:51 +0000774
775 // If the second token is a hashhash token, then we need to translate it to
776 // unknown so the token lexer doesn't try to perform token pasting.
777 if (Result.is(tok::hashhash))
778 Toks[1].setKind(tok::unknown);
779
Chris Lattner42aa16c2009-03-18 21:00:25 +0000780 // Enter this token stream so that we re-lex the tokens. Make sure to
781 // enable macro expansion, in case the token after the # is an identifier
782 // that is expanded.
783 EnterTokenStream(Toks, 2, false, true);
784 return;
785 }
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattner141e71f2008-03-09 01:54:53 +0000787 // If we reached here, the preprocessing token is not valid!
788 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Chris Lattner141e71f2008-03-09 01:54:53 +0000790 // Read the rest of the PP line.
791 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chris Lattner141e71f2008-03-09 01:54:53 +0000793 // Okay, we're done parsing the directive.
794}
795
Chris Lattner478a18e2009-01-26 06:19:46 +0000796/// GetLineValue - Convert a numeric token into an unsigned value, emitting
797/// Diagnostic DiagID if it is invalid, and returning the value in Val.
798static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemanec276082013-04-10 01:04:18 +0000799 unsigned DiagID, Preprocessor &PP,
800 bool IsGNULineDirective=false) {
Chris Lattner478a18e2009-01-26 06:19:46 +0000801 if (DigitTok.isNot(tok::numeric_constant)) {
802 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Peter Collingbourne84021552011-02-28 02:37:51 +0000804 if (DigitTok.isNot(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000805 PP.DiscardUntilEndOfDirective();
806 return true;
807 }
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000809 SmallString<64> IntegerBuffer;
Chris Lattner478a18e2009-01-26 06:19:46 +0000810 IntegerBuffer.resize(DigitTok.getLength());
811 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000812 bool Invalid = false;
813 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
814 if (Invalid)
815 return true;
816
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000817 // Verify that we have a simple digit-sequence, and compute the value. This
818 // is always a simple digit string computed in decimal, so we do this manually
819 // here.
820 Val = 0;
821 for (unsigned i = 0; i != ActualLength; ++i) {
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000822 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000823 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemanec276082013-04-10 01:04:18 +0000824 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000825 PP.DiscardUntilEndOfDirective();
826 return true;
827 }
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000829 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
830 if (NextVal < Val) { // overflow.
831 PP.Diag(DigitTok, DiagID);
832 PP.DiscardUntilEndOfDirective();
833 return true;
834 }
835 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000836 }
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Fariborz Jahanian540f9ae2012-06-26 21:19:20 +0000838 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemanec276082013-04-10 01:04:18 +0000839 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
840 << IsGNULineDirective;
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Chris Lattner478a18e2009-01-26 06:19:46 +0000842 return false;
843}
844
James Dennettdc201692012-06-22 05:46:07 +0000845/// \brief Handle a \#line directive: C99 6.10.4.
846///
847/// The two acceptable forms are:
848/// \verbatim
Chris Lattner359cc442009-01-26 05:29:08 +0000849/// # line digit-sequence
850/// # line digit-sequence "s-char-sequence"
James Dennettdc201692012-06-22 05:46:07 +0000851/// \endverbatim
Chris Lattner359cc442009-01-26 05:29:08 +0000852void Preprocessor::HandleLineDirective(Token &Tok) {
853 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
854 // expanded.
855 Token DigitTok;
856 Lex(DigitTok);
857
Chris Lattner359cc442009-01-26 05:29:08 +0000858 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000859 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000860 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000861 return;
Fariborz Jahanian540f9ae2012-06-26 21:19:20 +0000862
863 if (LineNo == 0)
864 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner359cc442009-01-26 05:29:08 +0000865
Chris Lattner478a18e2009-01-26 06:19:46 +0000866 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
867 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman158ebfb2011-10-10 23:35:28 +0000868 unsigned LineLimit = 32768U;
Richard Smith80ad52f2013-01-02 11:42:31 +0000869 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman158ebfb2011-10-10 23:35:28 +0000870 LineLimit = 2147483648U;
Chris Lattner359cc442009-01-26 05:29:08 +0000871 if (LineNo >= LineLimit)
872 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith80ad52f2013-01-02 11:42:31 +0000873 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smith661a9962011-10-15 01:18:56 +0000874 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Chris Lattner5b9a5042009-01-26 07:57:50 +0000876 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000877 Token StrTok;
878 Lex(StrTok);
879
Peter Collingbourne84021552011-02-28 02:37:51 +0000880 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
881 // string followed by eod.
882 if (StrTok.is(tok::eod))
Chris Lattner359cc442009-01-26 05:29:08 +0000883 ; // ok
884 else if (StrTok.isNot(tok::string_literal)) {
885 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smith99831e42012-03-06 03:21:47 +0000886 return DiscardUntilEndOfDirective();
887 } else if (StrTok.hasUDSuffix()) {
888 Diag(StrTok, diag::err_invalid_string_udl);
889 return DiscardUntilEndOfDirective();
Chris Lattner359cc442009-01-26 05:29:08 +0000890 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000891 // Parse and validate the string, converting it into a unique ID.
892 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000893 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000894 if (Literal.hadError)
895 return DiscardUntilEndOfDirective();
896 if (Literal.Pascal) {
897 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
898 return DiscardUntilEndOfDirective();
899 }
Jay Foad65aa6882011-06-21 15:13:30 +0000900 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Peter Collingbourne84021552011-02-28 02:37:51 +0000902 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattnerab82f412009-04-17 23:30:53 +0000903 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
904 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000905 }
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Chris Lattner4c4ea172009-02-03 21:52:55 +0000907 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Chris Lattner16629382009-03-27 17:13:49 +0000909 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000910 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
911 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000912 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000913}
914
Chris Lattner478a18e2009-01-26 06:19:46 +0000915/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
916/// marker directive.
917static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
918 bool &IsSystemHeader, bool &IsExternCHeader,
919 Preprocessor &PP) {
920 unsigned FlagVal;
921 Token FlagTok;
922 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000923 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000924 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
925 return true;
926
927 if (FlagVal == 1) {
928 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Chris Lattner478a18e2009-01-26 06:19:46 +0000930 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000931 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000932 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
933 return true;
934 } else if (FlagVal == 2) {
935 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Chris Lattner137b6a62009-02-04 06:25:26 +0000937 SourceManager &SM = PP.getSourceManager();
938 // If we are leaving the current presumed file, check to make sure the
939 // presumed include stack isn't empty!
940 FileID CurFileID =
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000941 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner137b6a62009-02-04 06:25:26 +0000942 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000943 if (PLoc.isInvalid())
944 return true;
945
Chris Lattner137b6a62009-02-04 06:25:26 +0000946 // If there is no include loc (main file) or if the include loc is in a
947 // different physical file, then we aren't in a "1" line marker flag region.
948 SourceLocation IncLoc = PLoc.getIncludeLoc();
949 if (IncLoc.isInvalid() ||
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000950 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner137b6a62009-02-04 06:25:26 +0000951 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
952 PP.DiscardUntilEndOfDirective();
953 return true;
954 }
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Chris Lattner478a18e2009-01-26 06:19:46 +0000956 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000957 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000958 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
959 return true;
960 }
961
962 // We must have 3 if there are still flags.
963 if (FlagVal != 3) {
964 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000965 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000966 return true;
967 }
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Chris Lattner478a18e2009-01-26 06:19:46 +0000969 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Chris Lattner478a18e2009-01-26 06:19:46 +0000971 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000972 if (FlagTok.is(tok::eod)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000973 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000974 return true;
975
976 // We must have 4 if there is yet another flag.
977 if (FlagVal != 4) {
978 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000979 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000980 return true;
981 }
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Chris Lattner478a18e2009-01-26 06:19:46 +0000983 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Chris Lattner478a18e2009-01-26 06:19:46 +0000985 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000986 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000987
988 // There are no more valid flags here.
989 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000990 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000991 return true;
992}
993
994/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
995/// one of the following forms:
996///
997/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000998/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000999/// # 42 "file" ('1' | '2')? '3' '4'?
1000///
1001void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1002 // Validate the number and convert it to an unsigned. GNU does not have a
1003 // line # limit other than it fit in 32-bits.
1004 unsigned LineNo;
1005 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemanec276082013-04-10 01:04:18 +00001006 *this, true))
Chris Lattner478a18e2009-01-26 06:19:46 +00001007 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattner478a18e2009-01-26 06:19:46 +00001009 Token StrTok;
1010 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Chris Lattner478a18e2009-01-26 06:19:46 +00001012 bool IsFileEntry = false, IsFileExit = false;
1013 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +00001014 int FilenameID = -1;
1015
Peter Collingbourne84021552011-02-28 02:37:51 +00001016 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1017 // string followed by eod.
1018 if (StrTok.is(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +00001019 ; // ok
1020 else if (StrTok.isNot(tok::string_literal)) {
1021 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +00001022 return DiscardUntilEndOfDirective();
Richard Smith99831e42012-03-06 03:21:47 +00001023 } else if (StrTok.hasUDSuffix()) {
1024 Diag(StrTok, diag::err_invalid_string_udl);
1025 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +00001026 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +00001027 // Parse and validate the string, converting it into a unique ID.
1028 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +00001029 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +00001030 if (Literal.hadError)
1031 return DiscardUntilEndOfDirective();
1032 if (Literal.Pascal) {
1033 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1034 return DiscardUntilEndOfDirective();
1035 }
Jay Foad65aa6882011-06-21 15:13:30 +00001036 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Chris Lattner478a18e2009-01-26 06:19:46 +00001038 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +00001039 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +00001040 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +00001041 return;
Chris Lattner478a18e2009-01-26 06:19:46 +00001042 }
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Chris Lattner9d79eba2009-02-04 05:21:58 +00001044 // Create a line note with this information.
1045 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +00001046 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +00001047 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Chris Lattner16629382009-03-27 17:13:49 +00001049 // If the preprocessor has callbacks installed, notify them of the #line
1050 // change. This is used so that the line marker comes out in -E mode for
1051 // example.
1052 if (Callbacks) {
1053 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1054 if (IsFileEntry)
1055 Reason = PPCallbacks::EnterFile;
1056 else if (IsFileExit)
1057 Reason = PPCallbacks::ExitFile;
1058 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1059 if (IsExternCHeader)
1060 FileKind = SrcMgr::C_ExternCSystem;
1061 else if (IsSystemHeader)
1062 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Chris Lattner86d0ef72010-04-14 04:28:50 +00001064 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +00001065 }
Chris Lattner478a18e2009-01-26 06:19:46 +00001066}
1067
1068
Chris Lattner099dd052009-01-26 05:30:54 +00001069/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1070///
Mike Stump1eb44332009-09-09 15:08:12 +00001071void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001072 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +00001073 // PTH doesn't emit #warning or #error directives.
1074 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +00001075 return CurPTHLexer->DiscardToEndOfLine();
1076
Chris Lattner141e71f2008-03-09 01:54:53 +00001077 // Read the rest of the line raw. We do this because we don't want macros
1078 // to be expanded and we don't require that the tokens be valid preprocessing
1079 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1080 // collapse multiple consequtive white space between tokens, but this isn't
1081 // specified by the standard.
Benjamin Kramer3093b202012-05-18 19:32:16 +00001082 SmallString<128> Message;
1083 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek34a2c422012-02-02 00:16:13 +00001084
1085 // Find the first non-whitespace character, so that we can make the
1086 // diagnostic more succinct.
Benjamin Kramer3093b202012-05-18 19:32:16 +00001087 StringRef Msg = Message.str().ltrim(" ");
1088
Chris Lattner359cc442009-01-26 05:29:08 +00001089 if (isWarning)
Ted Kremenek34a2c422012-02-02 00:16:13 +00001090 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner359cc442009-01-26 05:29:08 +00001091 else
Ted Kremenek34a2c422012-02-02 00:16:13 +00001092 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattner141e71f2008-03-09 01:54:53 +00001093}
1094
1095/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1096///
1097void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1098 // Yes, this directive is an extension.
1099 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Chris Lattner141e71f2008-03-09 01:54:53 +00001101 // Read the string argument.
1102 Token StrTok;
1103 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Chris Lattner141e71f2008-03-09 01:54:53 +00001105 // If the token kind isn't a string, it's a malformed directive.
1106 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +00001107 StrTok.isNot(tok::wide_string_literal)) {
1108 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne84021552011-02-28 02:37:51 +00001109 if (StrTok.isNot(tok::eod))
Chris Lattner099dd052009-01-26 05:30:54 +00001110 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +00001111 return;
1112 }
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Richard Smith99831e42012-03-06 03:21:47 +00001114 if (StrTok.hasUDSuffix()) {
1115 Diag(StrTok, diag::err_invalid_string_udl);
1116 return DiscardUntilEndOfDirective();
1117 }
1118
Peter Collingbourne84021552011-02-28 02:37:51 +00001119 // Verify that there is nothing after the string, other than EOD.
Chris Lattner35410d52009-04-14 05:07:49 +00001120 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +00001121
Douglas Gregor453091c2010-03-16 22:30:13 +00001122 if (Callbacks) {
1123 bool Invalid = false;
1124 std::string Str = getSpelling(StrTok, &Invalid);
1125 if (!Invalid)
1126 Callbacks->Ident(Tok.getLocation(), Str);
1127 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001128}
1129
Douglas Gregor94ad28b2012-01-03 18:24:14 +00001130/// \brief Handle a #public directive.
1131void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor7143aab2011-09-01 17:04:32 +00001132 Token MacroNameTok;
1133 ReadMacroName(MacroNameTok, 2);
1134
1135 // Error reading macro name? If so, diagnostic already issued.
1136 if (MacroNameTok.is(tok::eod))
1137 return;
1138
Douglas Gregor1ac13c32012-01-03 19:48:16 +00001139 // Check to see if this is the last token on the #__public_macro line.
1140 CheckEndOfDirective("__public_macro");
Douglas Gregor7143aab2011-09-01 17:04:32 +00001141
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001142 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor7143aab2011-09-01 17:04:32 +00001143 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001144 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor7143aab2011-09-01 17:04:32 +00001145
1146 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001147 if (MD == 0) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001148 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor7143aab2011-09-01 17:04:32 +00001149 return;
1150 }
1151
1152 // Note that this macro has now been exported.
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001153 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1154 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregoraa93a872011-10-17 15:32:29 +00001155}
1156
Douglas Gregor94ad28b2012-01-03 18:24:14 +00001157/// \brief Handle a #private directive.
Douglas Gregoraa93a872011-10-17 15:32:29 +00001158void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1159 Token MacroNameTok;
1160 ReadMacroName(MacroNameTok, 2);
1161
1162 // Error reading macro name? If so, diagnostic already issued.
1163 if (MacroNameTok.is(tok::eod))
1164 return;
1165
Douglas Gregor1ac13c32012-01-03 19:48:16 +00001166 // Check to see if this is the last token on the #__private_macro line.
1167 CheckEndOfDirective("__private_macro");
Douglas Gregoraa93a872011-10-17 15:32:29 +00001168
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001169 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregoraa93a872011-10-17 15:32:29 +00001170 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001171 MacroDirective *MD = getMacroDirective(II);
Douglas Gregoraa93a872011-10-17 15:32:29 +00001172
1173 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001174 if (MD == 0) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001175 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregoraa93a872011-10-17 15:32:29 +00001176 return;
1177 }
1178
1179 // Note that this macro has now been marked private.
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001180 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1181 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor7143aab2011-09-01 17:04:32 +00001182}
1183
Chris Lattner141e71f2008-03-09 01:54:53 +00001184//===----------------------------------------------------------------------===//
1185// Preprocessor Include Directive Handling.
1186//===----------------------------------------------------------------------===//
1187
1188/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettdc201692012-06-22 05:46:07 +00001189/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattner141e71f2008-03-09 01:54:53 +00001190/// true if the input filename was in <>'s or false if it were in ""'s. The
1191/// caller is expected to provide a buffer that is large enough to hold the
1192/// spelling of the filename, but is also expected to handle the case when
1193/// this method decides to use a different buffer.
1194bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001195 StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001196 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +00001197 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Chris Lattner141e71f2008-03-09 01:54:53 +00001199 // Make sure the filename is <x> or "x".
1200 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +00001201 if (Buffer[0] == '<') {
1202 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001203 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001204 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001205 return true;
1206 }
1207 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +00001208 } else if (Buffer[0] == '"') {
1209 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001210 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001211 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001212 return true;
1213 }
1214 isAngled = false;
1215 } else {
1216 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001217 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001218 return true;
1219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Chris Lattner141e71f2008-03-09 01:54:53 +00001221 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +00001222 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001223 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001224 Buffer = StringRef();
Chris Lattnera1394812010-01-10 01:35:12 +00001225 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Chris Lattner141e71f2008-03-09 01:54:53 +00001228 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001229 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001230 return isAngled;
1231}
1232
James Dennettdc201692012-06-22 05:46:07 +00001233/// \brief Handle cases where the \#include name is expanded from a macro
1234/// as multiple tokens, which need to be glued together.
1235///
1236/// This occurs for code like:
1237/// \code
1238/// \#define FOO <a/b.h>
1239/// \#include FOO
1240/// \endcode
Chris Lattner141e71f2008-03-09 01:54:53 +00001241/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1242///
1243/// This code concatenates and consumes tokens up to the '>' token. It returns
1244/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne84021552011-02-28 02:37:51 +00001245/// the EOD marker.
John Thompsona28cc092009-10-30 13:49:06 +00001246bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001247 SmallString<128> &FilenameBuffer,
Douglas Gregorecdcb882010-10-20 22:00:55 +00001248 SourceLocation &End) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001249 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001250
John Thompsona28cc092009-10-30 13:49:06 +00001251 Lex(CurTok);
Peter Collingbourne84021552011-02-28 02:37:51 +00001252 while (CurTok.isNot(tok::eod)) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001253 End = CurTok.getLocation();
1254
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001255 // FIXME: Provide code completion for #includes.
1256 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001257 setCodeCompletionReached();
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001258 Lex(CurTok);
1259 continue;
1260 }
1261
Chris Lattner141e71f2008-03-09 01:54:53 +00001262 // Append the spelling of this token to the buffer. If there was a space
1263 // before it, add it now.
1264 if (CurTok.hasLeadingSpace())
1265 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Chris Lattner141e71f2008-03-09 01:54:53 +00001267 // Get the spelling of the token, directly into FilenameBuffer if possible.
1268 unsigned PreAppendSize = FilenameBuffer.size();
1269 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Chris Lattner141e71f2008-03-09 01:54:53 +00001271 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001272 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Chris Lattner141e71f2008-03-09 01:54:53 +00001274 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1275 if (BufPtr != &FilenameBuffer[PreAppendSize])
1276 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Chris Lattner141e71f2008-03-09 01:54:53 +00001278 // Resize FilenameBuffer to the correct size.
1279 if (CurTok.getLength() != ActualLen)
1280 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Chris Lattner141e71f2008-03-09 01:54:53 +00001282 // If we found the '>' marker, return success.
1283 if (CurTok.is(tok::greater))
1284 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001285
John Thompsona28cc092009-10-30 13:49:06 +00001286 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001287 }
1288
Peter Collingbourne84021552011-02-28 02:37:51 +00001289 // If we hit the eod marker, emit an error and return true so that the caller
1290 // knows the EOD has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001291 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001292 return true;
1293}
1294
James Dennettdc201692012-06-22 05:46:07 +00001295/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1296/// the file to be included from the lexer, then include it! This is a common
1297/// routine with functionality shared between \#include, \#include_next and
1298/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001299/// specifies the file to start searching from.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001300void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1301 Token &IncludeTok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001302 const DirectoryLookup *LookupFrom,
1303 bool isImport) {
1304
1305 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001306 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001307
Chris Lattner141e71f2008-03-09 01:54:53 +00001308 // Reserve a buffer to get the spelling.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001309 SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001310 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001311 SourceLocation End;
Douglas Gregore3a82562011-11-30 18:02:36 +00001312 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregorecdcb882010-10-20 22:00:55 +00001313
Chris Lattner141e71f2008-03-09 01:54:53 +00001314 switch (FilenameTok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +00001315 case tok::eod:
1316 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattner141e71f2008-03-09 01:54:53 +00001317 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Chris Lattner141e71f2008-03-09 01:54:53 +00001319 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001320 case tok::string_literal:
1321 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregorecdcb882010-10-20 22:00:55 +00001322 End = FilenameTok.getLocation();
Argyrios Kyrtzidiscfa1caa2012-11-01 17:52:58 +00001323 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +00001324 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Chris Lattner141e71f2008-03-09 01:54:53 +00001326 case tok::less:
1327 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1328 // case, glue the tokens together into FilenameBuffer and interpret those.
1329 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +00001330 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne84021552011-02-28 02:37:51 +00001331 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001332 Filename = FilenameBuffer.str();
Argyrios Kyrtzidiscfa1caa2012-11-01 17:52:58 +00001333 CharEnd = End.getLocWithOffset(1);
Chris Lattner141e71f2008-03-09 01:54:53 +00001334 break;
1335 default:
1336 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1337 DiscardUntilEndOfDirective();
1338 return;
1339 }
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001341 CharSourceRange FilenameRange
1342 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman4c55c542012-03-02 22:51:54 +00001343 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001344 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001345 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001346 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1347 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001348 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001349 DiscardUntilEndOfDirective();
1350 return;
1351 }
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Peter Collingbourne84021552011-02-28 02:37:51 +00001353 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001354 // we allow macros that expand to nothing after the filename, because this
1355 // falls into the category of "#include pp-tokens new-line" specified in
1356 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001357 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001358
1359 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001360 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1361 Diag(FilenameTok, diag::err_pp_include_too_deep);
1362 return;
1363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
John McCall8dfac0b2011-09-30 05:12:12 +00001365 // Complain about attempts to #include files in an audit pragma.
1366 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1367 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1368 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1369
1370 // Immediately leave the pragma.
1371 PragmaARCCFCodeAuditedLoc = SourceLocation();
1372 }
1373
Aaron Ballman4c55c542012-03-02 22:51:54 +00001374 if (HeaderInfo.HasIncludeAliasMap()) {
1375 // Map the filename with the brackets still attached. If the name doesn't
1376 // map to anything, fall back on the filename we've already gotten the
1377 // spelling for.
1378 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1379 if (!NewName.empty())
1380 Filename = NewName;
1381 }
1382
Chris Lattner141e71f2008-03-09 01:54:53 +00001383 // Search include directories.
1384 const DirectoryLookup *CurDir;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001385 SmallString<1024> SearchPath;
1386 SmallString<1024> RelativePath;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001387 // We get the raw path only if we have 'Callbacks' to which we later pass
1388 // the path.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001389 Module *SuggestedModule = 0;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001390 const FileEntry *File = LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +00001391 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001392 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikie4e4d0842012-03-11 07:00:24 +00001393 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001394
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001395 if (Callbacks) {
1396 if (!File) {
1397 // Give the clients a chance to recover.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001398 SmallString<128> RecoveryPath;
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001399 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1400 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1401 // Add the recovery path to the list of search paths.
Daniel Dunbar1ea6bc02013-01-25 01:50:28 +00001402 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001403 HeaderInfo.AddSearchPath(DL, isAngled);
1404
1405 // Try the lookup again, skipping the cache.
1406 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikie4e4d0842012-03-11 07:00:24 +00001407 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001408 /*SkipCache*/true);
1409 }
1410 }
1411 }
1412
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001413 if (!SuggestedModule) {
1414 // Notify the callback object that we've seen an inclusion directive.
1415 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1416 FilenameRange, File,
1417 SearchPath, RelativePath,
1418 /*ImportedModule=*/0);
1419 }
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001420 }
1421
1422 if (File == 0) {
Aaron Ballmana52f5a32012-07-17 23:19:16 +00001423 if (!SuppressIncludeNotFoundError) {
1424 // If the file could not be located and it was included via angle
1425 // brackets, we can attempt a lookup as though it were a quoted path to
1426 // provide the user with a possible fixit.
1427 if (isAngled) {
1428 File = LookupFile(Filename, false, LookupFrom, CurDir,
1429 Callbacks ? &SearchPath : 0,
1430 Callbacks ? &RelativePath : 0,
1431 getLangOpts().Modules ? &SuggestedModule : 0);
1432 if (File) {
1433 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1434 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1435 Filename <<
1436 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1437 }
1438 }
1439 // If the file is still not found, just go with the vanilla diagnostic
1440 if (!File)
1441 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1442 }
1443 if (!File)
1444 return;
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001445 }
1446
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001447 // If we are supposed to import a module rather than including the header,
1448 // do so now.
Douglas Gregorc69c42e2011-11-17 22:44:56 +00001449 if (SuggestedModule) {
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001450 // Compute the module access path corresponding to this module.
1451 // FIXME: Should we have a second loadModule() overload to avoid this
1452 // extra lookup step?
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001453 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001454 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001455 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1456 FilenameTok.getLocation()));
1457 std::reverse(Path.begin(), Path.end());
1458
Douglas Gregore3a82562011-11-30 18:02:36 +00001459 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001460 SmallString<128> PathString;
Douglas Gregore3a82562011-11-30 18:02:36 +00001461 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1462 if (I)
1463 PathString += '.';
1464 PathString += Path[I].first->getName();
1465 }
1466 int IncludeKind = 0;
1467
1468 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1469 case tok::pp_include:
1470 IncludeKind = 0;
1471 break;
1472
1473 case tok::pp_import:
1474 IncludeKind = 1;
1475 break;
1476
Douglas Gregoredee9692011-11-30 18:03:26 +00001477 case tok::pp_include_next:
1478 IncludeKind = 2;
1479 break;
Douglas Gregore3a82562011-11-30 18:02:36 +00001480
1481 case tok::pp___include_macros:
1482 IncludeKind = 3;
1483 break;
1484
1485 default:
1486 llvm_unreachable("unknown include directive kind");
Douglas Gregore3a82562011-11-30 18:02:36 +00001487 }
1488
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001489 // Determine whether we are actually building the module that this
1490 // include directive maps to.
1491 bool BuildingImportedModule
David Blaikie4e4d0842012-03-11 07:00:24 +00001492 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001493
David Blaikie4e4d0842012-03-11 07:00:24 +00001494 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001495 // If we're not building the imported module, warn that we're going
1496 // to automatically turn this inclusion directive into a module import.
Douglas Gregorc13a34b2012-01-03 19:32:59 +00001497 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001498 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1499 /*IsTokenRange=*/false);
1500 Diag(HashLoc, diag::warn_auto_module_import)
1501 << IncludeKind << PathString
1502 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregor1b257af2012-12-11 22:11:52 +00001503 "@import " + PathString.str().str() + ";");
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001504 }
Douglas Gregore3a82562011-11-30 18:02:36 +00001505
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001506 // Load the module.
Douglas Gregor5e356932011-12-01 17:11:21 +00001507 // If this was an #__include_macros directive, only make macros visible.
1508 Module::NameVisibilityKind Visibility
1509 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor463d9092012-11-29 23:55:25 +00001510 ModuleLoadResult Imported
Douglas Gregor305dc3e2011-12-20 00:28:52 +00001511 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1512 /*IsIncludeDirective=*/true);
Argyrios Kyrtzidiseb788e92012-09-29 01:06:01 +00001513 assert((Imported == 0 || Imported == SuggestedModule) &&
1514 "the imported module is different than the suggested one");
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001515
1516 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001517 if (!BuildingImportedModule && Imported) {
1518 if (Callbacks) {
1519 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1520 FilenameRange, File,
1521 SearchPath, RelativePath, Imported);
1522 }
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001523 return;
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001524 }
Douglas Gregor463d9092012-11-29 23:55:25 +00001525
1526 // If we failed to find a submodule that we expected to find, we can
1527 // continue. Otherwise, there's an error in the included file, so we
1528 // don't want to include it.
1529 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1530 return;
1531 }
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +00001532 }
1533
1534 if (Callbacks && SuggestedModule) {
1535 // We didn't notify the callback object that we've seen an inclusion
1536 // directive before. Now that we are parsing the include normally and not
1537 // turning it to a module import, notify the callback object.
1538 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1539 FilenameRange, File,
1540 SearchPath, RelativePath,
1541 /*ImportedModule=*/0);
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001542 }
1543
Chris Lattner72181832008-09-26 20:12:23 +00001544 // The #included file will be considered to be a system header if either it is
1545 // in a system include directory, or if the #includer is a system include
1546 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001547 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001548 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001549 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001551 // Ask HeaderInfo if we should enter this #include file. If not, #including
1552 // this file will have no effect.
1553 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001554 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001555 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001556 return;
1557 }
1558
Chris Lattner141e71f2008-03-09 01:54:53 +00001559 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisdb81d382012-03-27 18:47:48 +00001560 SourceLocation IncludePos = End;
1561 // If the filename string was the result of macro expansions, set the include
1562 // position on the file where it will be included and after the expansions.
1563 if (IncludePos.isMacroID())
1564 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1565 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned57b7ff2011-06-30 16:41:03 +00001566 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattner141e71f2008-03-09 01:54:53 +00001567
1568 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001569 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001570}
1571
James Dennettdc201692012-06-22 05:46:07 +00001572/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattner141e71f2008-03-09 01:54:53 +00001573///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001574void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1575 Token &IncludeNextTok) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001576 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Chris Lattner141e71f2008-03-09 01:54:53 +00001578 // #include_next is like #include, except that we start searching after
1579 // the current found directory. If we can't do this, issue a
1580 // diagnostic.
1581 const DirectoryLookup *Lookup = CurDirLookup;
1582 if (isInPrimaryFile()) {
1583 Lookup = 0;
1584 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1585 } else if (Lookup == 0) {
1586 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1587 } else {
1588 // Start looking up in the next directory.
1589 ++Lookup;
1590 }
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Douglas Gregorecdcb882010-10-20 22:00:55 +00001592 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattner141e71f2008-03-09 01:54:53 +00001593}
1594
James Dennettdc201692012-06-22 05:46:07 +00001595/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman4207eda2012-03-18 03:10:37 +00001596void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1597 // The Microsoft #import directive takes a type library and generates header
1598 // files from it, and includes those. This is beyond the scope of what clang
1599 // does, so we ignore it and error out. However, #import can optionally have
1600 // trailing attributes that span multiple lines. We're going to eat those
1601 // so we can continue processing from there.
1602 Diag(Tok, diag::err_pp_import_directive_ms );
1603
1604 // Read tokens until we get to the end of the directive. Note that the
1605 // directive can be split over multiple lines using the backslash character.
1606 DiscardUntilEndOfDirective();
1607}
1608
James Dennettdc201692012-06-22 05:46:07 +00001609/// HandleImportDirective - Implements \#import.
Chris Lattner141e71f2008-03-09 01:54:53 +00001610///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001611void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1612 Token &ImportTok) {
Aaron Ballman4207eda2012-03-18 03:10:37 +00001613 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1614 if (LangOpts.MicrosoftMode)
1615 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001616 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman4207eda2012-03-18 03:10:37 +00001617 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00001618 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001619}
1620
Chris Lattnerde076652009-04-08 18:46:40 +00001621/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1622/// pseudo directive in the predefines buffer. This handles it by sucking all
1623/// tokens through the preprocessor and discarding them (only keeping the side
1624/// effects on the preprocessor).
Douglas Gregorecdcb882010-10-20 22:00:55 +00001625void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1626 Token &IncludeMacrosTok) {
Chris Lattnerde076652009-04-08 18:46:40 +00001627 // This directive should only occur in the predefines buffer. If not, emit an
1628 // error and reject it.
1629 SourceLocation Loc = IncludeMacrosTok.getLocation();
1630 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1631 Diag(IncludeMacrosTok.getLocation(),
1632 diag::pp_include_macros_out_of_predefines);
1633 DiscardUntilEndOfDirective();
1634 return;
1635 }
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Chris Lattnerfd105112009-04-08 20:53:24 +00001637 // Treat this as a normal #include for checking purposes. If this is
1638 // successful, it will push a new lexer onto the include stack.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001639 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Chris Lattnerfd105112009-04-08 20:53:24 +00001641 Token TmpTok;
1642 do {
1643 Lex(TmpTok);
1644 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1645 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001646}
1647
Chris Lattner141e71f2008-03-09 01:54:53 +00001648//===----------------------------------------------------------------------===//
1649// Preprocessor Macro Directive Handling.
1650//===----------------------------------------------------------------------===//
1651
1652/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1653/// definition has just been read. Lex the rest of the arguments and the
1654/// closing ), updating MI with what we learn. Return true if an error occurs
1655/// parsing the arg list.
Abramo Bagnarae2e87682012-03-31 20:17:27 +00001656bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001657 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Chris Lattner141e71f2008-03-09 01:54:53 +00001659 while (1) {
1660 LexUnexpandedToken(Tok);
1661 switch (Tok.getKind()) {
1662 case tok::r_paren:
1663 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001664 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001665 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001666 // Otherwise we have #define FOO(A,)
1667 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1668 return true;
1669 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikie4e4d0842012-03-11 07:00:24 +00001670 if (!LangOpts.C99)
Richard Smith80ad52f2013-01-02 11:42:31 +00001671 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smith661a9962011-10-15 01:18:56 +00001672 diag::warn_cxx98_compat_variadic_macro :
1673 diag::ext_variadic_macro);
Chris Lattner141e71f2008-03-09 01:54:53 +00001674
Joey Gouly617bb312013-01-17 17:35:00 +00001675 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1676 if (LangOpts.OpenCL) {
1677 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1678 return true;
1679 }
1680
Chris Lattner141e71f2008-03-09 01:54:53 +00001681 // Lex the token after the identifier.
1682 LexUnexpandedToken(Tok);
1683 if (Tok.isNot(tok::r_paren)) {
1684 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1685 return true;
1686 }
1687 // Add the __VA_ARGS__ identifier as an argument.
1688 Arguments.push_back(Ident__VA_ARGS__);
1689 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001690 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001691 return false;
Peter Collingbourne84021552011-02-28 02:37:51 +00001692 case tok::eod: // #define X(
Chris Lattner141e71f2008-03-09 01:54:53 +00001693 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1694 return true;
1695 default:
1696 // Handle keywords and identifiers here to accept things like
1697 // #define Foo(for) for.
1698 IdentifierInfo *II = Tok.getIdentifierInfo();
1699 if (II == 0) {
1700 // #define X(1
1701 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1702 return true;
1703 }
1704
1705 // If this is already used as an argument, it is used multiple times (e.g.
1706 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001707 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001708 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001709 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001710 return true;
1711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Chris Lattner141e71f2008-03-09 01:54:53 +00001713 // Add the argument to the macro info.
1714 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Chris Lattner141e71f2008-03-09 01:54:53 +00001716 // Lex the token after the identifier.
1717 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Chris Lattner141e71f2008-03-09 01:54:53 +00001719 switch (Tok.getKind()) {
1720 default: // #define X(A B
1721 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1722 return true;
1723 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001724 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001725 return false;
1726 case tok::comma: // #define X(A,
1727 break;
1728 case tok::ellipsis: // #define X(A... -> GCC extension
1729 // Diagnose extension.
1730 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Chris Lattner141e71f2008-03-09 01:54:53 +00001732 // Lex the token after the identifier.
1733 LexUnexpandedToken(Tok);
1734 if (Tok.isNot(tok::r_paren)) {
1735 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1736 return true;
1737 }
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Chris Lattner141e71f2008-03-09 01:54:53 +00001739 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001740 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001741 return false;
1742 }
1743 }
1744 }
1745}
1746
James Dennettdc201692012-06-22 05:46:07 +00001747/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattner141e71f2008-03-09 01:54:53 +00001748/// line then lets the caller lex the next real token.
1749void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1750 ++NumDefined;
1751
1752 Token MacroNameTok;
1753 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Chris Lattner141e71f2008-03-09 01:54:53 +00001755 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001756 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001757 return;
1758
Chris Lattner2451b522009-04-21 04:46:33 +00001759 Token LastTok = MacroNameTok;
1760
Chris Lattner141e71f2008-03-09 01:54:53 +00001761 // If we are supposed to keep comments in #defines, reenable comment saving
1762 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001763 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Chris Lattner141e71f2008-03-09 01:54:53 +00001765 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001766 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Chris Lattner141e71f2008-03-09 01:54:53 +00001768 Token Tok;
1769 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Chris Lattner141e71f2008-03-09 01:54:53 +00001771 // If this is a function-like macro definition, parse the argument list,
1772 // marking each of the identifiers as being used as macro arguments. Also,
1773 // check other constraints on the first token of the macro body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001774 if (Tok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001775 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001776 } else if (Tok.hasLeadingSpace()) {
1777 // This is a normal token with leading space. Clear the leading space
1778 // marker on the first token to get proper expansion.
1779 Tok.clearFlag(Token::LeadingSpace);
1780 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001781 // This is a function-like macro definition. Read the argument list.
1782 MI->setIsFunctionLike();
Abramo Bagnarae2e87682012-03-31 20:17:27 +00001783 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001784 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001785 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001786 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001787 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001788 DiscardUntilEndOfDirective();
1789 return;
1790 }
1791
Chris Lattner8fde5972009-04-19 18:26:34 +00001792 // If this is a definition of a variadic C99 function-like macro, not using
1793 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Chris Lattner8fde5972009-04-19 18:26:34 +00001795 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1796 // This gets unpoisoned where it is allowed.
1797 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1798 if (MI->isC99Varargs())
1799 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Chris Lattner141e71f2008-03-09 01:54:53 +00001801 // Read the first token after the arg list for down below.
1802 LexUnexpandedToken(Tok);
Richard Smith80ad52f2013-01-02 11:42:31 +00001803 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001804 // C99 requires whitespace between the macro definition and the body. Emit
1805 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001806 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001807 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001808 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1809 // first character of a replacement list is not a character required by
1810 // subclause 5.2.1, then there shall be white-space separation between the
1811 // identifier and the replacement list.". 5.2.1 lists this set:
1812 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1813 // is irrelevant here.
1814 bool isInvalid = false;
1815 if (Tok.is(tok::at)) // @ is not in the list above.
1816 isInvalid = true;
1817 else if (Tok.is(tok::unknown)) {
1818 // If we have an unknown token, it is something strange like "`". Since
1819 // all of valid characters would have lexed into a single character
1820 // token of some sort, we know this is not a valid case.
1821 isInvalid = true;
1822 }
1823 if (isInvalid)
1824 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1825 else
1826 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001827 }
Chris Lattner2451b522009-04-21 04:46:33 +00001828
Peter Collingbourne84021552011-02-28 02:37:51 +00001829 if (!Tok.is(tok::eod))
Chris Lattner2451b522009-04-21 04:46:33 +00001830 LastTok = Tok;
1831
Chris Lattner141e71f2008-03-09 01:54:53 +00001832 // Read the rest of the macro body.
1833 if (MI->isObjectLike()) {
1834 // Object-like macros are very simple, just read their body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001835 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001836 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001837 MI->AddTokenToBody(Tok);
1838 // Get the next token of the macro.
1839 LexUnexpandedToken(Tok);
1840 }
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Chris Lattner141e71f2008-03-09 01:54:53 +00001842 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001843 // Otherwise, read the body of a function-like macro. While we are at it,
1844 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1845 // parameters in function-like macro expansions.
Peter Collingbourne84021552011-02-28 02:37:51 +00001846 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001847 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001848
Eli Friedman4fa4b482012-11-14 02:18:46 +00001849 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001850 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Chris Lattner141e71f2008-03-09 01:54:53 +00001852 // Get the next token of the macro.
1853 LexUnexpandedToken(Tok);
1854 continue;
1855 }
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Eli Friedman4fa4b482012-11-14 02:18:46 +00001857 if (Tok.is(tok::hashhash)) {
1858
1859 // If we see token pasting, check if it looks like the gcc comma
1860 // pasting extension. We'll use this information to suppress
1861 // diagnostics later on.
1862
1863 // Get the next token of the macro.
1864 LexUnexpandedToken(Tok);
1865
1866 if (Tok.is(tok::eod)) {
1867 MI->AddTokenToBody(LastTok);
1868 break;
1869 }
1870
1871 unsigned NumTokens = MI->getNumTokens();
1872 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1873 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1874 MI->setHasCommaPasting();
1875
1876 // Things look ok, add the '##' and param name tokens to the macro.
1877 MI->AddTokenToBody(LastTok);
1878 MI->AddTokenToBody(Tok);
1879 LastTok = Tok;
1880
1881 // Get the next token of the macro.
1882 LexUnexpandedToken(Tok);
1883 continue;
1884 }
1885
Chris Lattner141e71f2008-03-09 01:54:53 +00001886 // Get the next token of the macro.
1887 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Chris Lattner32404692009-05-25 17:16:10 +00001889 // Check for a valid macro arg identifier.
1890 if (Tok.getIdentifierInfo() == 0 ||
1891 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1892
1893 // If this is assembler-with-cpp mode, we accept random gibberish after
1894 // the '#' because '#' is often a comment character. However, change
1895 // the kind of the token to tok::unknown so that the preprocessor isn't
1896 // confused.
David Blaikie4e4d0842012-03-11 07:00:24 +00001897 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner32404692009-05-25 17:16:10 +00001898 LastTok.setKind(tok::unknown);
1899 } else {
1900 Diag(Tok, diag::err_pp_stringize_not_parameter);
1901 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Chris Lattner32404692009-05-25 17:16:10 +00001903 // Disable __VA_ARGS__ again.
1904 Ident__VA_ARGS__->setIsPoisoned(true);
1905 return;
1906 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001907 }
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Chris Lattner32404692009-05-25 17:16:10 +00001909 // Things look ok, add the '#' and param name tokens to the macro.
1910 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001911 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001912 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Chris Lattner141e71f2008-03-09 01:54:53 +00001914 // Get the next token of the macro.
1915 LexUnexpandedToken(Tok);
1916 }
1917 }
Mike Stump1eb44332009-09-09 15:08:12 +00001918
1919
Chris Lattner141e71f2008-03-09 01:54:53 +00001920 // Disable __VA_ARGS__ again.
1921 Ident__VA_ARGS__->setIsPoisoned(true);
1922
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001923 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattner141e71f2008-03-09 01:54:53 +00001924 // replacement list.
1925 unsigned NumTokens = MI->getNumTokens();
1926 if (NumTokens != 0) {
1927 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1928 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001929 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001930 return;
1931 }
1932 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1933 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001934 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001935 return;
1936 }
1937 }
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Chris Lattner2451b522009-04-21 04:46:33 +00001939 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Chris Lattner141e71f2008-03-09 01:54:53 +00001941 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8a64bb52012-08-29 00:20:03 +00001942 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001943 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001944 // It is very common for system headers to have tons of macro redefinitions
1945 // and for warnings to be disabled in system headers. If this is the case,
1946 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001947 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001948 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001949 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner41c3ae12009-01-16 19:50:11 +00001950 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001951
Richard Smitheed55e62013-03-06 00:46:00 +00001952 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
1953 // C++ [cpp.predefined]p4, but allow it as an extension.
1954 if (OtherMI->isBuiltinMacro())
1955 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerf47724b2010-08-17 15:55:45 +00001956 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidisbd25ff82013-04-03 17:39:30 +00001957 // separation must be the same. C99 6.10.3p2.
Richard Smitheed55e62013-03-06 00:46:00 +00001958 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidisbd25ff82013-04-03 17:39:30 +00001959 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001960 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1961 << MacroNameTok.getIdentifierInfo();
1962 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1963 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001964 }
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001965 if (OtherMI->isWarnIfUnused())
1966 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattner141e71f2008-03-09 01:54:53 +00001967 }
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001969 DefMacroDirective *MD =
1970 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001972 assert(!MI->isUsed());
1973 // If we need warning for not using the macro, add its location in the
1974 // warn-because-unused-macro set. If it gets used it will be removed from set.
1975 if (isInPrimaryFile() && // don't warn for include'd macros.
1976 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikied6471f72011-09-25 23:23:43 +00001977 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001978 MI->setIsWarnIfUnused(true);
1979 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1980 }
1981
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001982 // If the callbacks want to know, tell them about the macro definition.
1983 if (Callbacks)
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00001984 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattner141e71f2008-03-09 01:54:53 +00001985}
1986
James Dennettdc201692012-06-22 05:46:07 +00001987/// HandleUndefDirective - Implements \#undef.
Chris Lattner141e71f2008-03-09 01:54:53 +00001988///
1989void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1990 ++NumUndefined;
1991
1992 Token MacroNameTok;
1993 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Chris Lattner141e71f2008-03-09 01:54:53 +00001995 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001996 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001997 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Chris Lattner141e71f2008-03-09 01:54:53 +00001999 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00002000 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Chris Lattner141e71f2008-03-09 01:54:53 +00002002 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002003 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00002004 const MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Argyrios Kyrtzidis36845472013-01-16 16:52:44 +00002006 // If the callbacks want to know, tell them about the macro #undef.
2007 // Note: no matter if the macro was defined or not.
2008 if (Callbacks)
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00002009 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis36845472013-01-16 16:52:44 +00002010
Chris Lattner141e71f2008-03-09 01:54:53 +00002011 // If the macro is not defined, this is a noop undef, just return.
2012 if (MI == 0) return;
2013
Argyrios Kyrtzidis1f8dcfc2011-07-11 20:39:47 +00002014 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattner141e71f2008-03-09 01:54:53 +00002015 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00002016
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002017 if (MI->isWarnIfUnused())
2018 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2019
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00002020 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2021 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattner141e71f2008-03-09 01:54:53 +00002022}
2023
2024
2025//===----------------------------------------------------------------------===//
2026// Preprocessor Conditional Directive Handling.
2027//===----------------------------------------------------------------------===//
2028
James Dennettdc201692012-06-22 05:46:07 +00002029/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2030/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2031/// true if any tokens have been returned or pp-directives activated before this
2032/// \#ifndef has been lexed.
Chris Lattner141e71f2008-03-09 01:54:53 +00002033///
2034void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2035 bool ReadAnyTokensBeforeDirective) {
2036 ++NumIf;
2037 Token DirectiveTok = Result;
2038
2039 Token MacroNameTok;
2040 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Chris Lattner141e71f2008-03-09 01:54:53 +00002042 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00002043 if (MacroNameTok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002044 // Skip code until we get to #endif. This helps with recovery by not
2045 // emitting an error when the #endif is reached.
2046 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2047 /*Foundnonskip*/false, /*FoundElse*/false);
2048 return;
2049 }
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Chris Lattner141e71f2008-03-09 01:54:53 +00002051 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00002052 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00002053
Chris Lattner13d283d2010-02-12 08:03:27 +00002054 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00002055 MacroDirective *MD = getMacroDirective(MII);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00002056 MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002057
Ted Kremenek60e45d42008-11-18 00:34:22 +00002058 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00002059 // If the start of a top-level #ifdef and if the macro is not defined,
2060 // inform MIOpt that this might be the start of a proper include guard.
2061 // Otherwise it is some other form of unknown conditional which we can't
2062 // handle.
2063 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002064 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00002065 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00002066 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00002067 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00002068 }
2069
Chris Lattner141e71f2008-03-09 01:54:53 +00002070 // If there is a macro, process it.
2071 if (MI) // Mark it used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002072 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002074 if (Callbacks) {
2075 if (isIfndef)
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00002076 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002077 else
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +00002078 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002079 }
2080
Chris Lattner141e71f2008-03-09 01:54:53 +00002081 // Should we include the stuff contained by this directive?
2082 if (!MI == isIfndef) {
2083 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00002084 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2085 /*wasskip*/false, /*foundnonskip*/true,
2086 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00002087 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00002088 // No, skip the contents of this block.
Chris Lattner141e71f2008-03-09 01:54:53 +00002089 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002090 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002091 /*FoundElse*/false);
2092 }
2093}
2094
James Dennettdc201692012-06-22 05:46:07 +00002095/// HandleIfDirective - Implements the \#if directive.
Chris Lattner141e71f2008-03-09 01:54:53 +00002096///
2097void Preprocessor::HandleIfDirective(Token &IfToken,
2098 bool ReadAnyTokensBeforeDirective) {
2099 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Craig Silverstein08985b92010-11-06 01:19:03 +00002101 // Parse and evaluate the conditional expression.
Chris Lattner141e71f2008-03-09 01:54:53 +00002102 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein08985b92010-11-06 01:19:03 +00002103 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2104 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2105 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes0049db62008-06-01 18:31:24 +00002106
2107 // If this condition is equivalent to #ifndef X, and if this is the first
2108 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002109 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00002110 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00002111 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00002112 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00002113 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00002114 }
2115
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002116 if (Callbacks)
2117 Callbacks->If(IfToken.getLocation(),
2118 SourceRange(ConditionalBegin, ConditionalEnd));
2119
Chris Lattner141e71f2008-03-09 01:54:53 +00002120 // Should we include the stuff contained by this directive?
2121 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002122 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002123 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002124 /*foundnonskip*/true, /*foundelse*/false);
2125 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00002126 // No, skip the contents of this block.
Mike Stump1eb44332009-09-09 15:08:12 +00002127 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002128 /*FoundElse*/false);
2129 }
2130}
2131
James Dennettdc201692012-06-22 05:46:07 +00002132/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattner141e71f2008-03-09 01:54:53 +00002133///
2134void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2135 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Chris Lattner141e71f2008-03-09 01:54:53 +00002137 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00002138 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00002139
Chris Lattner141e71f2008-03-09 01:54:53 +00002140 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00002141 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002142 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00002143 Diag(EndifToken, diag::err_pp_endif_without_if);
2144 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00002145 }
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Chris Lattner141e71f2008-03-09 01:54:53 +00002147 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002148 if (CurPPLexer->getConditionalStackDepth() == 0)
2149 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Ted Kremenek60e45d42008-11-18 00:34:22 +00002151 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00002152 "This code should only be reachable in the non-skipping case!");
Craig Silverstein08985b92010-11-06 01:19:03 +00002153
2154 if (Callbacks)
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002155 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +00002156}
2157
James Dennettdc201692012-06-22 05:46:07 +00002158/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein08985b92010-11-06 01:19:03 +00002159///
Chris Lattner141e71f2008-03-09 01:54:53 +00002160void Preprocessor::HandleElseDirective(Token &Result) {
2161 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00002162
Chris Lattner141e71f2008-03-09 01:54:53 +00002163 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00002164 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Chris Lattner141e71f2008-03-09 01:54:53 +00002166 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00002167 if (CurPPLexer->popConditionalLevel(CI)) {
2168 Diag(Result, diag::pp_err_else_without_if);
2169 return;
2170 }
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Chris Lattner141e71f2008-03-09 01:54:53 +00002172 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002173 if (CurPPLexer->getConditionalStackDepth() == 0)
2174 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00002175
2176 // If this is a #else with a #else before it, report the error.
2177 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002179 if (Callbacks)
2180 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2181
Craig Silverstein08985b92010-11-06 01:19:03 +00002182 // Finally, skip the rest of the contents of this block.
2183 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00002184 /*FoundElse*/true, Result.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00002185}
2186
James Dennettdc201692012-06-22 05:46:07 +00002187/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein08985b92010-11-06 01:19:03 +00002188///
Chris Lattner141e71f2008-03-09 01:54:53 +00002189void Preprocessor::HandleElifDirective(Token &ElifToken) {
2190 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Chris Lattner141e71f2008-03-09 01:54:53 +00002192 // #elif directive in a non-skipping conditional... start skipping.
2193 // We don't care what the condition is, because we will always skip it (since
2194 // the block immediately before it was included).
Craig Silverstein08985b92010-11-06 01:19:03 +00002195 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00002196 DiscardUntilEndOfDirective();
Craig Silverstein08985b92010-11-06 01:19:03 +00002197 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00002198
2199 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00002200 if (CurPPLexer->popConditionalLevel(CI)) {
2201 Diag(ElifToken, diag::pp_err_elif_without_if);
2202 return;
2203 }
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Chris Lattner141e71f2008-03-09 01:54:53 +00002205 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002206 if (CurPPLexer->getConditionalStackDepth() == 0)
2207 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00002208
Chris Lattner141e71f2008-03-09 01:54:53 +00002209 // If this is a #elif with a #else before it, report the error.
2210 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002211
2212 if (Callbacks)
2213 Callbacks->Elif(ElifToken.getLocation(),
2214 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +00002215
Craig Silverstein08985b92010-11-06 01:19:03 +00002216 // Finally, skip the rest of the contents of this block.
2217 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00002218 /*FoundElse*/CI.FoundElse,
2219 ElifToken.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00002220}