blob: cb56615ddcc4b2e361ece86e3bc27226c91b28f5 [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattnerf64b3522008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner710bb872009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-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 Lattner100c65e2009-01-26 05:29:08 +000025#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000026#include "llvm/Support/ErrorHandling.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000027#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000028using namespace clang;
29
30//===----------------------------------------------------------------------===//
31// Utility Methods for Preprocessor Directive Handling.
32//===----------------------------------------------------------------------===//
33
Chris Lattnerc0a585d2010-08-17 15:55:45 +000034MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000035 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000036
Ted Kremenekc8456f82010-10-19 22:15:20 +000037 if (MICache) {
38 MIChain = MICache;
39 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000040 }
Ted Kremenekc8456f82010-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 Lattnerc0a585d2010-08-17 15:55:45 +000052}
53
54MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
55 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000056 new (MI) MacroInfo(L);
57 return MI;
58}
59
Argyrios Kyrtzidis4f32da12013-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 Kyrtzidisd48b91d2013-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 Kyrtzidis4f32da12013-03-22 21:12:51 +000070 new (MI) MacroInfo(L);
71 MI->FromASTFile = true;
72 MI->setOwningModuleID(SubModuleID);
73 return MI;
74}
75
Argyrios Kyrtzidisb6210df2013-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 Kyrtzidis09c9e812013-02-20 00:54:57 +000096 return MD;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000097}
98
James Dennettf6333ac2012-06-22 05:46:07 +000099/// \brief Release the specified MacroInfo to be reused for allocating
100/// new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +0000101void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-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 Lattner666f7a42009-02-20 22:19:20 +0000116
Ted Kremenekc8456f82010-10-19 22:15:20 +0000117 MI->Destroy();
118}
Chris Lattner666f7a42009-02-20 22:19:20 +0000119
James Dennettf6333ac2012-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 Lattnerf64b3522008-03-09 01:54:53 +0000122void Preprocessor::DiscardUntilEndOfDirective() {
123 Token Tmp;
124 do {
125 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000126 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000127 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000128}
129
James Dennettf6333ac2012-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 Lattnerf64b3522008-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 Stump11289f42009-09-09 15:08:12 +0000140
Douglas Gregor12785102010-08-24 20:21:13 +0000141 if (MacroNameTok.is(tok::code_completion)) {
142 if (CodeComplete)
143 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000144 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000145 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000146 }
147
Chris Lattnerf64b3522008-03-09 01:54:53 +0000148 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000149 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000150 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
151 return;
152 }
Mike Stump11289f42009-09-09 15:08:12 +0000153
Chris Lattnerf64b3522008-03-09 01:54:53 +0000154 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
155 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000156 bool Invalid = false;
157 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
158 if (Invalid)
159 return;
Nico Weber2e686202012-02-29 22:54:43 +0000160
Chris Lattner77c76ae2008-12-13 20:12:40 +0000161 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000162
163 // Allow #defining |and| and friends in microsoft mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000164 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weber2e686202012-02-29 22:54:43 +0000165 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
166 return;
167 }
168
Chris Lattner77c76ae2008-12-13 20:12:40 +0000169 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000170 // C++ 2.5p2: Alternative tokens behave the same as its primary token
171 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000172 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-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 Smith7b242542013-03-06 00:46:00 +0000177 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000178 Diag(MacroNameTok, diag::err_defined_macro_name);
Richard Smith7b242542013-03-06 00:46:00 +0000179 } else if (isDefineUndef == 2 && II->hasMacroDefinition() &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000180 getMacroInfo(II)->isBuiltinMacro()) {
Richard Smith7b242542013-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 Lattnerf64b3522008-03-09 01:54:53 +0000185 } else {
186 // Okay, we got a good identifier node. Return it.
187 return;
188 }
Mike Stump11289f42009-09-09 15:08:12 +0000189
Chris Lattnerf64b3522008-03-09 01:54:53 +0000190 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000191 // token kind to tok::eod.
192 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000193 return DiscardUntilEndOfDirective();
194}
195
James Dennettf6333ac2012-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 Lattner0003c272009-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 Lattnerf64b3522008-03-09 01:54:53 +0000201 Token Tmp;
Chris Lattner0003c272009-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 Stump11289f42009-09-09 15:08:12 +0000209
Chris Lattnerf64b3522008-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 Stump11289f42009-09-09 15:08:12 +0000214
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000215 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000216 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-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 Gregora771f462010-03-31 17:46:05 +0000220 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000221 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000222 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000223 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
224 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000225 DiscardUntilEndOfDirective();
226 }
227}
228
229
230
James Dennettf6333ac2012-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 Lattnerf64b3522008-03-09 01:54:53 +0000234/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-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 Lattnerf64b3522008-03-09 01:54:53 +0000239void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
240 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000241 bool FoundElse,
242 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000243 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000244 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000245
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000246 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000247 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000248
Ted Kremenek56572ab2008-12-12 18:34:08 +0000249 if (CurPTHLexer) {
250 PTHSkipExcludedConditionalBlock();
251 return;
252 }
Mike Stump11289f42009-09-09 15:08:12 +0000253
Chris Lattnerf64b3522008-03-09 01:54:53 +0000254 // Enter raw mode to disable identifier lookup (and thus macro expansion),
255 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000256 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000257 Token Tok;
258 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000259 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000260
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000261 if (Tok.is(tok::code_completion)) {
262 if (CodeComplete)
263 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000264 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000265 continue;
266 }
267
Chris Lattnerf64b3522008-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 Kremenek30cd88c2008-11-18 00:34:22 +0000272 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000273 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000274 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
275 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000276 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000277 }
278
Chris Lattnerf64b3522008-03-09 01:54:53 +0000279 // Just return and let the caller lex after this #include.
280 break;
281 }
Mike Stump11289f42009-09-09 15:08:12 +0000282
Chris Lattnerf64b3522008-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 Stump11289f42009-09-09 15:08:12 +0000286
Chris Lattnerf64b3522008-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 Collingbourne2f1e36b2011-02-28 02:37:51 +0000289 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000290 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000291 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000292
Mike Stump11289f42009-09-09 15:08:12 +0000293
Chris Lattnerf64b3522008-03-09 01:54:53 +0000294 // Read the next token, the directive flavor.
295 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000296
Chris Lattnerf64b3522008-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 Bagnaraea4f7c72010-12-22 08:23:18 +0000299 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000300 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000301 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000302 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-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 Bagnaraea4f7c72010-12-22 08:23:18 +0000311 const char *RawCharData = Tok.getRawIdentifierData();
312
Chris Lattnerf64b3522008-03-09 01:54:53 +0000313 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000314 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000315 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000316 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000317 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000318 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000319 continue;
320 }
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chris Lattnerf64b3522008-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 Kramer144884642009-12-31 13:32:38 +0000325 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000326 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000327 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000328 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 } else {
330 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000331 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000332 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000333 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000334 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000335 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000336 continue;
337 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000338 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000339 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000340 }
Mike Stump11289f42009-09-09 15:08:12 +0000341
Benjamin Kramer144884642009-12-31 13:32:38 +0000342 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000343 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000344 if (Sub.empty() || // "if"
345 Sub == "def" || // "ifdef"
346 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-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 Kremenek30cd88c2008-11-18 00:34:22 +0000350 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000351 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000352 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000353 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000354 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000355 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000356 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000357 PPConditionalInfo CondInfo;
358 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000359 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000360 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000361 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000362
Chris Lattnerf64b3522008-03-09 01:54:53 +0000363 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000364 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-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 Smithd0124572012-06-21 00:35:03 +0000368 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000369 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000370 if (Callbacks)
371 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000372 break;
Richard Smithd0124572012-06-21 00:35:03 +0000373 } else {
374 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000375 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000376 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-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 Kremenek30cd88c2008-11-18 00:34:22 +0000380 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000381
Chris Lattnerf64b3522008-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 Stump11289f42009-09-09 15:08:12 +0000384
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385 // Note that we've seen a #else in this conditional.
386 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000387
Chris Lattnerf64b3522008-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 Smith87d8fb92012-06-24 23:56:26 +0000392 // Restore the value of LexingRawMode so that trailing comments
393 // are handled correctly.
394 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000395 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000396 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000397 if (Callbacks)
398 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000399 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000400 } else {
401 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000402 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000403 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000404 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000405
406 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000407 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-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 Kremenek30cd88c2008-11-18 00:34:22 +0000416 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
417 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000418 IdentifierInfo *IfNDefMacro = 0;
419 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000420 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000421 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000422 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattnerf64b3522008-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 Stump11289f42009-09-09 15:08:12 +0000426
Chris Lattnerf64b3522008-03-09 01:54:53 +0000427 // If this condition is true, enter it!
428 if (ShouldEnter) {
429 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000430 if (Callbacks)
431 Callbacks->Elif(Tok.getLocation(),
432 SourceRange(ConditionalBegin, ConditionalEnd),
433 CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000434 break;
435 }
436 }
437 }
Mike Stump11289f42009-09-09 15:08:12 +0000438
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000439 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000440 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000441 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-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 Kremenek30cd88c2008-11-18 00:34:22 +0000447 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-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 Lattnerf64b3522008-03-09 01:54:53 +0000453}
454
Ted Kremenek56572ab2008-12-12 18:34:08 +0000455void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000456
457 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000458 assert(CurPTHLexer);
459 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000460
Ted Kremenek56572ab2008-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 Yasskinb3321532010-12-23 01:01:28 +0000467 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000468 assert(!InCond && "Can't be skipping if not in a conditional!");
469 break;
470 }
Mike Stump11289f42009-09-09 15:08:12 +0000471
Ted Kremenek56572ab2008-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 Stump11289f42009-09-09 15:08:12 +0000476
Ted Kremenek56572ab2008-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 Stump11289f42009-09-09 15:08:12 +0000488
Ted Kremenek56572ab2008-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 Stump11289f42009-09-09 15:08:12 +0000492
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000493 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000494 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000495 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000496 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000497
Ted Kremenek56572ab2008-12-12 18:34:08 +0000498 break;
499 }
Mike Stump11289f42009-09-09 15:08:12 +0000500
Ted Kremenek56572ab2008-12-12 18:34:08 +0000501 // Otherwise skip this block.
502 continue;
503 }
Mike Stump11289f42009-09-09 15:08:12 +0000504
Ted Kremenek56572ab2008-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 Stump11289f42009-09-09 15:08:12 +0000511
Ted Kremenek56572ab2008-12-12 18:34:08 +0000512 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000513 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-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 Carruth3cc331a2011-03-16 18:34:36 +0000534const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000535 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000536 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000537 bool isAngled,
538 const DirectoryLookup *FromDir,
539 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000540 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000541 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000542 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000543 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000544 // If the header lookup mechanism may be relative to the current file, pass in
545 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000546 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000547 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000548 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000549 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000550
Chris Lattner022923a2009-02-04 19:45:07 +0000551 // If there is no file entry associated with this file, it must be the
552 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000553 // it won't be scanned for preprocessor directives. If we have the
554 // predefines buffer, resolve #include references (which come from the
555 // -include command line argument) as if they came from the main file, this
556 // affects file lookup etc.
557 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000558 FID = SourceMgr.getMainFileID();
559 CurFileEnt = SourceMgr.getFileEntryForID(FID);
560 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000561 }
Mike Stump11289f42009-09-09 15:08:12 +0000562
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000563 // Do a standard file entry lookup.
564 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000565 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000566 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000567 SearchPath, RelativePath, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000568 if (FE) {
569 if (SuggestedModule) {
570 Module *RequestedModule = SuggestedModule->getModule();
571 if (RequestedModule) {
572 ModuleMap::ModuleHeaderRole Role = SuggestedModule->getRole();
573 #ifndef NDEBUG
574 // Check for consistency between the module header role
575 // as obtained from the lookup and as obtained from the module.
576 // This check is not cheap, so enable it only for debugging.
577 SmallVectorImpl<const FileEntry *> &PvtHdrs
578 = RequestedModule->PrivateHeaders;
579 SmallVectorImpl<const FileEntry *>::iterator Look
580 = std::find(PvtHdrs.begin(), PvtHdrs.end(), FE);
581 bool IsPrivate = Look != PvtHdrs.end();
582 assert((IsPrivate && Role == ModuleMap::PrivateHeader)
583 || (!IsPrivate && Role != ModuleMap::PrivateHeader));
584 #endif
585 if (Role == ModuleMap::PrivateHeader) {
586 if (RequestedModule->getTopLevelModule() != getCurrentModule())
587 Diag(FilenameLoc, diag::error_use_of_private_header_outside_module)
588 << Filename;
589 }
590 }
591 }
592 return FE;
593 }
Mike Stump11289f42009-09-09 15:08:12 +0000594
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000595 // Otherwise, see if this is a subframework header. If so, this is relative
596 // to one of the headers on the #include stack. Walk the list of the current
597 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000598 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000599 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000600 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000601 SearchPath, RelativePath,
602 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000603 return FE;
604 }
Mike Stump11289f42009-09-09 15:08:12 +0000605
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000606 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
607 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000608 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000609 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000610 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000611 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000612 Filename, CurFileEnt, SearchPath, RelativePath,
613 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000614 return FE;
615 }
616 }
Mike Stump11289f42009-09-09 15:08:12 +0000617
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000618 // Otherwise, we really couldn't find the file.
619 return 0;
620}
621
Chris Lattnerf64b3522008-03-09 01:54:53 +0000622
623//===----------------------------------------------------------------------===//
624// Preprocessor Directive Handling.
625//===----------------------------------------------------------------------===//
626
David Blaikied5321242012-06-06 18:52:13 +0000627class Preprocessor::ResetMacroExpansionHelper {
628public:
629 ResetMacroExpansionHelper(Preprocessor *pp)
630 : PP(pp), save(pp->DisableMacroExpansion) {
631 if (pp->MacroExpansionInDirectivesOverride)
632 pp->DisableMacroExpansion = false;
633 }
634 ~ResetMacroExpansionHelper() {
635 PP->DisableMacroExpansion = save;
636 }
637private:
638 Preprocessor *PP;
639 bool save;
640};
641
Chris Lattnerf64b3522008-03-09 01:54:53 +0000642/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000643/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000644/// lexer/preprocessor state, and advances the lexer(s) so that the next token
645/// read is the correct one.
646void Preprocessor::HandleDirective(Token &Result) {
647 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000648
Chris Lattnerf64b3522008-03-09 01:54:53 +0000649 // We just parsed a # character at the start of a line, so we're in directive
650 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000651 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000652 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000653 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000654
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000655 bool ImmediatelyAfterTopLevelIfndef =
656 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
657 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
658
Chris Lattnerf64b3522008-03-09 01:54:53 +0000659 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000660
Chris Lattnerf64b3522008-03-09 01:54:53 +0000661 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000662 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000663 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000664 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000665
Chris Lattner2d17ab72009-03-18 21:00:25 +0000666 // Save the '#' token in case we need to return it later.
667 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000668
Chris Lattnerf64b3522008-03-09 01:54:53 +0000669 // Read the next token, the directive flavor. This isn't expanded due to
670 // C99 6.10.3p8.
671 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000672
Chris Lattnerf64b3522008-03-09 01:54:53 +0000673 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
674 // #define A(x) #x
675 // A(abc
676 // #warning blah
677 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000678 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
679 // not support this for #include-like directives, since that can result in
680 // terrible diagnostics, and does not work in GCC.
681 if (InMacroArgs) {
682 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
683 switch (II->getPPKeywordID()) {
684 case tok::pp_include:
685 case tok::pp_import:
686 case tok::pp_include_next:
687 case tok::pp___include_macros:
688 Diag(Result, diag::err_embedded_include) << II->getName();
689 DiscardUntilEndOfDirective();
690 return;
691 default:
692 break;
693 }
694 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000695 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000696 }
Mike Stump11289f42009-09-09 15:08:12 +0000697
David Blaikied5321242012-06-06 18:52:13 +0000698 // Temporarily enable macro expansion if set so
699 // and reset to previous state when returning from this function.
700 ResetMacroExpansionHelper helper(this);
701
Chris Lattnerf64b3522008-03-09 01:54:53 +0000702 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000703 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000704 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000705 case tok::code_completion:
706 if (CodeComplete)
707 CodeComplete->CodeCompleteDirective(
708 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000709 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000710 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000711 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000712 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000713 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000714 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000715 default:
716 IdentifierInfo *II = Result.getIdentifierInfo();
717 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000718
Chris Lattnerf64b3522008-03-09 01:54:53 +0000719 // Ask what the preprocessor keyword ID is.
720 switch (II->getPPKeywordID()) {
721 default: break;
722 // C99 6.10.1 - Conditional Inclusion.
723 case tok::pp_if:
724 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
725 case tok::pp_ifdef:
726 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
727 case tok::pp_ifndef:
728 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
729 case tok::pp_elif:
730 return HandleElifDirective(Result);
731 case tok::pp_else:
732 return HandleElseDirective(Result);
733 case tok::pp_endif:
734 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattnerf64b3522008-03-09 01:54:53 +0000736 // C99 6.10.2 - Source File Inclusion.
737 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000738 // Handle #include.
739 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000740 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000741 // Handle -imacros.
742 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000743
Chris Lattnerf64b3522008-03-09 01:54:53 +0000744 // C99 6.10.3 - Macro Replacement.
745 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000746 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000747 case tok::pp_undef:
748 return HandleUndefDirective(Result);
749
750 // C99 6.10.4 - Line Control.
751 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000752 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000753
Chris Lattnerf64b3522008-03-09 01:54:53 +0000754 // C99 6.10.5 - Error Directive.
755 case tok::pp_error:
756 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000757
Chris Lattnerf64b3522008-03-09 01:54:53 +0000758 // C99 6.10.6 - Pragma Directive.
759 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000760 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattnerf64b3522008-03-09 01:54:53 +0000762 // GNU Extensions.
763 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000764 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000765 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000766 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000767
Chris Lattnerf64b3522008-03-09 01:54:53 +0000768 case tok::pp_warning:
769 Diag(Result, diag::ext_pp_warning_directive);
770 return HandleUserDiagnosticDirective(Result, true);
771 case tok::pp_ident:
772 return HandleIdentSCCSDirective(Result);
773 case tok::pp_sccs:
774 return HandleIdentSCCSDirective(Result);
775 case tok::pp_assert:
776 //isExtension = true; // FIXME: implement #assert
777 break;
778 case tok::pp_unassert:
779 //isExtension = true; // FIXME: implement #unassert
780 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000781
Douglas Gregor663b48f2012-01-03 19:48:16 +0000782 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000783 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000784 return HandleMacroPublicDirective(Result);
785 break;
786
Douglas Gregor663b48f2012-01-03 19:48:16 +0000787 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000788 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000789 return HandleMacroPrivateDirective(Result);
790 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000791 }
792 break;
793 }
Mike Stump11289f42009-09-09 15:08:12 +0000794
Chris Lattner2d17ab72009-03-18 21:00:25 +0000795 // If this is a .S file, treat unknown # directives as non-preprocessor
796 // directives. This is important because # may be a comment or introduce
797 // various pseudo-ops. Just return the # token and push back the following
798 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000799 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000800 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000801 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000802 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000803 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000804
805 // If the second token is a hashhash token, then we need to translate it to
806 // unknown so the token lexer doesn't try to perform token pasting.
807 if (Result.is(tok::hashhash))
808 Toks[1].setKind(tok::unknown);
809
Chris Lattner2d17ab72009-03-18 21:00:25 +0000810 // Enter this token stream so that we re-lex the tokens. Make sure to
811 // enable macro expansion, in case the token after the # is an identifier
812 // that is expanded.
813 EnterTokenStream(Toks, 2, false, true);
814 return;
815 }
Mike Stump11289f42009-09-09 15:08:12 +0000816
Chris Lattnerf64b3522008-03-09 01:54:53 +0000817 // If we reached here, the preprocessing token is not valid!
818 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000819
Chris Lattnerf64b3522008-03-09 01:54:53 +0000820 // Read the rest of the PP line.
821 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000822
Chris Lattnerf64b3522008-03-09 01:54:53 +0000823 // Okay, we're done parsing the directive.
824}
825
Chris Lattner76e68962009-01-26 06:19:46 +0000826/// GetLineValue - Convert a numeric token into an unsigned value, emitting
827/// Diagnostic DiagID if it is invalid, and returning the value in Val.
828static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000829 unsigned DiagID, Preprocessor &PP,
830 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000831 if (DigitTok.isNot(tok::numeric_constant)) {
832 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000833
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000834 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000835 PP.DiscardUntilEndOfDirective();
836 return true;
837 }
Mike Stump11289f42009-09-09 15:08:12 +0000838
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000839 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000840 IntegerBuffer.resize(DigitTok.getLength());
841 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000842 bool Invalid = false;
843 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
844 if (Invalid)
845 return true;
846
Chris Lattnerd66f1722009-04-18 18:35:15 +0000847 // Verify that we have a simple digit-sequence, and compute the value. This
848 // is always a simple digit string computed in decimal, so we do this manually
849 // here.
850 Val = 0;
851 for (unsigned i = 0; i != ActualLength; ++i) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000852 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000853 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000854 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000855 PP.DiscardUntilEndOfDirective();
856 return true;
857 }
Mike Stump11289f42009-09-09 15:08:12 +0000858
Chris Lattnerd66f1722009-04-18 18:35:15 +0000859 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
860 if (NextVal < Val) { // overflow.
861 PP.Diag(DigitTok, DiagID);
862 PP.DiscardUntilEndOfDirective();
863 return true;
864 }
865 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000866 }
Mike Stump11289f42009-09-09 15:08:12 +0000867
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000868 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000869 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
870 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000871
Chris Lattner76e68962009-01-26 06:19:46 +0000872 return false;
873}
874
James Dennettf6333ac2012-06-22 05:46:07 +0000875/// \brief Handle a \#line directive: C99 6.10.4.
876///
877/// The two acceptable forms are:
878/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000879/// # line digit-sequence
880/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000881/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000882void Preprocessor::HandleLineDirective(Token &Tok) {
883 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
884 // expanded.
885 Token DigitTok;
886 Lex(DigitTok);
887
Chris Lattner100c65e2009-01-26 05:29:08 +0000888 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000889 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000890 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000891 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000892
893 if (LineNo == 0)
894 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000895
Chris Lattner76e68962009-01-26 06:19:46 +0000896 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
897 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000898 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000899 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000900 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000901 if (LineNo >= LineLimit)
902 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000903 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000904 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000905
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000906 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000907 Token StrTok;
908 Lex(StrTok);
909
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000910 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
911 // string followed by eod.
912 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000913 ; // ok
914 else if (StrTok.isNot(tok::string_literal)) {
915 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000916 return DiscardUntilEndOfDirective();
917 } else if (StrTok.hasUDSuffix()) {
918 Diag(StrTok, diag::err_invalid_string_udl);
919 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000920 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000921 // Parse and validate the string, converting it into a unique ID.
922 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000923 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000924 if (Literal.hadError)
925 return DiscardUntilEndOfDirective();
926 if (Literal.Pascal) {
927 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
928 return DiscardUntilEndOfDirective();
929 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000930 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000931
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000932 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000933 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
934 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000935 }
Mike Stump11289f42009-09-09 15:08:12 +0000936
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000937 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000938
Chris Lattner839150e2009-03-27 17:13:49 +0000939 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000940 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
941 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000942 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000943}
944
Chris Lattner76e68962009-01-26 06:19:46 +0000945/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
946/// marker directive.
947static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
948 bool &IsSystemHeader, bool &IsExternCHeader,
949 Preprocessor &PP) {
950 unsigned FlagVal;
951 Token FlagTok;
952 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000953 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000954 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
955 return true;
956
957 if (FlagVal == 1) {
958 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000959
Chris Lattner76e68962009-01-26 06:19:46 +0000960 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000961 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000962 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
963 return true;
964 } else if (FlagVal == 2) {
965 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000966
Chris Lattner1c967782009-02-04 06:25:26 +0000967 SourceManager &SM = PP.getSourceManager();
968 // If we are leaving the current presumed file, check to make sure the
969 // presumed include stack isn't empty!
970 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000971 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000972 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000973 if (PLoc.isInvalid())
974 return true;
975
Chris Lattner1c967782009-02-04 06:25:26 +0000976 // If there is no include loc (main file) or if the include loc is in a
977 // different physical file, then we aren't in a "1" line marker flag region.
978 SourceLocation IncLoc = PLoc.getIncludeLoc();
979 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000980 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000981 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
982 PP.DiscardUntilEndOfDirective();
983 return true;
984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattner76e68962009-01-26 06:19:46 +0000986 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000987 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000988 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
989 return true;
990 }
991
992 // We must have 3 if there are still flags.
993 if (FlagVal != 3) {
994 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000995 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000996 return true;
997 }
Mike Stump11289f42009-09-09 15:08:12 +0000998
Chris Lattner76e68962009-01-26 06:19:46 +0000999 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001000
Chris Lattner76e68962009-01-26 06:19:46 +00001001 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001002 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001003 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001004 return true;
1005
1006 // We must have 4 if there is yet another flag.
1007 if (FlagVal != 4) {
1008 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001009 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001010 return true;
1011 }
Mike Stump11289f42009-09-09 15:08:12 +00001012
Chris Lattner76e68962009-01-26 06:19:46 +00001013 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001014
Chris Lattner76e68962009-01-26 06:19:46 +00001015 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001016 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001017
1018 // There are no more valid flags here.
1019 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001020 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001021 return true;
1022}
1023
1024/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1025/// one of the following forms:
1026///
1027/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001028/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001029/// # 42 "file" ('1' | '2')? '3' '4'?
1030///
1031void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1032 // Validate the number and convert it to an unsigned. GNU does not have a
1033 // line # limit other than it fit in 32-bits.
1034 unsigned LineNo;
1035 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001036 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001037 return;
Mike Stump11289f42009-09-09 15:08:12 +00001038
Chris Lattner76e68962009-01-26 06:19:46 +00001039 Token StrTok;
1040 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001041
Chris Lattner76e68962009-01-26 06:19:46 +00001042 bool IsFileEntry = false, IsFileExit = false;
1043 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001044 int FilenameID = -1;
1045
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001046 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1047 // string followed by eod.
1048 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001049 ; // ok
1050 else if (StrTok.isNot(tok::string_literal)) {
1051 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001052 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001053 } else if (StrTok.hasUDSuffix()) {
1054 Diag(StrTok, diag::err_invalid_string_udl);
1055 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001056 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001057 // Parse and validate the string, converting it into a unique ID.
1058 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001059 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001060 if (Literal.hadError)
1061 return DiscardUntilEndOfDirective();
1062 if (Literal.Pascal) {
1063 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1064 return DiscardUntilEndOfDirective();
1065 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001066 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001067
Chris Lattner76e68962009-01-26 06:19:46 +00001068 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001069 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001070 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001071 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001072 }
Mike Stump11289f42009-09-09 15:08:12 +00001073
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001074 // Create a line note with this information.
1075 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001076 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001077 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001078
Chris Lattner839150e2009-03-27 17:13:49 +00001079 // If the preprocessor has callbacks installed, notify them of the #line
1080 // change. This is used so that the line marker comes out in -E mode for
1081 // example.
1082 if (Callbacks) {
1083 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1084 if (IsFileEntry)
1085 Reason = PPCallbacks::EnterFile;
1086 else if (IsFileExit)
1087 Reason = PPCallbacks::ExitFile;
1088 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1089 if (IsExternCHeader)
1090 FileKind = SrcMgr::C_ExternCSystem;
1091 else if (IsSystemHeader)
1092 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001093
Chris Lattnerc745cec2010-04-14 04:28:50 +00001094 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001095 }
Chris Lattner76e68962009-01-26 06:19:46 +00001096}
1097
1098
Chris Lattner38d7fd22009-01-26 05:30:54 +00001099/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1100///
Mike Stump11289f42009-09-09 15:08:12 +00001101void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001102 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001103 // PTH doesn't emit #warning or #error directives.
1104 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001105 return CurPTHLexer->DiscardToEndOfLine();
1106
Chris Lattnerf64b3522008-03-09 01:54:53 +00001107 // Read the rest of the line raw. We do this because we don't want macros
1108 // to be expanded and we don't require that the tokens be valid preprocessing
1109 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1110 // collapse multiple consequtive white space between tokens, but this isn't
1111 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001112 SmallString<128> Message;
1113 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001114
1115 // Find the first non-whitespace character, so that we can make the
1116 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001117 StringRef Msg = Message.str().ltrim(" ");
1118
Chris Lattner100c65e2009-01-26 05:29:08 +00001119 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001120 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001121 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001122 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001123}
1124
1125/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1126///
1127void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1128 // Yes, this directive is an extension.
1129 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001130
Chris Lattnerf64b3522008-03-09 01:54:53 +00001131 // Read the string argument.
1132 Token StrTok;
1133 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001134
Chris Lattnerf64b3522008-03-09 01:54:53 +00001135 // If the token kind isn't a string, it's a malformed directive.
1136 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001137 StrTok.isNot(tok::wide_string_literal)) {
1138 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001139 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001140 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001141 return;
1142 }
Mike Stump11289f42009-09-09 15:08:12 +00001143
Richard Smithd67aea22012-03-06 03:21:47 +00001144 if (StrTok.hasUDSuffix()) {
1145 Diag(StrTok, diag::err_invalid_string_udl);
1146 return DiscardUntilEndOfDirective();
1147 }
1148
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001149 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001150 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001151
Douglas Gregordc970f02010-03-16 22:30:13 +00001152 if (Callbacks) {
1153 bool Invalid = false;
1154 std::string Str = getSpelling(StrTok, &Invalid);
1155 if (!Invalid)
1156 Callbacks->Ident(Tok.getLocation(), Str);
1157 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001158}
1159
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001160/// \brief Handle a #public directive.
1161void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001162 Token MacroNameTok;
1163 ReadMacroName(MacroNameTok, 2);
1164
1165 // Error reading macro name? If so, diagnostic already issued.
1166 if (MacroNameTok.is(tok::eod))
1167 return;
1168
Douglas Gregor663b48f2012-01-03 19:48:16 +00001169 // Check to see if this is the last token on the #__public_macro line.
1170 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001171
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001172 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001173 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001174 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001175
1176 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001177 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001178 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001179 return;
1180 }
1181
1182 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001183 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1184 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001185}
1186
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001187/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001188void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1189 Token MacroNameTok;
1190 ReadMacroName(MacroNameTok, 2);
1191
1192 // Error reading macro name? If so, diagnostic already issued.
1193 if (MacroNameTok.is(tok::eod))
1194 return;
1195
Douglas Gregor663b48f2012-01-03 19:48:16 +00001196 // Check to see if this is the last token on the #__private_macro line.
1197 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001198
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001199 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001200 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001201 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001202
1203 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001204 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001205 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001206 return;
1207 }
1208
1209 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001210 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1211 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001212}
1213
Chris Lattnerf64b3522008-03-09 01:54:53 +00001214//===----------------------------------------------------------------------===//
1215// Preprocessor Include Directive Handling.
1216//===----------------------------------------------------------------------===//
1217
1218/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001219/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001220/// true if the input filename was in <>'s or false if it were in ""'s. The
1221/// caller is expected to provide a buffer that is large enough to hold the
1222/// spelling of the filename, but is also expected to handle the case when
1223/// this method decides to use a different buffer.
1224bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001225 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001226 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001227 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001228
Chris Lattnerf64b3522008-03-09 01:54:53 +00001229 // Make sure the filename is <x> or "x".
1230 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001231 if (Buffer[0] == '<') {
1232 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001233 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001234 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001235 return true;
1236 }
1237 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001238 } else if (Buffer[0] == '"') {
1239 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001240 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001241 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001242 return true;
1243 }
1244 isAngled = false;
1245 } else {
1246 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001247 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001248 return true;
1249 }
Mike Stump11289f42009-09-09 15:08:12 +00001250
Chris Lattnerf64b3522008-03-09 01:54:53 +00001251 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001252 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001253 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001254 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001255 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001256 }
Mike Stump11289f42009-09-09 15:08:12 +00001257
Chris Lattnerf64b3522008-03-09 01:54:53 +00001258 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001259 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001260 return isAngled;
1261}
1262
James Dennettf6333ac2012-06-22 05:46:07 +00001263/// \brief Handle cases where the \#include name is expanded from a macro
1264/// as multiple tokens, which need to be glued together.
1265///
1266/// This occurs for code like:
1267/// \code
1268/// \#define FOO <a/b.h>
1269/// \#include FOO
1270/// \endcode
Chris Lattnerf64b3522008-03-09 01:54:53 +00001271/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1272///
1273/// This code concatenates and consumes tokens up to the '>' token. It returns
1274/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001275/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001276bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001277 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001278 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001279 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001280
John Thompsonb5353522009-10-30 13:49:06 +00001281 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001282 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001283 End = CurTok.getLocation();
1284
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001285 // FIXME: Provide code completion for #includes.
1286 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001287 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001288 Lex(CurTok);
1289 continue;
1290 }
1291
Chris Lattnerf64b3522008-03-09 01:54:53 +00001292 // Append the spelling of this token to the buffer. If there was a space
1293 // before it, add it now.
1294 if (CurTok.hasLeadingSpace())
1295 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001296
Chris Lattnerf64b3522008-03-09 01:54:53 +00001297 // Get the spelling of the token, directly into FilenameBuffer if possible.
1298 unsigned PreAppendSize = FilenameBuffer.size();
1299 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001300
Chris Lattnerf64b3522008-03-09 01:54:53 +00001301 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001302 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001303
Chris Lattnerf64b3522008-03-09 01:54:53 +00001304 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1305 if (BufPtr != &FilenameBuffer[PreAppendSize])
1306 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001307
Chris Lattnerf64b3522008-03-09 01:54:53 +00001308 // Resize FilenameBuffer to the correct size.
1309 if (CurTok.getLength() != ActualLen)
1310 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001311
Chris Lattnerf64b3522008-03-09 01:54:53 +00001312 // If we found the '>' marker, return success.
1313 if (CurTok.is(tok::greater))
1314 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001315
John Thompsonb5353522009-10-30 13:49:06 +00001316 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001317 }
1318
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001319 // If we hit the eod marker, emit an error and return true so that the caller
1320 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001321 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001322 return true;
1323}
1324
James Dennettf6333ac2012-06-22 05:46:07 +00001325/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1326/// the file to be included from the lexer, then include it! This is a common
1327/// routine with functionality shared between \#include, \#include_next and
1328/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001329/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001330void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1331 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001332 const DirectoryLookup *LookupFrom,
1333 bool isImport) {
1334
1335 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001336 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001337
Chris Lattnerf64b3522008-03-09 01:54:53 +00001338 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001339 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001340 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001341 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001342 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001343
Chris Lattnerf64b3522008-03-09 01:54:53 +00001344 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001345 case tok::eod:
1346 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001347 return;
Mike Stump11289f42009-09-09 15:08:12 +00001348
Chris Lattnerf64b3522008-03-09 01:54:53 +00001349 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001350 case tok::string_literal:
1351 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001352 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001353 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001354 break;
Mike Stump11289f42009-09-09 15:08:12 +00001355
Chris Lattnerf64b3522008-03-09 01:54:53 +00001356 case tok::less:
1357 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1358 // case, glue the tokens together into FilenameBuffer and interpret those.
1359 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001360 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001361 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001362 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001363 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001364 break;
1365 default:
1366 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1367 DiscardUntilEndOfDirective();
1368 return;
1369 }
Mike Stump11289f42009-09-09 15:08:12 +00001370
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001371 CharSourceRange FilenameRange
1372 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001373 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001374 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001375 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001376 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1377 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001378 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001379 DiscardUntilEndOfDirective();
1380 return;
1381 }
Mike Stump11289f42009-09-09 15:08:12 +00001382
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001383 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001384 // we allow macros that expand to nothing after the filename, because this
1385 // falls into the category of "#include pp-tokens new-line" specified in
1386 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001387 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001388
1389 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001390 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1391 Diag(FilenameTok, diag::err_pp_include_too_deep);
1392 return;
1393 }
Mike Stump11289f42009-09-09 15:08:12 +00001394
John McCall32f5fe12011-09-30 05:12:12 +00001395 // Complain about attempts to #include files in an audit pragma.
1396 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1397 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1398 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1399
1400 // Immediately leave the pragma.
1401 PragmaARCCFCodeAuditedLoc = SourceLocation();
1402 }
1403
Aaron Ballman611306e2012-03-02 22:51:54 +00001404 if (HeaderInfo.HasIncludeAliasMap()) {
1405 // Map the filename with the brackets still attached. If the name doesn't
1406 // map to anything, fall back on the filename we've already gotten the
1407 // spelling for.
1408 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1409 if (!NewName.empty())
1410 Filename = NewName;
1411 }
1412
Chris Lattnerf64b3522008-03-09 01:54:53 +00001413 // Search include directories.
1414 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001415 SmallString<1024> SearchPath;
1416 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001417 // We get the raw path only if we have 'Callbacks' to which we later pass
1418 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001419 ModuleMap::KnownHeader SuggestedModule;
1420 SourceLocation FilenameLoc = FilenameTok.getLocation();
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001421 const FileEntry *File = LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001422 FilenameLoc, Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001423 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001424 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001425
Douglas Gregor11729f02011-11-30 18:12:06 +00001426 if (Callbacks) {
1427 if (!File) {
1428 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001429 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001430 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1431 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1432 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001433 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001434 HeaderInfo.AddSearchPath(DL, isAngled);
1435
1436 // Try the lookup again, skipping the cache.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001437 File = LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, CurDir,
1438 0, 0, getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001439 /*SkipCache*/true);
1440 }
1441 }
1442 }
1443
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001444 if (!SuggestedModule) {
1445 // Notify the callback object that we've seen an inclusion directive.
1446 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1447 FilenameRange, File,
1448 SearchPath, RelativePath,
1449 /*ImportedModule=*/0);
1450 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001451 }
1452
1453 if (File == 0) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001454 if (!SuppressIncludeNotFoundError) {
1455 // If the file could not be located and it was included via angle
1456 // brackets, we can attempt a lookup as though it were a quoted path to
1457 // provide the user with a possible fixit.
1458 if (isAngled) {
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001459 File = LookupFile(FilenameLoc, Filename, false, LookupFrom, CurDir,
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001460 Callbacks ? &SearchPath : 0,
1461 Callbacks ? &RelativePath : 0,
1462 getLangOpts().Modules ? &SuggestedModule : 0);
1463 if (File) {
1464 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1465 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1466 Filename <<
1467 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1468 }
1469 }
1470 // If the file is still not found, just go with the vanilla diagnostic
1471 if (!File)
1472 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1473 }
1474 if (!File)
1475 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001476 }
1477
Douglas Gregor97eec242011-09-15 22:00:41 +00001478 // If we are supposed to import a module rather than including the header,
1479 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001480 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001481 // Compute the module access path corresponding to this module.
1482 // FIXME: Should we have a second loadModule() overload to avoid this
1483 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001484 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001485 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001486 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1487 FilenameTok.getLocation()));
1488 std::reverse(Path.begin(), Path.end());
1489
Douglas Gregor41e115a2011-11-30 18:02:36 +00001490 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001491 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001492 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1493 if (I)
1494 PathString += '.';
1495 PathString += Path[I].first->getName();
1496 }
1497 int IncludeKind = 0;
1498
1499 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1500 case tok::pp_include:
1501 IncludeKind = 0;
1502 break;
1503
1504 case tok::pp_import:
1505 IncludeKind = 1;
1506 break;
1507
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001508 case tok::pp_include_next:
1509 IncludeKind = 2;
1510 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001511
1512 case tok::pp___include_macros:
1513 IncludeKind = 3;
1514 break;
1515
1516 default:
1517 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001518 }
1519
Douglas Gregor2537a362011-12-08 17:01:29 +00001520 // Determine whether we are actually building the module that this
1521 // include directive maps to.
1522 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001523 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001524
David Blaikiebbafb8a2012-03-11 07:00:24 +00001525 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001526 // If we're not building the imported module, warn that we're going
1527 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001528 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001529 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1530 /*IsTokenRange=*/false);
1531 Diag(HashLoc, diag::warn_auto_module_import)
1532 << IncludeKind << PathString
1533 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001534 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001535 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001536
Douglas Gregor71944202011-11-30 00:36:36 +00001537 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001538 // If this was an #__include_macros directive, only make macros visible.
1539 Module::NameVisibilityKind Visibility
1540 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001541 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001542 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1543 /*IsIncludeDirective=*/true);
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001544 assert((Imported == 0 || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001545 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001546
1547 if (!Imported && hadModuleLoaderFatalFailure()) {
1548 // With a fatal failure in the module loader, we abort parsing.
1549 Token &Result = IncludeTok;
1550 if (CurLexer) {
1551 Result.startToken();
1552 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1553 CurLexer->cutOffLexing();
1554 } else {
1555 assert(CurPTHLexer && "#include but no current lexer set!");
1556 CurPTHLexer->getEOF(Result);
1557 }
1558 return;
1559 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001560
1561 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001562 if (!BuildingImportedModule && Imported) {
1563 if (Callbacks) {
1564 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1565 FilenameRange, File,
1566 SearchPath, RelativePath, Imported);
1567 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001568 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001569 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001570
1571 // If we failed to find a submodule that we expected to find, we can
1572 // continue. Otherwise, there's an error in the included file, so we
1573 // don't want to include it.
1574 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1575 return;
1576 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001577 }
1578
1579 if (Callbacks && SuggestedModule) {
1580 // We didn't notify the callback object that we've seen an inclusion
1581 // directive before. Now that we are parsing the include normally and not
1582 // turning it to a module import, notify the callback object.
1583 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1584 FilenameRange, File,
1585 SearchPath, RelativePath,
1586 /*ImportedModule=*/0);
Douglas Gregor97eec242011-09-15 22:00:41 +00001587 }
1588
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001589 // The #included file will be considered to be a system header if either it is
1590 // in a system include directory, or if the #includer is a system include
1591 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001592 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001593 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001594 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001595
Chris Lattner72286d62010-04-19 20:44:31 +00001596 // Ask HeaderInfo if we should enter this #include file. If not, #including
1597 // this file will have no effect.
1598 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001599 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001600 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001601 return;
1602 }
1603
Chris Lattnerf64b3522008-03-09 01:54:53 +00001604 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001605 SourceLocation IncludePos = End;
1606 // If the filename string was the result of macro expansions, set the include
1607 // position on the file where it will be included and after the expansions.
1608 if (IncludePos.isMacroID())
1609 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1610 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001611 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001612
1613 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001614 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001615}
1616
James Dennettf6333ac2012-06-22 05:46:07 +00001617/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001618///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001619void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1620 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001621 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001622
Chris Lattnerf64b3522008-03-09 01:54:53 +00001623 // #include_next is like #include, except that we start searching after
1624 // the current found directory. If we can't do this, issue a
1625 // diagnostic.
1626 const DirectoryLookup *Lookup = CurDirLookup;
1627 if (isInPrimaryFile()) {
1628 Lookup = 0;
1629 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1630 } else if (Lookup == 0) {
1631 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1632 } else {
1633 // Start looking up in the next directory.
1634 ++Lookup;
1635 }
Mike Stump11289f42009-09-09 15:08:12 +00001636
Douglas Gregor796d76a2010-10-20 22:00:55 +00001637 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001638}
1639
James Dennettf6333ac2012-06-22 05:46:07 +00001640/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001641void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1642 // The Microsoft #import directive takes a type library and generates header
1643 // files from it, and includes those. This is beyond the scope of what clang
1644 // does, so we ignore it and error out. However, #import can optionally have
1645 // trailing attributes that span multiple lines. We're going to eat those
1646 // so we can continue processing from there.
1647 Diag(Tok, diag::err_pp_import_directive_ms );
1648
1649 // Read tokens until we get to the end of the directive. Note that the
1650 // directive can be split over multiple lines using the backslash character.
1651 DiscardUntilEndOfDirective();
1652}
1653
James Dennettf6333ac2012-06-22 05:46:07 +00001654/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001655///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001656void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1657 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001658 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1659 if (LangOpts.MicrosoftMode)
1660 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001661 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001662 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001663 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001664}
1665
Chris Lattner58a1eb02009-04-08 18:46:40 +00001666/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1667/// pseudo directive in the predefines buffer. This handles it by sucking all
1668/// tokens through the preprocessor and discarding them (only keeping the side
1669/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001670void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1671 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001672 // This directive should only occur in the predefines buffer. If not, emit an
1673 // error and reject it.
1674 SourceLocation Loc = IncludeMacrosTok.getLocation();
1675 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1676 Diag(IncludeMacrosTok.getLocation(),
1677 diag::pp_include_macros_out_of_predefines);
1678 DiscardUntilEndOfDirective();
1679 return;
1680 }
Mike Stump11289f42009-09-09 15:08:12 +00001681
Chris Lattnere01d82b2009-04-08 20:53:24 +00001682 // Treat this as a normal #include for checking purposes. If this is
1683 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001684 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001685
Chris Lattnere01d82b2009-04-08 20:53:24 +00001686 Token TmpTok;
1687 do {
1688 Lex(TmpTok);
1689 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1690 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001691}
1692
Chris Lattnerf64b3522008-03-09 01:54:53 +00001693//===----------------------------------------------------------------------===//
1694// Preprocessor Macro Directive Handling.
1695//===----------------------------------------------------------------------===//
1696
1697/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1698/// definition has just been read. Lex the rest of the arguments and the
1699/// closing ), updating MI with what we learn. Return true if an error occurs
1700/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001701bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001702 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001703
Chris Lattnerf64b3522008-03-09 01:54:53 +00001704 while (1) {
1705 LexUnexpandedToken(Tok);
1706 switch (Tok.getKind()) {
1707 case tok::r_paren:
1708 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001709 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001710 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001711 // Otherwise we have #define FOO(A,)
1712 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1713 return true;
1714 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001715 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001716 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001717 diag::warn_cxx98_compat_variadic_macro :
1718 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001719
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001720 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1721 if (LangOpts.OpenCL) {
1722 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1723 return true;
1724 }
1725
Chris Lattnerf64b3522008-03-09 01:54:53 +00001726 // Lex the token after the identifier.
1727 LexUnexpandedToken(Tok);
1728 if (Tok.isNot(tok::r_paren)) {
1729 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1730 return true;
1731 }
1732 // Add the __VA_ARGS__ identifier as an argument.
1733 Arguments.push_back(Ident__VA_ARGS__);
1734 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001735 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001736 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001737 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001738 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1739 return true;
1740 default:
1741 // Handle keywords and identifiers here to accept things like
1742 // #define Foo(for) for.
1743 IdentifierInfo *II = Tok.getIdentifierInfo();
1744 if (II == 0) {
1745 // #define X(1
1746 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1747 return true;
1748 }
1749
1750 // If this is already used as an argument, it is used multiple times (e.g.
1751 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001752 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001753 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001754 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001755 return true;
1756 }
Mike Stump11289f42009-09-09 15:08:12 +00001757
Chris Lattnerf64b3522008-03-09 01:54:53 +00001758 // Add the argument to the macro info.
1759 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001760
Chris Lattnerf64b3522008-03-09 01:54:53 +00001761 // Lex the token after the identifier.
1762 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001763
Chris Lattnerf64b3522008-03-09 01:54:53 +00001764 switch (Tok.getKind()) {
1765 default: // #define X(A B
1766 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1767 return true;
1768 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001769 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001770 return false;
1771 case tok::comma: // #define X(A,
1772 break;
1773 case tok::ellipsis: // #define X(A... -> GCC extension
1774 // Diagnose extension.
1775 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001776
Chris Lattnerf64b3522008-03-09 01:54:53 +00001777 // Lex the token after the identifier.
1778 LexUnexpandedToken(Tok);
1779 if (Tok.isNot(tok::r_paren)) {
1780 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1781 return true;
1782 }
Mike Stump11289f42009-09-09 15:08:12 +00001783
Chris Lattnerf64b3522008-03-09 01:54:53 +00001784 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001785 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001786 return false;
1787 }
1788 }
1789 }
1790}
1791
James Dennettf6333ac2012-06-22 05:46:07 +00001792/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001793/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001794void Preprocessor::HandleDefineDirective(Token &DefineTok,
1795 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001796 ++NumDefined;
1797
1798 Token MacroNameTok;
1799 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001800
Chris Lattnerf64b3522008-03-09 01:54:53 +00001801 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001802 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001803 return;
1804
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001805 Token LastTok = MacroNameTok;
1806
Chris Lattnerf64b3522008-03-09 01:54:53 +00001807 // If we are supposed to keep comments in #defines, reenable comment saving
1808 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001809 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001810
Chris Lattnerf64b3522008-03-09 01:54:53 +00001811 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001812 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001813
Chris Lattnerf64b3522008-03-09 01:54:53 +00001814 Token Tok;
1815 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001816
Chris Lattnerf64b3522008-03-09 01:54:53 +00001817 // If this is a function-like macro definition, parse the argument list,
1818 // marking each of the identifiers as being used as macro arguments. Also,
1819 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001820 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001821 if (ImmediatelyAfterHeaderGuard) {
1822 // Save this macro information since it may part of a header guard.
1823 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
1824 MacroNameTok.getLocation());
1825 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001826 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001827 } else if (Tok.hasLeadingSpace()) {
1828 // This is a normal token with leading space. Clear the leading space
1829 // marker on the first token to get proper expansion.
1830 Tok.clearFlag(Token::LeadingSpace);
1831 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001832 // This is a function-like macro definition. Read the argument list.
1833 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001834 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001835 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001836 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001837 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001838 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001839 DiscardUntilEndOfDirective();
1840 return;
1841 }
1842
Chris Lattner249c38b2009-04-19 18:26:34 +00001843 // If this is a definition of a variadic C99 function-like macro, not using
1844 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattner249c38b2009-04-19 18:26:34 +00001846 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1847 // This gets unpoisoned where it is allowed.
1848 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1849 if (MI->isC99Varargs())
1850 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001851
Chris Lattnerf64b3522008-03-09 01:54:53 +00001852 // Read the first token after the arg list for down below.
1853 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001854 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001855 // C99 requires whitespace between the macro definition and the body. Emit
1856 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001857 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001858 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001859 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1860 // first character of a replacement list is not a character required by
1861 // subclause 5.2.1, then there shall be white-space separation between the
1862 // identifier and the replacement list.". 5.2.1 lists this set:
1863 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1864 // is irrelevant here.
1865 bool isInvalid = false;
1866 if (Tok.is(tok::at)) // @ is not in the list above.
1867 isInvalid = true;
1868 else if (Tok.is(tok::unknown)) {
1869 // If we have an unknown token, it is something strange like "`". Since
1870 // all of valid characters would have lexed into a single character
1871 // token of some sort, we know this is not a valid case.
1872 isInvalid = true;
1873 }
1874 if (isInvalid)
1875 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1876 else
1877 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001878 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001879
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001880 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001881 LastTok = Tok;
1882
Chris Lattnerf64b3522008-03-09 01:54:53 +00001883 // Read the rest of the macro body.
1884 if (MI->isObjectLike()) {
1885 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001886 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001887 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001888 MI->AddTokenToBody(Tok);
1889 // Get the next token of the macro.
1890 LexUnexpandedToken(Tok);
1891 }
Mike Stump11289f42009-09-09 15:08:12 +00001892
Chris Lattnerf64b3522008-03-09 01:54:53 +00001893 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001894 // Otherwise, read the body of a function-like macro. While we are at it,
1895 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1896 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001897 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001898 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001899
Eli Friedman14d3c792012-11-14 02:18:46 +00001900 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001901 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001902
Chris Lattnerf64b3522008-03-09 01:54:53 +00001903 // Get the next token of the macro.
1904 LexUnexpandedToken(Tok);
1905 continue;
1906 }
Mike Stump11289f42009-09-09 15:08:12 +00001907
Richard Smith701a3522013-07-09 01:00:29 +00001908 // If we're in -traditional mode, then we should ignore stringification
1909 // and token pasting. Mark the tokens as unknown so as not to confuse
1910 // things.
1911 if (getLangOpts().TraditionalCPP) {
1912 Tok.setKind(tok::unknown);
1913 MI->AddTokenToBody(Tok);
1914
1915 // Get the next token of the macro.
1916 LexUnexpandedToken(Tok);
1917 continue;
1918 }
1919
Eli Friedman14d3c792012-11-14 02:18:46 +00001920 if (Tok.is(tok::hashhash)) {
1921
1922 // If we see token pasting, check if it looks like the gcc comma
1923 // pasting extension. We'll use this information to suppress
1924 // diagnostics later on.
1925
1926 // Get the next token of the macro.
1927 LexUnexpandedToken(Tok);
1928
1929 if (Tok.is(tok::eod)) {
1930 MI->AddTokenToBody(LastTok);
1931 break;
1932 }
1933
1934 unsigned NumTokens = MI->getNumTokens();
1935 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1936 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1937 MI->setHasCommaPasting();
1938
1939 // Things look ok, add the '##' and param name tokens to the macro.
1940 MI->AddTokenToBody(LastTok);
1941 MI->AddTokenToBody(Tok);
1942 LastTok = Tok;
1943
1944 // Get the next token of the macro.
1945 LexUnexpandedToken(Tok);
1946 continue;
1947 }
1948
Chris Lattnerf64b3522008-03-09 01:54:53 +00001949 // Get the next token of the macro.
1950 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001951
Chris Lattner83bd8282009-05-25 17:16:10 +00001952 // Check for a valid macro arg identifier.
1953 if (Tok.getIdentifierInfo() == 0 ||
1954 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1955
1956 // If this is assembler-with-cpp mode, we accept random gibberish after
1957 // the '#' because '#' is often a comment character. However, change
1958 // the kind of the token to tok::unknown so that the preprocessor isn't
1959 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001960 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001961 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00001962 MI->AddTokenToBody(LastTok);
1963 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00001964 } else {
1965 Diag(Tok, diag::err_pp_stringize_not_parameter);
1966 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001967
Chris Lattner83bd8282009-05-25 17:16:10 +00001968 // Disable __VA_ARGS__ again.
1969 Ident__VA_ARGS__->setIsPoisoned(true);
1970 return;
1971 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001972 }
Mike Stump11289f42009-09-09 15:08:12 +00001973
Chris Lattner83bd8282009-05-25 17:16:10 +00001974 // Things look ok, add the '#' and param name tokens to the macro.
1975 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001976 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001977 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001978
Chris Lattnerf64b3522008-03-09 01:54:53 +00001979 // Get the next token of the macro.
1980 LexUnexpandedToken(Tok);
1981 }
1982 }
Mike Stump11289f42009-09-09 15:08:12 +00001983
1984
Chris Lattnerf64b3522008-03-09 01:54:53 +00001985 // Disable __VA_ARGS__ again.
1986 Ident__VA_ARGS__->setIsPoisoned(true);
1987
Chris Lattner57540c52011-04-15 05:22:18 +00001988 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001989 // replacement list.
1990 unsigned NumTokens = MI->getNumTokens();
1991 if (NumTokens != 0) {
1992 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1993 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001994 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001995 return;
1996 }
1997 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1998 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001999 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002000 return;
2001 }
2002 }
Mike Stump11289f42009-09-09 15:08:12 +00002003
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002004 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002005
Chris Lattnerf64b3522008-03-09 01:54:53 +00002006 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002007 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002008 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00002009 // It is very common for system headers to have tons of macro redefinitions
2010 // and for warnings to be disabled in system headers. If this is the case,
2011 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002012 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002013 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002014 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002015 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002016
Richard Smith7b242542013-03-06 00:46:00 +00002017 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2018 // C++ [cpp.predefined]p4, but allow it as an extension.
2019 if (OtherMI->isBuiltinMacro())
2020 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002021 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002022 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002023 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002024 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002025 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2026 << MacroNameTok.getIdentifierInfo();
2027 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2028 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002029 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002030 if (OtherMI->isWarnIfUnused())
2031 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002032 }
Mike Stump11289f42009-09-09 15:08:12 +00002033
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002034 DefMacroDirective *MD =
2035 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002036
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002037 assert(!MI->isUsed());
2038 // If we need warning for not using the macro, add its location in the
2039 // warn-because-unused-macro set. If it gets used it will be removed from set.
2040 if (isInPrimaryFile() && // don't warn for include'd macros.
2041 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00002042 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002043 MI->setIsWarnIfUnused(true);
2044 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2045 }
2046
Chris Lattner928e9092009-04-12 01:39:54 +00002047 // If the callbacks want to know, tell them about the macro definition.
2048 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002049 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002050}
2051
James Dennettf6333ac2012-06-22 05:46:07 +00002052/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002053///
2054void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2055 ++NumUndefined;
2056
2057 Token MacroNameTok;
2058 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00002059
Chris Lattnerf64b3522008-03-09 01:54:53 +00002060 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002061 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002062 return;
Mike Stump11289f42009-09-09 15:08:12 +00002063
Chris Lattnerf64b3522008-03-09 01:54:53 +00002064 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002065 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002066
Chris Lattnerf64b3522008-03-09 01:54:53 +00002067 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002068 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002069 const MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Mike Stump11289f42009-09-09 15:08:12 +00002070
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002071 // If the callbacks want to know, tell them about the macro #undef.
2072 // Note: no matter if the macro was defined or not.
2073 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002074 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002075
Chris Lattnerf64b3522008-03-09 01:54:53 +00002076 // If the macro is not defined, this is a noop undef, just return.
2077 if (MI == 0) return;
2078
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002079 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002080 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002081
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002082 if (MI->isWarnIfUnused())
2083 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2084
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002085 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2086 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002087}
2088
2089
2090//===----------------------------------------------------------------------===//
2091// Preprocessor Conditional Directive Handling.
2092//===----------------------------------------------------------------------===//
2093
James Dennettf6333ac2012-06-22 05:46:07 +00002094/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2095/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2096/// true if any tokens have been returned or pp-directives activated before this
2097/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002098///
2099void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2100 bool ReadAnyTokensBeforeDirective) {
2101 ++NumIf;
2102 Token DirectiveTok = Result;
2103
2104 Token MacroNameTok;
2105 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002106
Chris Lattnerf64b3522008-03-09 01:54:53 +00002107 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002108 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002109 // Skip code until we get to #endif. This helps with recovery by not
2110 // emitting an error when the #endif is reached.
2111 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2112 /*Foundnonskip*/false, /*FoundElse*/false);
2113 return;
2114 }
Mike Stump11289f42009-09-09 15:08:12 +00002115
Chris Lattnerf64b3522008-03-09 01:54:53 +00002116 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002117 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002118
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002119 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002120 MacroDirective *MD = getMacroDirective(MII);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002121 MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002122
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002123 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002124 // If the start of a top-level #ifdef and if the macro is not defined,
2125 // inform MIOpt that this might be the start of a proper include guard.
2126 // Otherwise it is some other form of unknown conditional which we can't
2127 // handle.
2128 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002129 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002130 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002131 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002132 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002133 }
2134
Chris Lattnerf64b3522008-03-09 01:54:53 +00002135 // If there is a macro, process it.
2136 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002137 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002138
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002139 if (Callbacks) {
2140 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002141 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002142 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002143 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002144 }
2145
Chris Lattnerf64b3522008-03-09 01:54:53 +00002146 // Should we include the stuff contained by this directive?
2147 if (!MI == isIfndef) {
2148 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002149 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2150 /*wasskip*/false, /*foundnonskip*/true,
2151 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002152 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002153 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002154 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002155 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002156 /*FoundElse*/false);
2157 }
2158}
2159
James Dennettf6333ac2012-06-22 05:46:07 +00002160/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002161///
2162void Preprocessor::HandleIfDirective(Token &IfToken,
2163 bool ReadAnyTokensBeforeDirective) {
2164 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002165
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002166 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002167 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002168 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2169 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2170 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002171
2172 // If this condition is equivalent to #ifndef X, and if this is the first
2173 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002174 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002175 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002176 // FIXME: Pass in the location of the macro name, not the 'if' token.
2177 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002178 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002179 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002180 }
2181
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002182 if (Callbacks)
2183 Callbacks->If(IfToken.getLocation(),
2184 SourceRange(ConditionalBegin, ConditionalEnd));
2185
Chris Lattnerf64b3522008-03-09 01:54:53 +00002186 // Should we include the stuff contained by this directive?
2187 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002188 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002189 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002190 /*foundnonskip*/true, /*foundelse*/false);
2191 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002192 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002193 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002194 /*FoundElse*/false);
2195 }
2196}
2197
James Dennettf6333ac2012-06-22 05:46:07 +00002198/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002199///
2200void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2201 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002202
Chris Lattnerf64b3522008-03-09 01:54:53 +00002203 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002204 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002205
Chris Lattnerf64b3522008-03-09 01:54:53 +00002206 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002207 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002208 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002209 Diag(EndifToken, diag::err_pp_endif_without_if);
2210 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002211 }
Mike Stump11289f42009-09-09 15:08:12 +00002212
Chris Lattnerf64b3522008-03-09 01:54:53 +00002213 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002214 if (CurPPLexer->getConditionalStackDepth() == 0)
2215 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002216
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002217 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002218 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002219
2220 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002221 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002222}
2223
James Dennettf6333ac2012-06-22 05:46:07 +00002224/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002225///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002226void Preprocessor::HandleElseDirective(Token &Result) {
2227 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002228
Chris Lattnerf64b3522008-03-09 01:54:53 +00002229 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002230 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002231
Chris Lattnerf64b3522008-03-09 01:54:53 +00002232 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002233 if (CurPPLexer->popConditionalLevel(CI)) {
2234 Diag(Result, diag::pp_err_else_without_if);
2235 return;
2236 }
Mike Stump11289f42009-09-09 15:08:12 +00002237
Chris Lattnerf64b3522008-03-09 01:54:53 +00002238 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002239 if (CurPPLexer->getConditionalStackDepth() == 0)
2240 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002241
2242 // If this is a #else with a #else before it, report the error.
2243 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002244
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002245 if (Callbacks)
2246 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2247
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002248 // Finally, skip the rest of the contents of this block.
2249 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002250 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002251}
2252
James Dennettf6333ac2012-06-22 05:46:07 +00002253/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002254///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002255void Preprocessor::HandleElifDirective(Token &ElifToken) {
2256 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002257
Chris Lattnerf64b3522008-03-09 01:54:53 +00002258 // #elif directive in a non-skipping conditional... start skipping.
2259 // We don't care what the condition is, because we will always skip it (since
2260 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002261 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002262 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002263 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002264
2265 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002266 if (CurPPLexer->popConditionalLevel(CI)) {
2267 Diag(ElifToken, diag::pp_err_elif_without_if);
2268 return;
2269 }
Mike Stump11289f42009-09-09 15:08:12 +00002270
Chris Lattnerf64b3522008-03-09 01:54:53 +00002271 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002272 if (CurPPLexer->getConditionalStackDepth() == 0)
2273 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002274
Chris Lattnerf64b3522008-03-09 01:54:53 +00002275 // If this is a #elif with a #else before it, report the error.
2276 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002277
2278 if (Callbacks)
2279 Callbacks->Elif(ElifToken.getLocation(),
2280 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002281
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002282 // Finally, skip the rest of the contents of this block.
2283 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002284 /*FoundElse*/CI.FoundElse,
2285 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002286}