blob: ef0cbd656f9ce411be2d4f8c1a059a8281400597 [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"
Daniel Jasper07e6c402013-08-05 20:26:17 +000020#include "clang/Lex/HeaderSearchOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/LexDiagnostic.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/ModuleLoader.h"
25#include "clang/Lex/Pragma.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000026#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000027#include "llvm/Support/ErrorHandling.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000028#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000029using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Utility Methods for Preprocessor Directive Handling.
33//===----------------------------------------------------------------------===//
34
Chris Lattnerc0a585d2010-08-17 15:55:45 +000035MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000036 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000037
Ted Kremenekc8456f82010-10-19 22:15:20 +000038 if (MICache) {
39 MIChain = MICache;
40 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000041 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000042 else {
43 MIChain = BP.Allocate<MacroInfoChain>();
44 }
45
46 MIChain->Next = MIChainHead;
47 MIChain->Prev = 0;
48 if (MIChainHead)
49 MIChainHead->Prev = MIChain;
50 MIChainHead = MIChain;
51
52 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000053}
54
55MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
56 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000057 new (MI) MacroInfo(L);
58 return MI;
59}
60
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000061MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
62 unsigned SubModuleID) {
63 LLVM_STATIC_ASSERT(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
64 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000065 DeserializedMacroInfoChain *MIChain =
66 BP.Allocate<DeserializedMacroInfoChain>();
67 MIChain->Next = DeserialMIChainHead;
68 DeserialMIChainHead = MIChain;
69
70 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000071 new (MI) MacroInfo(L);
72 MI->FromASTFile = true;
73 MI->setOwningModuleID(SubModuleID);
74 return MI;
75}
76
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000077DefMacroDirective *
78Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc,
79 bool isImported) {
80 DefMacroDirective *MD = BP.Allocate<DefMacroDirective>();
81 new (MD) DefMacroDirective(MI, Loc, isImported);
82 return MD;
83}
84
85UndefMacroDirective *
86Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
87 UndefMacroDirective *MD = BP.Allocate<UndefMacroDirective>();
88 new (MD) UndefMacroDirective(UndefLoc);
89 return MD;
90}
91
92VisibilityMacroDirective *
93Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
94 bool isPublic) {
95 VisibilityMacroDirective *MD = BP.Allocate<VisibilityMacroDirective>();
96 new (MD) VisibilityMacroDirective(Loc, isPublic);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000097 return MD;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000098}
99
James Dennettf6333ac2012-06-22 05:46:07 +0000100/// \brief Release the specified MacroInfo to be reused for allocating
101/// new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +0000102void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +0000103 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
104 if (MacroInfoChain *Prev = MIChain->Prev) {
105 MacroInfoChain *Next = MIChain->Next;
106 Prev->Next = Next;
107 if (Next)
108 Next->Prev = Prev;
109 }
110 else {
111 assert(MIChainHead == MIChain);
112 MIChainHead = MIChain->Next;
113 MIChainHead->Prev = 0;
114 }
115 MIChain->Next = MICache;
116 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +0000117
Ted Kremenekc8456f82010-10-19 22:15:20 +0000118 MI->Destroy();
119}
Chris Lattner666f7a42009-02-20 22:19:20 +0000120
James Dennettf6333ac2012-06-22 05:46:07 +0000121/// \brief Read and discard all tokens remaining on the current line until
122/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000123void Preprocessor::DiscardUntilEndOfDirective() {
124 Token Tmp;
125 do {
126 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000127 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000128 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000129}
130
James Dennettf6333ac2012-06-22 05:46:07 +0000131/// \brief Lex and validate a macro name, which occurs after a
132/// \#define or \#undef.
133///
134/// This sets the token kind to eod and discards the rest
135/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
136/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
137/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000138void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
139 // Read the token, don't allow macro expansion on it.
140 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Douglas Gregor12785102010-08-24 20:21:13 +0000142 if (MacroNameTok.is(tok::code_completion)) {
143 if (CodeComplete)
144 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000145 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000146 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000147 }
148
Chris Lattnerf64b3522008-03-09 01:54:53 +0000149 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000150 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000151 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
152 return;
153 }
Mike Stump11289f42009-09-09 15:08:12 +0000154
Chris Lattnerf64b3522008-03-09 01:54:53 +0000155 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
156 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000157 bool Invalid = false;
158 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
159 if (Invalid)
160 return;
Nico Weber2e686202012-02-29 22:54:43 +0000161
Chris Lattner77c76ae2008-12-13 20:12:40 +0000162 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000163
164 // Allow #defining |and| and friends in microsoft mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000165 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weber2e686202012-02-29 22:54:43 +0000166 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
167 return;
168 }
169
Chris Lattner77c76ae2008-12-13 20:12:40 +0000170 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000171 // C++ 2.5p2: Alternative tokens behave the same as its primary token
172 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000173 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000174 else
175 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
176 // Fall through on error.
177 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Richard Smith7b242542013-03-06 00:46:00 +0000178 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000179 Diag(MacroNameTok, diag::err_defined_macro_name);
Richard Smith7b242542013-03-06 00:46:00 +0000180 } else if (isDefineUndef == 2 && II->hasMacroDefinition() &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000181 getMacroInfo(II)->isBuiltinMacro()) {
Richard Smith7b242542013-03-06 00:46:00 +0000182 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
183 // and C++ [cpp.predefined]p4], but allow it as an extension.
184 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
185 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000186 } else {
187 // Okay, we got a good identifier node. Return it.
188 return;
189 }
Mike Stump11289f42009-09-09 15:08:12 +0000190
Chris Lattnerf64b3522008-03-09 01:54:53 +0000191 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000192 // token kind to tok::eod.
193 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000194 return DiscardUntilEndOfDirective();
195}
196
James Dennettf6333ac2012-06-22 05:46:07 +0000197/// \brief Ensure that the next token is a tok::eod token.
198///
199/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000200/// true, then we consider macros that expand to zero tokens as being ok.
201void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000202 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000203 // Lex unexpanded tokens for most directives: macros might expand to zero
204 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
205 // #line) allow empty macros.
206 if (EnableMacros)
207 Lex(Tmp);
208 else
209 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattnerf64b3522008-03-09 01:54:53 +0000211 // There should be no tokens after the directive, but we allow them as an
212 // extension.
213 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
214 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000215
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000216 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000217 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000218 // or if this is a macro-style preprocessing directive, because it is more
219 // trouble than it is worth to insert /**/ and check that there is no /**/
220 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000221 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000222 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000223 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000224 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
225 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000226 DiscardUntilEndOfDirective();
227 }
228}
229
230
231
James Dennettf6333ac2012-06-22 05:46:07 +0000232/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
233/// decided that the subsequent tokens are in the \#if'd out portion of the
234/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000235/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000236/// this \#if directive, so \#else/\#elif blocks should never be entered.
237/// If ElseOk is true, then \#else directives are ok, if not, then we have
238/// already seen one so a \#else directive is a duplicate. When this returns,
239/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000240void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
241 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000242 bool FoundElse,
243 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000244 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000245 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000246
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000247 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000248 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000249
Ted Kremenek56572ab2008-12-12 18:34:08 +0000250 if (CurPTHLexer) {
251 PTHSkipExcludedConditionalBlock();
252 return;
253 }
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattnerf64b3522008-03-09 01:54:53 +0000255 // Enter raw mode to disable identifier lookup (and thus macro expansion),
256 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000257 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000258 Token Tok;
259 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000260 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000262 if (Tok.is(tok::code_completion)) {
263 if (CodeComplete)
264 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000265 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000266 continue;
267 }
268
Chris Lattnerf64b3522008-03-09 01:54:53 +0000269 // If this is the end of the buffer, we have an error.
270 if (Tok.is(tok::eof)) {
271 // Emit errors for each unterminated conditional on the stack, including
272 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000273 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000274 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000275 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
276 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000277 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000278 }
279
Chris Lattnerf64b3522008-03-09 01:54:53 +0000280 // Just return and let the caller lex after this #include.
281 break;
282 }
Mike Stump11289f42009-09-09 15:08:12 +0000283
Chris Lattnerf64b3522008-03-09 01:54:53 +0000284 // If this token is not a preprocessor directive, just skip it.
285 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
286 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000287
Chris Lattnerf64b3522008-03-09 01:54:53 +0000288 // We just parsed a # character at the start of a line, so we're in
289 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000290 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000291 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000292 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000293
Mike Stump11289f42009-09-09 15:08:12 +0000294
Chris Lattnerf64b3522008-03-09 01:54:53 +0000295 // Read the next token, the directive flavor.
296 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000297
Chris Lattnerf64b3522008-03-09 01:54:53 +0000298 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
299 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000300 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000301 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000302 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000303 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000304 continue;
305 }
306
307 // If the first letter isn't i or e, it isn't intesting to us. We know that
308 // this is safe in the face of spelling differences, because there is no way
309 // to spell an i/e in a strange way that is another letter. Skipping this
310 // allows us to avoid looking up the identifier info for #define/#undef and
311 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000312 const char *RawCharData = Tok.getRawIdentifierData();
313
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000315 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000316 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000317 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000318 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000319 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000320 continue;
321 }
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattnerf64b3522008-03-09 01:54:53 +0000323 // Get the identifier name without trigraphs or embedded newlines. Note
324 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
325 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000326 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000327 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000328 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000329 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000330 } else {
331 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000332 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000333 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000334 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000335 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000336 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000337 continue;
338 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000339 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000340 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000341 }
Mike Stump11289f42009-09-09 15:08:12 +0000342
Benjamin Kramer144884642009-12-31 13:32:38 +0000343 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000344 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000345 if (Sub.empty() || // "if"
346 Sub == "def" || // "ifdef"
347 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000348 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
349 // bother parsing the condition.
350 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000351 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000352 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000353 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000354 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000355 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000356 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000357 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000358 PPConditionalInfo CondInfo;
359 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000360 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000361 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000363
Chris Lattnerf64b3522008-03-09 01:54:53 +0000364 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000365 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000366 // Restore the value of LexingRawMode so that trailing comments
367 // are handled correctly, if we've reached the outermost block.
368 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000369 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000370 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000371 if (Callbacks)
372 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000373 break;
Richard Smithd0124572012-06-21 00:35:03 +0000374 } else {
375 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000376 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000377 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000378 // #else directive in a skipping conditional. If not in some other
379 // skipping conditional, and if #else hasn't already been seen, enter it
380 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000381 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattnerf64b3522008-03-09 01:54:53 +0000383 // If this is a #else with a #else before it, report the error.
384 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 // Note that we've seen a #else in this conditional.
387 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000388
Chris Lattnerf64b3522008-03-09 01:54:53 +0000389 // If the conditional is at the top level, and the #if block wasn't
390 // entered, enter the #else block now.
391 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
392 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000393 // Restore the value of LexingRawMode so that trailing comments
394 // are handled correctly.
395 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000396 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000397 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000398 if (Callbacks)
399 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000400 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000401 } else {
402 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000403 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000404 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000405 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000406
407 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000408 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000409 // If this is in a skipping block or if we're already handled this #if
410 // block, don't bother parsing the condition.
411 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
412 DiscardUntilEndOfDirective();
413 ShouldEnter = false;
414 } else {
415 // Restore the value of LexingRawMode so that identifiers are
416 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000417 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
418 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000419 IdentifierInfo *IfNDefMacro = 0;
420 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000421 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000422 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000423 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattnerf64b3522008-03-09 01:54:53 +0000425 // If this is a #elif with a #else before it, report the error.
426 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000427
Chris Lattnerf64b3522008-03-09 01:54:53 +0000428 // If this condition is true, enter it!
429 if (ShouldEnter) {
430 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000431 if (Callbacks)
432 Callbacks->Elif(Tok.getLocation(),
433 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompsonb1028562013-07-18 00:00:36 +0000434 ShouldEnter, CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000435 break;
436 }
437 }
438 }
Mike Stump11289f42009-09-09 15:08:12 +0000439
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000440 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000441 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000442 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000443 }
444
445 // Finally, if we are out of the conditional (saw an #endif or ran off the end
446 // of the file, just stop skipping and return to lexing whatever came after
447 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000448 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000449
450 if (Callbacks) {
451 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
452 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
453 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000454}
455
Ted Kremenek56572ab2008-12-12 18:34:08 +0000456void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000457
458 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000459 assert(CurPTHLexer);
460 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000461
Ted Kremenek56572ab2008-12-12 18:34:08 +0000462 // Skip to the next '#else', '#elif', or #endif.
463 if (CurPTHLexer->SkipBlock()) {
464 // We have reached an #endif. Both the '#' and 'endif' tokens
465 // have been consumed by the PTHLexer. Just pop off the condition level.
466 PPConditionalInfo CondInfo;
467 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000468 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000469 assert(!InCond && "Can't be skipping if not in a conditional!");
470 break;
471 }
Mike Stump11289f42009-09-09 15:08:12 +0000472
Ted Kremenek56572ab2008-12-12 18:34:08 +0000473 // We have reached a '#else' or '#elif'. Lex the next token to get
474 // the directive flavor.
475 Token Tok;
476 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000477
Ted Kremenek56572ab2008-12-12 18:34:08 +0000478 // We can actually look up the IdentifierInfo here since we aren't in
479 // raw mode.
480 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
481
482 if (K == tok::pp_else) {
483 // #else: Enter the else condition. We aren't in a nested condition
484 // since we skip those. We're always in the one matching the last
485 // blocked we skipped.
486 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
487 // Note that we've seen a #else in this conditional.
488 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000489
Ted Kremenek56572ab2008-12-12 18:34:08 +0000490 // If the #if block wasn't entered then enter the #else block now.
491 if (!CondInfo.FoundNonSkip) {
492 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000493
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000494 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000495 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000496 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000497 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000498
Ted Kremenek56572ab2008-12-12 18:34:08 +0000499 break;
500 }
Mike Stump11289f42009-09-09 15:08:12 +0000501
Ted Kremenek56572ab2008-12-12 18:34:08 +0000502 // Otherwise skip this block.
503 continue;
504 }
Mike Stump11289f42009-09-09 15:08:12 +0000505
Ted Kremenek56572ab2008-12-12 18:34:08 +0000506 assert(K == tok::pp_elif);
507 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
508
509 // If this is a #elif with a #else before it, report the error.
510 if (CondInfo.FoundElse)
511 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000512
Ted Kremenek56572ab2008-12-12 18:34:08 +0000513 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000514 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000515 if (CondInfo.FoundNonSkip)
516 continue;
517
518 // Evaluate the condition of the #elif.
519 IdentifierInfo *IfNDefMacro = 0;
520 CurPTHLexer->ParsingPreprocessorDirective = true;
521 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
522 CurPTHLexer->ParsingPreprocessorDirective = false;
523
524 // If this condition is true, enter it!
525 if (ShouldEnter) {
526 CondInfo.FoundNonSkip = true;
527 break;
528 }
529
530 // Otherwise, skip this block and go to the next one.
531 continue;
532 }
533}
534
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000535const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000536 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000537 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000538 bool isAngled,
539 const DirectoryLookup *FromDir,
540 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000541 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000542 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000543 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000544 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000545 // If the header lookup mechanism may be relative to the current file, pass in
546 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000547 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000548 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000549 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000550 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000551
Chris Lattner022923a2009-02-04 19:45:07 +0000552 // If there is no file entry associated with this file, it must be the
553 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000554 // it won't be scanned for preprocessor directives. If we have the
555 // predefines buffer, resolve #include references (which come from the
556 // -include command line argument) as if they came from the main file, this
557 // affects file lookup etc.
558 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000559 FID = SourceMgr.getMainFileID();
560 CurFileEnt = SourceMgr.getFileEntryForID(FID);
561 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000562 }
Mike Stump11289f42009-09-09 15:08:12 +0000563
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000564 // Do a standard file entry lookup.
565 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000566 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000567 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000568 SearchPath, RelativePath, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000569 if (FE) {
570 if (SuggestedModule) {
571 Module *RequestedModule = SuggestedModule->getModule();
572 if (RequestedModule) {
573 ModuleMap::ModuleHeaderRole Role = SuggestedModule->getRole();
574 #ifndef NDEBUG
575 // Check for consistency between the module header role
576 // as obtained from the lookup and as obtained from the module.
577 // This check is not cheap, so enable it only for debugging.
578 SmallVectorImpl<const FileEntry *> &PvtHdrs
579 = RequestedModule->PrivateHeaders;
580 SmallVectorImpl<const FileEntry *>::iterator Look
581 = std::find(PvtHdrs.begin(), PvtHdrs.end(), FE);
582 bool IsPrivate = Look != PvtHdrs.end();
583 assert((IsPrivate && Role == ModuleMap::PrivateHeader)
584 || (!IsPrivate && Role != ModuleMap::PrivateHeader));
585 #endif
586 if (Role == ModuleMap::PrivateHeader) {
587 if (RequestedModule->getTopLevelModule() != getCurrentModule())
588 Diag(FilenameLoc, diag::error_use_of_private_header_outside_module)
589 << Filename;
590 }
591 }
592 }
593 return FE;
594 }
Mike Stump11289f42009-09-09 15:08:12 +0000595
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000596 // Otherwise, see if this is a subframework header. If so, this is relative
597 // to one of the headers on the #include stack. Walk the list of the current
598 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000599 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000600 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000601 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000602 SearchPath, RelativePath,
603 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000604 return FE;
605 }
Mike Stump11289f42009-09-09 15:08:12 +0000606
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000607 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
608 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000609 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000610 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000611 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000612 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000613 Filename, CurFileEnt, SearchPath, RelativePath,
614 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000615 return FE;
616 }
617 }
Mike Stump11289f42009-09-09 15:08:12 +0000618
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000619 // Otherwise, we really couldn't find the file.
620 return 0;
621}
622
Chris Lattnerf64b3522008-03-09 01:54:53 +0000623
624//===----------------------------------------------------------------------===//
625// Preprocessor Directive Handling.
626//===----------------------------------------------------------------------===//
627
David Blaikied5321242012-06-06 18:52:13 +0000628class Preprocessor::ResetMacroExpansionHelper {
629public:
630 ResetMacroExpansionHelper(Preprocessor *pp)
631 : PP(pp), save(pp->DisableMacroExpansion) {
632 if (pp->MacroExpansionInDirectivesOverride)
633 pp->DisableMacroExpansion = false;
634 }
635 ~ResetMacroExpansionHelper() {
636 PP->DisableMacroExpansion = save;
637 }
638private:
639 Preprocessor *PP;
640 bool save;
641};
642
Chris Lattnerf64b3522008-03-09 01:54:53 +0000643/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000644/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000645/// lexer/preprocessor state, and advances the lexer(s) so that the next token
646/// read is the correct one.
647void Preprocessor::HandleDirective(Token &Result) {
648 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000649
Chris Lattnerf64b3522008-03-09 01:54:53 +0000650 // We just parsed a # character at the start of a line, so we're in directive
651 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000652 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000653 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000654 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000655
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000656 bool ImmediatelyAfterTopLevelIfndef =
657 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
658 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
659
Chris Lattnerf64b3522008-03-09 01:54:53 +0000660 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000661
Chris Lattnerf64b3522008-03-09 01:54:53 +0000662 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000663 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000664 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000665 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattner2d17ab72009-03-18 21:00:25 +0000667 // Save the '#' token in case we need to return it later.
668 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000669
Chris Lattnerf64b3522008-03-09 01:54:53 +0000670 // Read the next token, the directive flavor. This isn't expanded due to
671 // C99 6.10.3p8.
672 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000673
Chris Lattnerf64b3522008-03-09 01:54:53 +0000674 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
675 // #define A(x) #x
676 // A(abc
677 // #warning blah
678 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000679 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
680 // not support this for #include-like directives, since that can result in
681 // terrible diagnostics, and does not work in GCC.
682 if (InMacroArgs) {
683 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
684 switch (II->getPPKeywordID()) {
685 case tok::pp_include:
686 case tok::pp_import:
687 case tok::pp_include_next:
688 case tok::pp___include_macros:
689 Diag(Result, diag::err_embedded_include) << II->getName();
690 DiscardUntilEndOfDirective();
691 return;
692 default:
693 break;
694 }
695 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000696 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000697 }
Mike Stump11289f42009-09-09 15:08:12 +0000698
David Blaikied5321242012-06-06 18:52:13 +0000699 // Temporarily enable macro expansion if set so
700 // and reset to previous state when returning from this function.
701 ResetMacroExpansionHelper helper(this);
702
Chris Lattnerf64b3522008-03-09 01:54:53 +0000703 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000704 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000705 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000706 case tok::code_completion:
707 if (CodeComplete)
708 CodeComplete->CodeCompleteDirective(
709 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000710 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000711 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000712 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000713 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000714 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000715 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000716 default:
717 IdentifierInfo *II = Result.getIdentifierInfo();
718 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000719
Chris Lattnerf64b3522008-03-09 01:54:53 +0000720 // Ask what the preprocessor keyword ID is.
721 switch (II->getPPKeywordID()) {
722 default: break;
723 // C99 6.10.1 - Conditional Inclusion.
724 case tok::pp_if:
725 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
726 case tok::pp_ifdef:
727 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
728 case tok::pp_ifndef:
729 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
730 case tok::pp_elif:
731 return HandleElifDirective(Result);
732 case tok::pp_else:
733 return HandleElseDirective(Result);
734 case tok::pp_endif:
735 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000736
Chris Lattnerf64b3522008-03-09 01:54:53 +0000737 // C99 6.10.2 - Source File Inclusion.
738 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000739 // Handle #include.
740 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000741 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000742 // Handle -imacros.
743 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000744
Chris Lattnerf64b3522008-03-09 01:54:53 +0000745 // C99 6.10.3 - Macro Replacement.
746 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000747 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000748 case tok::pp_undef:
749 return HandleUndefDirective(Result);
750
751 // C99 6.10.4 - Line Control.
752 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000753 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000754
Chris Lattnerf64b3522008-03-09 01:54:53 +0000755 // C99 6.10.5 - Error Directive.
756 case tok::pp_error:
757 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000758
Chris Lattnerf64b3522008-03-09 01:54:53 +0000759 // C99 6.10.6 - Pragma Directive.
760 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000761 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000762
Chris Lattnerf64b3522008-03-09 01:54:53 +0000763 // GNU Extensions.
764 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000765 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000766 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000767 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000768
Chris Lattnerf64b3522008-03-09 01:54:53 +0000769 case tok::pp_warning:
770 Diag(Result, diag::ext_pp_warning_directive);
771 return HandleUserDiagnosticDirective(Result, true);
772 case tok::pp_ident:
773 return HandleIdentSCCSDirective(Result);
774 case tok::pp_sccs:
775 return HandleIdentSCCSDirective(Result);
776 case tok::pp_assert:
777 //isExtension = true; // FIXME: implement #assert
778 break;
779 case tok::pp_unassert:
780 //isExtension = true; // FIXME: implement #unassert
781 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000782
Douglas Gregor663b48f2012-01-03 19:48:16 +0000783 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000784 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000785 return HandleMacroPublicDirective(Result);
786 break;
787
Douglas Gregor663b48f2012-01-03 19:48:16 +0000788 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000789 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000790 return HandleMacroPrivateDirective(Result);
791 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000792 }
793 break;
794 }
Mike Stump11289f42009-09-09 15:08:12 +0000795
Chris Lattner2d17ab72009-03-18 21:00:25 +0000796 // If this is a .S file, treat unknown # directives as non-preprocessor
797 // directives. This is important because # may be a comment or introduce
798 // various pseudo-ops. Just return the # token and push back the following
799 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000800 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000801 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000802 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000803 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000804 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000805
806 // If the second token is a hashhash token, then we need to translate it to
807 // unknown so the token lexer doesn't try to perform token pasting.
808 if (Result.is(tok::hashhash))
809 Toks[1].setKind(tok::unknown);
810
Chris Lattner2d17ab72009-03-18 21:00:25 +0000811 // Enter this token stream so that we re-lex the tokens. Make sure to
812 // enable macro expansion, in case the token after the # is an identifier
813 // that is expanded.
814 EnterTokenStream(Toks, 2, false, true);
815 return;
816 }
Mike Stump11289f42009-09-09 15:08:12 +0000817
Chris Lattnerf64b3522008-03-09 01:54:53 +0000818 // If we reached here, the preprocessing token is not valid!
819 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000820
Chris Lattnerf64b3522008-03-09 01:54:53 +0000821 // Read the rest of the PP line.
822 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000823
Chris Lattnerf64b3522008-03-09 01:54:53 +0000824 // Okay, we're done parsing the directive.
825}
826
Chris Lattner76e68962009-01-26 06:19:46 +0000827/// GetLineValue - Convert a numeric token into an unsigned value, emitting
828/// Diagnostic DiagID if it is invalid, and returning the value in Val.
829static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000830 unsigned DiagID, Preprocessor &PP,
831 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000832 if (DigitTok.isNot(tok::numeric_constant)) {
833 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000834
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000835 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000836 PP.DiscardUntilEndOfDirective();
837 return true;
838 }
Mike Stump11289f42009-09-09 15:08:12 +0000839
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000840 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000841 IntegerBuffer.resize(DigitTok.getLength());
842 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000843 bool Invalid = false;
844 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
845 if (Invalid)
846 return true;
847
Chris Lattnerd66f1722009-04-18 18:35:15 +0000848 // Verify that we have a simple digit-sequence, and compute the value. This
849 // is always a simple digit string computed in decimal, so we do this manually
850 // here.
851 Val = 0;
852 for (unsigned i = 0; i != ActualLength; ++i) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000853 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000854 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000855 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000856 PP.DiscardUntilEndOfDirective();
857 return true;
858 }
Mike Stump11289f42009-09-09 15:08:12 +0000859
Chris Lattnerd66f1722009-04-18 18:35:15 +0000860 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
861 if (NextVal < Val) { // overflow.
862 PP.Diag(DigitTok, DiagID);
863 PP.DiscardUntilEndOfDirective();
864 return true;
865 }
866 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000867 }
Mike Stump11289f42009-09-09 15:08:12 +0000868
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000869 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000870 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
871 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000872
Chris Lattner76e68962009-01-26 06:19:46 +0000873 return false;
874}
875
James Dennettf6333ac2012-06-22 05:46:07 +0000876/// \brief Handle a \#line directive: C99 6.10.4.
877///
878/// The two acceptable forms are:
879/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000880/// # line digit-sequence
881/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000882/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000883void Preprocessor::HandleLineDirective(Token &Tok) {
884 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
885 // expanded.
886 Token DigitTok;
887 Lex(DigitTok);
888
Chris Lattner100c65e2009-01-26 05:29:08 +0000889 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000890 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000891 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000892 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000893
894 if (LineNo == 0)
895 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000896
Chris Lattner76e68962009-01-26 06:19:46 +0000897 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
898 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000899 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000900 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000901 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000902 if (LineNo >= LineLimit)
903 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000904 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000905 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000906
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000907 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000908 Token StrTok;
909 Lex(StrTok);
910
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000911 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
912 // string followed by eod.
913 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000914 ; // ok
915 else if (StrTok.isNot(tok::string_literal)) {
916 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000917 return DiscardUntilEndOfDirective();
918 } else if (StrTok.hasUDSuffix()) {
919 Diag(StrTok, diag::err_invalid_string_udl);
920 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000921 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000922 // Parse and validate the string, converting it into a unique ID.
923 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000924 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000925 if (Literal.hadError)
926 return DiscardUntilEndOfDirective();
927 if (Literal.Pascal) {
928 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
929 return DiscardUntilEndOfDirective();
930 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000931 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000932
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000933 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000934 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
935 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000936 }
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000938 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000939
Chris Lattner839150e2009-03-27 17:13:49 +0000940 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000941 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
942 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000943 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000944}
945
Chris Lattner76e68962009-01-26 06:19:46 +0000946/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
947/// marker directive.
948static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
949 bool &IsSystemHeader, bool &IsExternCHeader,
950 Preprocessor &PP) {
951 unsigned FlagVal;
952 Token FlagTok;
953 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000954 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000955 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
956 return true;
957
958 if (FlagVal == 1) {
959 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chris Lattner76e68962009-01-26 06:19:46 +0000961 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000962 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000963 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
964 return true;
965 } else if (FlagVal == 2) {
966 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000967
Chris Lattner1c967782009-02-04 06:25:26 +0000968 SourceManager &SM = PP.getSourceManager();
969 // If we are leaving the current presumed file, check to make sure the
970 // presumed include stack isn't empty!
971 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000972 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000973 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000974 if (PLoc.isInvalid())
975 return true;
976
Chris Lattner1c967782009-02-04 06:25:26 +0000977 // If there is no include loc (main file) or if the include loc is in a
978 // different physical file, then we aren't in a "1" line marker flag region.
979 SourceLocation IncLoc = PLoc.getIncludeLoc();
980 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000981 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000982 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
983 PP.DiscardUntilEndOfDirective();
984 return true;
985 }
Mike Stump11289f42009-09-09 15:08:12 +0000986
Chris Lattner76e68962009-01-26 06:19:46 +0000987 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000988 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000989 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
990 return true;
991 }
992
993 // We must have 3 if there are still flags.
994 if (FlagVal != 3) {
995 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000996 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000997 return true;
998 }
Mike Stump11289f42009-09-09 15:08:12 +0000999
Chris Lattner76e68962009-01-26 06:19:46 +00001000 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001001
Chris Lattner76e68962009-01-26 06:19:46 +00001002 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001003 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001004 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001005 return true;
1006
1007 // We must have 4 if there is yet another flag.
1008 if (FlagVal != 4) {
1009 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001010 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001011 return true;
1012 }
Mike Stump11289f42009-09-09 15:08:12 +00001013
Chris Lattner76e68962009-01-26 06:19:46 +00001014 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001015
Chris Lattner76e68962009-01-26 06:19:46 +00001016 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001017 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001018
1019 // There are no more valid flags here.
1020 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001021 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001022 return true;
1023}
1024
1025/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1026/// one of the following forms:
1027///
1028/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001029/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001030/// # 42 "file" ('1' | '2')? '3' '4'?
1031///
1032void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1033 // Validate the number and convert it to an unsigned. GNU does not have a
1034 // line # limit other than it fit in 32-bits.
1035 unsigned LineNo;
1036 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001037 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001038 return;
Mike Stump11289f42009-09-09 15:08:12 +00001039
Chris Lattner76e68962009-01-26 06:19:46 +00001040 Token StrTok;
1041 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001042
Chris Lattner76e68962009-01-26 06:19:46 +00001043 bool IsFileEntry = false, IsFileExit = false;
1044 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001045 int FilenameID = -1;
1046
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001047 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1048 // string followed by eod.
1049 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001050 ; // ok
1051 else if (StrTok.isNot(tok::string_literal)) {
1052 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001053 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001054 } else if (StrTok.hasUDSuffix()) {
1055 Diag(StrTok, diag::err_invalid_string_udl);
1056 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001057 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001058 // Parse and validate the string, converting it into a unique ID.
1059 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001060 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001061 if (Literal.hadError)
1062 return DiscardUntilEndOfDirective();
1063 if (Literal.Pascal) {
1064 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1065 return DiscardUntilEndOfDirective();
1066 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001067 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001068
Chris Lattner76e68962009-01-26 06:19:46 +00001069 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001070 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001071 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001072 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001073 }
Mike Stump11289f42009-09-09 15:08:12 +00001074
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001075 // Create a line note with this information.
1076 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001077 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001078 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001079
Chris Lattner839150e2009-03-27 17:13:49 +00001080 // If the preprocessor has callbacks installed, notify them of the #line
1081 // change. This is used so that the line marker comes out in -E mode for
1082 // example.
1083 if (Callbacks) {
1084 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1085 if (IsFileEntry)
1086 Reason = PPCallbacks::EnterFile;
1087 else if (IsFileExit)
1088 Reason = PPCallbacks::ExitFile;
1089 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1090 if (IsExternCHeader)
1091 FileKind = SrcMgr::C_ExternCSystem;
1092 else if (IsSystemHeader)
1093 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001094
Chris Lattnerc745cec2010-04-14 04:28:50 +00001095 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001096 }
Chris Lattner76e68962009-01-26 06:19:46 +00001097}
1098
1099
Chris Lattner38d7fd22009-01-26 05:30:54 +00001100/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1101///
Mike Stump11289f42009-09-09 15:08:12 +00001102void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001103 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001104 // PTH doesn't emit #warning or #error directives.
1105 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001106 return CurPTHLexer->DiscardToEndOfLine();
1107
Chris Lattnerf64b3522008-03-09 01:54:53 +00001108 // Read the rest of the line raw. We do this because we don't want macros
1109 // to be expanded and we don't require that the tokens be valid preprocessing
1110 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1111 // collapse multiple consequtive white space between tokens, but this isn't
1112 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001113 SmallString<128> Message;
1114 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001115
1116 // Find the first non-whitespace character, so that we can make the
1117 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001118 StringRef Msg = Message.str().ltrim(" ");
1119
Chris Lattner100c65e2009-01-26 05:29:08 +00001120 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001121 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001122 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001123 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001124}
1125
1126/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1127///
1128void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1129 // Yes, this directive is an extension.
1130 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001131
Chris Lattnerf64b3522008-03-09 01:54:53 +00001132 // Read the string argument.
1133 Token StrTok;
1134 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001135
Chris Lattnerf64b3522008-03-09 01:54:53 +00001136 // If the token kind isn't a string, it's a malformed directive.
1137 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001138 StrTok.isNot(tok::wide_string_literal)) {
1139 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001140 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001141 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001142 return;
1143 }
Mike Stump11289f42009-09-09 15:08:12 +00001144
Richard Smithd67aea22012-03-06 03:21:47 +00001145 if (StrTok.hasUDSuffix()) {
1146 Diag(StrTok, diag::err_invalid_string_udl);
1147 return DiscardUntilEndOfDirective();
1148 }
1149
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001150 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001151 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001152
Douglas Gregordc970f02010-03-16 22:30:13 +00001153 if (Callbacks) {
1154 bool Invalid = false;
1155 std::string Str = getSpelling(StrTok, &Invalid);
1156 if (!Invalid)
1157 Callbacks->Ident(Tok.getLocation(), Str);
1158 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001159}
1160
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001161/// \brief Handle a #public directive.
1162void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001163 Token MacroNameTok;
1164 ReadMacroName(MacroNameTok, 2);
1165
1166 // Error reading macro name? If so, diagnostic already issued.
1167 if (MacroNameTok.is(tok::eod))
1168 return;
1169
Douglas Gregor663b48f2012-01-03 19:48:16 +00001170 // Check to see if this is the last token on the #__public_macro line.
1171 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001172
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001173 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001174 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001175 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001176
1177 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001178 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001179 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001180 return;
1181 }
1182
1183 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001184 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1185 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001186}
1187
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001188/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001189void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1190 Token MacroNameTok;
1191 ReadMacroName(MacroNameTok, 2);
1192
1193 // Error reading macro name? If so, diagnostic already issued.
1194 if (MacroNameTok.is(tok::eod))
1195 return;
1196
Douglas Gregor663b48f2012-01-03 19:48:16 +00001197 // Check to see if this is the last token on the #__private_macro line.
1198 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001199
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001200 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001201 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001202 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001203
1204 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001205 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001206 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001207 return;
1208 }
1209
1210 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001211 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1212 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001213}
1214
Chris Lattnerf64b3522008-03-09 01:54:53 +00001215//===----------------------------------------------------------------------===//
1216// Preprocessor Include Directive Handling.
1217//===----------------------------------------------------------------------===//
1218
1219/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001220/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001221/// true if the input filename was in <>'s or false if it were in ""'s. The
1222/// caller is expected to provide a buffer that is large enough to hold the
1223/// spelling of the filename, but is also expected to handle the case when
1224/// this method decides to use a different buffer.
1225bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001226 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001227 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001228 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001229
Chris Lattnerf64b3522008-03-09 01:54:53 +00001230 // Make sure the filename is <x> or "x".
1231 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001232 if (Buffer[0] == '<') {
1233 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001234 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001235 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001236 return true;
1237 }
1238 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001239 } else if (Buffer[0] == '"') {
1240 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001241 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001242 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001243 return true;
1244 }
1245 isAngled = false;
1246 } else {
1247 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001248 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001249 return true;
1250 }
Mike Stump11289f42009-09-09 15:08:12 +00001251
Chris Lattnerf64b3522008-03-09 01:54:53 +00001252 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001253 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001254 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001255 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001256 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001257 }
Mike Stump11289f42009-09-09 15:08:12 +00001258
Chris Lattnerf64b3522008-03-09 01:54:53 +00001259 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001260 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001261 return isAngled;
1262}
1263
James Dennettf6333ac2012-06-22 05:46:07 +00001264/// \brief Handle cases where the \#include name is expanded from a macro
1265/// as multiple tokens, which need to be glued together.
1266///
1267/// This occurs for code like:
1268/// \code
1269/// \#define FOO <a/b.h>
1270/// \#include FOO
1271/// \endcode
Chris Lattnerf64b3522008-03-09 01:54:53 +00001272/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1273///
1274/// This code concatenates and consumes tokens up to the '>' token. It returns
1275/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001276/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001277bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001278 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001279 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001280 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001281
John Thompsonb5353522009-10-30 13:49:06 +00001282 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001283 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001284 End = CurTok.getLocation();
1285
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001286 // FIXME: Provide code completion for #includes.
1287 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001288 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001289 Lex(CurTok);
1290 continue;
1291 }
1292
Chris Lattnerf64b3522008-03-09 01:54:53 +00001293 // Append the spelling of this token to the buffer. If there was a space
1294 // before it, add it now.
1295 if (CurTok.hasLeadingSpace())
1296 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001297
Chris Lattnerf64b3522008-03-09 01:54:53 +00001298 // Get the spelling of the token, directly into FilenameBuffer if possible.
1299 unsigned PreAppendSize = FilenameBuffer.size();
1300 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001301
Chris Lattnerf64b3522008-03-09 01:54:53 +00001302 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001303 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001304
Chris Lattnerf64b3522008-03-09 01:54:53 +00001305 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1306 if (BufPtr != &FilenameBuffer[PreAppendSize])
1307 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001308
Chris Lattnerf64b3522008-03-09 01:54:53 +00001309 // Resize FilenameBuffer to the correct size.
1310 if (CurTok.getLength() != ActualLen)
1311 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001312
Chris Lattnerf64b3522008-03-09 01:54:53 +00001313 // If we found the '>' marker, return success.
1314 if (CurTok.is(tok::greater))
1315 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001316
John Thompsonb5353522009-10-30 13:49:06 +00001317 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001318 }
1319
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001320 // If we hit the eod marker, emit an error and return true so that the caller
1321 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001322 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001323 return true;
1324}
1325
James Dennettf6333ac2012-06-22 05:46:07 +00001326/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1327/// the file to be included from the lexer, then include it! This is a common
1328/// routine with functionality shared between \#include, \#include_next and
1329/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001330/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001331void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1332 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001333 const DirectoryLookup *LookupFrom,
1334 bool isImport) {
1335
1336 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001337 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001338
Chris Lattnerf64b3522008-03-09 01:54:53 +00001339 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001340 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001341 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001342 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001343 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001344
Chris Lattnerf64b3522008-03-09 01:54:53 +00001345 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001346 case tok::eod:
1347 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001348 return;
Mike Stump11289f42009-09-09 15:08:12 +00001349
Chris Lattnerf64b3522008-03-09 01:54:53 +00001350 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001351 case tok::string_literal:
1352 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001353 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001354 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001355 break;
Mike Stump11289f42009-09-09 15:08:12 +00001356
Chris Lattnerf64b3522008-03-09 01:54:53 +00001357 case tok::less:
1358 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1359 // case, glue the tokens together into FilenameBuffer and interpret those.
1360 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001361 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001362 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001363 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001364 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001365 break;
1366 default:
1367 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1368 DiscardUntilEndOfDirective();
1369 return;
1370 }
Mike Stump11289f42009-09-09 15:08:12 +00001371
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001372 CharSourceRange FilenameRange
1373 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001374 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001375 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001376 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001377 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1378 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001379 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001380 DiscardUntilEndOfDirective();
1381 return;
1382 }
Mike Stump11289f42009-09-09 15:08:12 +00001383
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001384 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001385 // we allow macros that expand to nothing after the filename, because this
1386 // falls into the category of "#include pp-tokens new-line" specified in
1387 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001388 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001389
1390 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001391 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1392 Diag(FilenameTok, diag::err_pp_include_too_deep);
1393 return;
1394 }
Mike Stump11289f42009-09-09 15:08:12 +00001395
John McCall32f5fe12011-09-30 05:12:12 +00001396 // Complain about attempts to #include files in an audit pragma.
1397 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1398 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1399 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1400
1401 // Immediately leave the pragma.
1402 PragmaARCCFCodeAuditedLoc = SourceLocation();
1403 }
1404
Aaron Ballman611306e2012-03-02 22:51:54 +00001405 if (HeaderInfo.HasIncludeAliasMap()) {
1406 // Map the filename with the brackets still attached. If the name doesn't
1407 // map to anything, fall back on the filename we've already gotten the
1408 // spelling for.
1409 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1410 if (!NewName.empty())
1411 Filename = NewName;
1412 }
1413
Chris Lattnerf64b3522008-03-09 01:54:53 +00001414 // Search include directories.
1415 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001416 SmallString<1024> SearchPath;
1417 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001418 // We get the raw path only if we have 'Callbacks' to which we later pass
1419 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001420 ModuleMap::KnownHeader SuggestedModule;
1421 SourceLocation FilenameLoc = FilenameTok.getLocation();
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001422 const FileEntry *File = LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001423 FilenameLoc, Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001424 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
Daniel Jasper07e6c402013-08-05 20:26:17 +00001425 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001426
Douglas Gregor11729f02011-11-30 18:12:06 +00001427 if (Callbacks) {
1428 if (!File) {
1429 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001430 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001431 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1432 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1433 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001434 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001435 HeaderInfo.AddSearchPath(DL, isAngled);
1436
1437 // Try the lookup again, skipping the cache.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001438 File = LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, CurDir,
Daniel Jasper07e6c402013-08-05 20:26:17 +00001439 0, 0, HeaderInfo.getHeaderSearchOpts().ModuleMaps
1440 ? &SuggestedModule
1441 : 0,
1442 /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001443 }
1444 }
1445 }
1446
Daniel Jasper07e6c402013-08-05 20:26:17 +00001447 if (!SuggestedModule || !getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001448 // Notify the callback object that we've seen an inclusion directive.
1449 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1450 FilenameRange, File,
1451 SearchPath, RelativePath,
1452 /*ImportedModule=*/0);
1453 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001454 }
1455
1456 if (File == 0) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001457 if (!SuppressIncludeNotFoundError) {
1458 // If the file could not be located and it was included via angle
1459 // brackets, we can attempt a lookup as though it were a quoted path to
1460 // provide the user with a possible fixit.
1461 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001462 File = LookupFile(
1463 FilenameLoc, Filename, false, LookupFrom, CurDir,
1464 Callbacks ? &SearchPath : 0, Callbacks ? &RelativePath : 0,
1465 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : 0);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001466 if (File) {
1467 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1468 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1469 Filename <<
1470 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1471 }
1472 }
1473 // If the file is still not found, just go with the vanilla diagnostic
1474 if (!File)
1475 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1476 }
1477 if (!File)
1478 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001479 }
1480
Douglas Gregor97eec242011-09-15 22:00:41 +00001481 // If we are supposed to import a module rather than including the header,
1482 // do so now.
Daniel Jasper07e6c402013-08-05 20:26:17 +00001483 if (SuggestedModule && getLangOpts().Modules) {
Douglas Gregor71944202011-11-30 00:36:36 +00001484 // Compute the module access path corresponding to this module.
1485 // FIXME: Should we have a second loadModule() overload to avoid this
1486 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001487 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001488 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001489 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1490 FilenameTok.getLocation()));
1491 std::reverse(Path.begin(), Path.end());
1492
Douglas Gregor41e115a2011-11-30 18:02:36 +00001493 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001494 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001495 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1496 if (I)
1497 PathString += '.';
1498 PathString += Path[I].first->getName();
1499 }
1500 int IncludeKind = 0;
1501
1502 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1503 case tok::pp_include:
1504 IncludeKind = 0;
1505 break;
1506
1507 case tok::pp_import:
1508 IncludeKind = 1;
1509 break;
1510
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001511 case tok::pp_include_next:
1512 IncludeKind = 2;
1513 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001514
1515 case tok::pp___include_macros:
1516 IncludeKind = 3;
1517 break;
1518
1519 default:
1520 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001521 }
1522
Douglas Gregor2537a362011-12-08 17:01:29 +00001523 // Determine whether we are actually building the module that this
1524 // include directive maps to.
1525 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001526 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001527
David Blaikiebbafb8a2012-03-11 07:00:24 +00001528 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001529 // If we're not building the imported module, warn that we're going
1530 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001531 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001532 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1533 /*IsTokenRange=*/false);
1534 Diag(HashLoc, diag::warn_auto_module_import)
1535 << IncludeKind << PathString
1536 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001537 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001538 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001539
Douglas Gregor71944202011-11-30 00:36:36 +00001540 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001541 // If this was an #__include_macros directive, only make macros visible.
1542 Module::NameVisibilityKind Visibility
1543 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001544 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001545 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1546 /*IsIncludeDirective=*/true);
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001547 assert((Imported == 0 || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001548 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001549
1550 if (!Imported && hadModuleLoaderFatalFailure()) {
1551 // With a fatal failure in the module loader, we abort parsing.
1552 Token &Result = IncludeTok;
1553 if (CurLexer) {
1554 Result.startToken();
1555 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1556 CurLexer->cutOffLexing();
1557 } else {
1558 assert(CurPTHLexer && "#include but no current lexer set!");
1559 CurPTHLexer->getEOF(Result);
1560 }
1561 return;
1562 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001563
1564 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001565 if (!BuildingImportedModule && Imported) {
1566 if (Callbacks) {
1567 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1568 FilenameRange, File,
1569 SearchPath, RelativePath, Imported);
1570 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001571 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001572 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001573
1574 // If we failed to find a submodule that we expected to find, we can
1575 // continue. Otherwise, there's an error in the included file, so we
1576 // don't want to include it.
1577 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1578 return;
1579 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001580 }
1581
1582 if (Callbacks && SuggestedModule) {
1583 // We didn't notify the callback object that we've seen an inclusion
1584 // directive before. Now that we are parsing the include normally and not
1585 // turning it to a module import, notify the callback object.
1586 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1587 FilenameRange, File,
1588 SearchPath, RelativePath,
1589 /*ImportedModule=*/0);
Douglas Gregor97eec242011-09-15 22:00:41 +00001590 }
1591
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001592 // The #included file will be considered to be a system header if either it is
1593 // in a system include directory, or if the #includer is a system include
1594 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001595 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001596 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001597 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001598
Chris Lattner72286d62010-04-19 20:44:31 +00001599 // Ask HeaderInfo if we should enter this #include file. If not, #including
1600 // this file will have no effect.
1601 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001602 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001603 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001604 return;
1605 }
1606
Chris Lattnerf64b3522008-03-09 01:54:53 +00001607 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001608 SourceLocation IncludePos = End;
1609 // If the filename string was the result of macro expansions, set the include
1610 // position on the file where it will be included and after the expansions.
1611 if (IncludePos.isMacroID())
1612 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1613 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001614 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001615
1616 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001617 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001618}
1619
James Dennettf6333ac2012-06-22 05:46:07 +00001620/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001621///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001622void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1623 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001624 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001625
Chris Lattnerf64b3522008-03-09 01:54:53 +00001626 // #include_next is like #include, except that we start searching after
1627 // the current found directory. If we can't do this, issue a
1628 // diagnostic.
1629 const DirectoryLookup *Lookup = CurDirLookup;
1630 if (isInPrimaryFile()) {
1631 Lookup = 0;
1632 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1633 } else if (Lookup == 0) {
1634 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1635 } else {
1636 // Start looking up in the next directory.
1637 ++Lookup;
1638 }
Mike Stump11289f42009-09-09 15:08:12 +00001639
Douglas Gregor796d76a2010-10-20 22:00:55 +00001640 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001641}
1642
James Dennettf6333ac2012-06-22 05:46:07 +00001643/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001644void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1645 // The Microsoft #import directive takes a type library and generates header
1646 // files from it, and includes those. This is beyond the scope of what clang
1647 // does, so we ignore it and error out. However, #import can optionally have
1648 // trailing attributes that span multiple lines. We're going to eat those
1649 // so we can continue processing from there.
1650 Diag(Tok, diag::err_pp_import_directive_ms );
1651
1652 // Read tokens until we get to the end of the directive. Note that the
1653 // directive can be split over multiple lines using the backslash character.
1654 DiscardUntilEndOfDirective();
1655}
1656
James Dennettf6333ac2012-06-22 05:46:07 +00001657/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001658///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001659void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1660 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001661 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1662 if (LangOpts.MicrosoftMode)
1663 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001664 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001665 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001666 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001667}
1668
Chris Lattner58a1eb02009-04-08 18:46:40 +00001669/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1670/// pseudo directive in the predefines buffer. This handles it by sucking all
1671/// tokens through the preprocessor and discarding them (only keeping the side
1672/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001673void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1674 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001675 // This directive should only occur in the predefines buffer. If not, emit an
1676 // error and reject it.
1677 SourceLocation Loc = IncludeMacrosTok.getLocation();
1678 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1679 Diag(IncludeMacrosTok.getLocation(),
1680 diag::pp_include_macros_out_of_predefines);
1681 DiscardUntilEndOfDirective();
1682 return;
1683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Chris Lattnere01d82b2009-04-08 20:53:24 +00001685 // Treat this as a normal #include for checking purposes. If this is
1686 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001687 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001688
Chris Lattnere01d82b2009-04-08 20:53:24 +00001689 Token TmpTok;
1690 do {
1691 Lex(TmpTok);
1692 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1693 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001694}
1695
Chris Lattnerf64b3522008-03-09 01:54:53 +00001696//===----------------------------------------------------------------------===//
1697// Preprocessor Macro Directive Handling.
1698//===----------------------------------------------------------------------===//
1699
1700/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1701/// definition has just been read. Lex the rest of the arguments and the
1702/// closing ), updating MI with what we learn. Return true if an error occurs
1703/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001704bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001705 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001706
Chris Lattnerf64b3522008-03-09 01:54:53 +00001707 while (1) {
1708 LexUnexpandedToken(Tok);
1709 switch (Tok.getKind()) {
1710 case tok::r_paren:
1711 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001712 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001713 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001714 // Otherwise we have #define FOO(A,)
1715 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1716 return true;
1717 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001718 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001719 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001720 diag::warn_cxx98_compat_variadic_macro :
1721 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001722
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001723 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1724 if (LangOpts.OpenCL) {
1725 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1726 return true;
1727 }
1728
Chris Lattnerf64b3522008-03-09 01:54:53 +00001729 // Lex the token after the identifier.
1730 LexUnexpandedToken(Tok);
1731 if (Tok.isNot(tok::r_paren)) {
1732 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1733 return true;
1734 }
1735 // Add the __VA_ARGS__ identifier as an argument.
1736 Arguments.push_back(Ident__VA_ARGS__);
1737 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001738 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001739 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001740 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001741 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1742 return true;
1743 default:
1744 // Handle keywords and identifiers here to accept things like
1745 // #define Foo(for) for.
1746 IdentifierInfo *II = Tok.getIdentifierInfo();
1747 if (II == 0) {
1748 // #define X(1
1749 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1750 return true;
1751 }
1752
1753 // If this is already used as an argument, it is used multiple times (e.g.
1754 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001755 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001756 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001757 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001758 return true;
1759 }
Mike Stump11289f42009-09-09 15:08:12 +00001760
Chris Lattnerf64b3522008-03-09 01:54:53 +00001761 // Add the argument to the macro info.
1762 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001763
Chris Lattnerf64b3522008-03-09 01:54:53 +00001764 // Lex the token after the identifier.
1765 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001766
Chris Lattnerf64b3522008-03-09 01:54:53 +00001767 switch (Tok.getKind()) {
1768 default: // #define X(A B
1769 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1770 return true;
1771 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001772 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001773 return false;
1774 case tok::comma: // #define X(A,
1775 break;
1776 case tok::ellipsis: // #define X(A... -> GCC extension
1777 // Diagnose extension.
1778 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001779
Chris Lattnerf64b3522008-03-09 01:54:53 +00001780 // Lex the token after the identifier.
1781 LexUnexpandedToken(Tok);
1782 if (Tok.isNot(tok::r_paren)) {
1783 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1784 return true;
1785 }
Mike Stump11289f42009-09-09 15:08:12 +00001786
Chris Lattnerf64b3522008-03-09 01:54:53 +00001787 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001788 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001789 return false;
1790 }
1791 }
1792 }
1793}
1794
James Dennettf6333ac2012-06-22 05:46:07 +00001795/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001796/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001797void Preprocessor::HandleDefineDirective(Token &DefineTok,
1798 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001799 ++NumDefined;
1800
1801 Token MacroNameTok;
1802 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001803
Chris Lattnerf64b3522008-03-09 01:54:53 +00001804 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001805 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001806 return;
1807
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001808 Token LastTok = MacroNameTok;
1809
Chris Lattnerf64b3522008-03-09 01:54:53 +00001810 // If we are supposed to keep comments in #defines, reenable comment saving
1811 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001812 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001813
Chris Lattnerf64b3522008-03-09 01:54:53 +00001814 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001815 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001816
Chris Lattnerf64b3522008-03-09 01:54:53 +00001817 Token Tok;
1818 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001819
Chris Lattnerf64b3522008-03-09 01:54:53 +00001820 // If this is a function-like macro definition, parse the argument list,
1821 // marking each of the identifiers as being used as macro arguments. Also,
1822 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001823 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001824 if (ImmediatelyAfterHeaderGuard) {
1825 // Save this macro information since it may part of a header guard.
1826 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
1827 MacroNameTok.getLocation());
1828 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001829 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001830 } else if (Tok.hasLeadingSpace()) {
1831 // This is a normal token with leading space. Clear the leading space
1832 // marker on the first token to get proper expansion.
1833 Tok.clearFlag(Token::LeadingSpace);
1834 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001835 // This is a function-like macro definition. Read the argument list.
1836 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001837 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001838 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001839 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001840 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001841 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001842 DiscardUntilEndOfDirective();
1843 return;
1844 }
1845
Chris Lattner249c38b2009-04-19 18:26:34 +00001846 // If this is a definition of a variadic C99 function-like macro, not using
1847 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001848
Chris Lattner249c38b2009-04-19 18:26:34 +00001849 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1850 // This gets unpoisoned where it is allowed.
1851 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1852 if (MI->isC99Varargs())
1853 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001854
Chris Lattnerf64b3522008-03-09 01:54:53 +00001855 // Read the first token after the arg list for down below.
1856 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001857 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001858 // C99 requires whitespace between the macro definition and the body. Emit
1859 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001860 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001861 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001862 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1863 // first character of a replacement list is not a character required by
1864 // subclause 5.2.1, then there shall be white-space separation between the
1865 // identifier and the replacement list.". 5.2.1 lists this set:
1866 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1867 // is irrelevant here.
1868 bool isInvalid = false;
1869 if (Tok.is(tok::at)) // @ is not in the list above.
1870 isInvalid = true;
1871 else if (Tok.is(tok::unknown)) {
1872 // If we have an unknown token, it is something strange like "`". Since
1873 // all of valid characters would have lexed into a single character
1874 // token of some sort, we know this is not a valid case.
1875 isInvalid = true;
1876 }
1877 if (isInvalid)
1878 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1879 else
1880 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001881 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001882
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001883 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001884 LastTok = Tok;
1885
Chris Lattnerf64b3522008-03-09 01:54:53 +00001886 // Read the rest of the macro body.
1887 if (MI->isObjectLike()) {
1888 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001889 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001890 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001891 MI->AddTokenToBody(Tok);
1892 // Get the next token of the macro.
1893 LexUnexpandedToken(Tok);
1894 }
Mike Stump11289f42009-09-09 15:08:12 +00001895
Chris Lattnerf64b3522008-03-09 01:54:53 +00001896 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001897 // Otherwise, read the body of a function-like macro. While we are at it,
1898 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1899 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001900 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001901 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001902
Eli Friedman14d3c792012-11-14 02:18:46 +00001903 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001904 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001905
Chris Lattnerf64b3522008-03-09 01:54:53 +00001906 // Get the next token of the macro.
1907 LexUnexpandedToken(Tok);
1908 continue;
1909 }
Mike Stump11289f42009-09-09 15:08:12 +00001910
Richard Smith701a3522013-07-09 01:00:29 +00001911 // If we're in -traditional mode, then we should ignore stringification
1912 // and token pasting. Mark the tokens as unknown so as not to confuse
1913 // things.
1914 if (getLangOpts().TraditionalCPP) {
1915 Tok.setKind(tok::unknown);
1916 MI->AddTokenToBody(Tok);
1917
1918 // Get the next token of the macro.
1919 LexUnexpandedToken(Tok);
1920 continue;
1921 }
1922
Eli Friedman14d3c792012-11-14 02:18:46 +00001923 if (Tok.is(tok::hashhash)) {
1924
1925 // If we see token pasting, check if it looks like the gcc comma
1926 // pasting extension. We'll use this information to suppress
1927 // diagnostics later on.
1928
1929 // Get the next token of the macro.
1930 LexUnexpandedToken(Tok);
1931
1932 if (Tok.is(tok::eod)) {
1933 MI->AddTokenToBody(LastTok);
1934 break;
1935 }
1936
1937 unsigned NumTokens = MI->getNumTokens();
1938 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1939 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1940 MI->setHasCommaPasting();
1941
1942 // Things look ok, add the '##' and param name tokens to the macro.
1943 MI->AddTokenToBody(LastTok);
1944 MI->AddTokenToBody(Tok);
1945 LastTok = Tok;
1946
1947 // Get the next token of the macro.
1948 LexUnexpandedToken(Tok);
1949 continue;
1950 }
1951
Chris Lattnerf64b3522008-03-09 01:54:53 +00001952 // Get the next token of the macro.
1953 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001954
Chris Lattner83bd8282009-05-25 17:16:10 +00001955 // Check for a valid macro arg identifier.
1956 if (Tok.getIdentifierInfo() == 0 ||
1957 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1958
1959 // If this is assembler-with-cpp mode, we accept random gibberish after
1960 // the '#' because '#' is often a comment character. However, change
1961 // the kind of the token to tok::unknown so that the preprocessor isn't
1962 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001963 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001964 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00001965 MI->AddTokenToBody(LastTok);
1966 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00001967 } else {
1968 Diag(Tok, diag::err_pp_stringize_not_parameter);
1969 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001970
Chris Lattner83bd8282009-05-25 17:16:10 +00001971 // Disable __VA_ARGS__ again.
1972 Ident__VA_ARGS__->setIsPoisoned(true);
1973 return;
1974 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001975 }
Mike Stump11289f42009-09-09 15:08:12 +00001976
Chris Lattner83bd8282009-05-25 17:16:10 +00001977 // Things look ok, add the '#' and param name tokens to the macro.
1978 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001979 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001980 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001981
Chris Lattnerf64b3522008-03-09 01:54:53 +00001982 // Get the next token of the macro.
1983 LexUnexpandedToken(Tok);
1984 }
1985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
1987
Chris Lattnerf64b3522008-03-09 01:54:53 +00001988 // Disable __VA_ARGS__ again.
1989 Ident__VA_ARGS__->setIsPoisoned(true);
1990
Chris Lattner57540c52011-04-15 05:22:18 +00001991 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001992 // replacement list.
1993 unsigned NumTokens = MI->getNumTokens();
1994 if (NumTokens != 0) {
1995 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1996 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001997 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001998 return;
1999 }
2000 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2001 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002002 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002003 return;
2004 }
2005 }
Mike Stump11289f42009-09-09 15:08:12 +00002006
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002007 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002008
Chris Lattnerf64b3522008-03-09 01:54:53 +00002009 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002010 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002011 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00002012 // It is very common for system headers to have tons of macro redefinitions
2013 // and for warnings to be disabled in system headers. If this is the case,
2014 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002015 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002016 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002017 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002018 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002019
Richard Smith7b242542013-03-06 00:46:00 +00002020 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2021 // C++ [cpp.predefined]p4, but allow it as an extension.
2022 if (OtherMI->isBuiltinMacro())
2023 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002024 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002025 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002026 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002027 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002028 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2029 << MacroNameTok.getIdentifierInfo();
2030 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2031 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002032 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002033 if (OtherMI->isWarnIfUnused())
2034 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002035 }
Mike Stump11289f42009-09-09 15:08:12 +00002036
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002037 DefMacroDirective *MD =
2038 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002039
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002040 assert(!MI->isUsed());
2041 // If we need warning for not using the macro, add its location in the
2042 // warn-because-unused-macro set. If it gets used it will be removed from set.
2043 if (isInPrimaryFile() && // don't warn for include'd macros.
2044 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00002045 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002046 MI->setIsWarnIfUnused(true);
2047 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2048 }
2049
Chris Lattner928e9092009-04-12 01:39:54 +00002050 // If the callbacks want to know, tell them about the macro definition.
2051 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002052 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002053}
2054
James Dennettf6333ac2012-06-22 05:46:07 +00002055/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002056///
2057void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2058 ++NumUndefined;
2059
2060 Token MacroNameTok;
2061 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00002062
Chris Lattnerf64b3522008-03-09 01:54:53 +00002063 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002064 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002065 return;
Mike Stump11289f42009-09-09 15:08:12 +00002066
Chris Lattnerf64b3522008-03-09 01:54:53 +00002067 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002068 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002069
Chris Lattnerf64b3522008-03-09 01:54:53 +00002070 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002071 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002072 const MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Mike Stump11289f42009-09-09 15:08:12 +00002073
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002074 // If the callbacks want to know, tell them about the macro #undef.
2075 // Note: no matter if the macro was defined or not.
2076 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002077 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002078
Chris Lattnerf64b3522008-03-09 01:54:53 +00002079 // If the macro is not defined, this is a noop undef, just return.
2080 if (MI == 0) return;
2081
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002082 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002083 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002084
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002085 if (MI->isWarnIfUnused())
2086 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2087
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002088 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2089 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002090}
2091
2092
2093//===----------------------------------------------------------------------===//
2094// Preprocessor Conditional Directive Handling.
2095//===----------------------------------------------------------------------===//
2096
James Dennettf6333ac2012-06-22 05:46:07 +00002097/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2098/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2099/// true if any tokens have been returned or pp-directives activated before this
2100/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002101///
2102void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2103 bool ReadAnyTokensBeforeDirective) {
2104 ++NumIf;
2105 Token DirectiveTok = Result;
2106
2107 Token MacroNameTok;
2108 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002109
Chris Lattnerf64b3522008-03-09 01:54:53 +00002110 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002111 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002112 // Skip code until we get to #endif. This helps with recovery by not
2113 // emitting an error when the #endif is reached.
2114 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2115 /*Foundnonskip*/false, /*FoundElse*/false);
2116 return;
2117 }
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattnerf64b3522008-03-09 01:54:53 +00002119 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002120 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002121
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002122 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002123 MacroDirective *MD = getMacroDirective(MII);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002124 MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002125
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002126 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002127 // If the start of a top-level #ifdef and if the macro is not defined,
2128 // inform MIOpt that this might be the start of a proper include guard.
2129 // Otherwise it is some other form of unknown conditional which we can't
2130 // handle.
2131 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002132 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002133 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002134 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002135 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002136 }
2137
Chris Lattnerf64b3522008-03-09 01:54:53 +00002138 // If there is a macro, process it.
2139 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002140 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002141
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002142 if (Callbacks) {
2143 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002144 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002145 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002146 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002147 }
2148
Chris Lattnerf64b3522008-03-09 01:54:53 +00002149 // Should we include the stuff contained by this directive?
2150 if (!MI == isIfndef) {
2151 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002152 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2153 /*wasskip*/false, /*foundnonskip*/true,
2154 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002155 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002156 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002157 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002158 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002159 /*FoundElse*/false);
2160 }
2161}
2162
James Dennettf6333ac2012-06-22 05:46:07 +00002163/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002164///
2165void Preprocessor::HandleIfDirective(Token &IfToken,
2166 bool ReadAnyTokensBeforeDirective) {
2167 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002168
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002169 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002170 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002171 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2172 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2173 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002174
2175 // If this condition is equivalent to #ifndef X, and if this is the first
2176 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002177 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002178 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002179 // FIXME: Pass in the location of the macro name, not the 'if' token.
2180 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002181 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002182 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002183 }
2184
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002185 if (Callbacks)
2186 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002187 SourceRange(ConditionalBegin, ConditionalEnd),
2188 ConditionalTrue);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002189
Chris Lattnerf64b3522008-03-09 01:54:53 +00002190 // Should we include the stuff contained by this directive?
2191 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002192 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002193 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002194 /*foundnonskip*/true, /*foundelse*/false);
2195 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002196 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002197 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002198 /*FoundElse*/false);
2199 }
2200}
2201
James Dennettf6333ac2012-06-22 05:46:07 +00002202/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002203///
2204void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2205 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002206
Chris Lattnerf64b3522008-03-09 01:54:53 +00002207 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002208 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002209
Chris Lattnerf64b3522008-03-09 01:54:53 +00002210 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002211 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002212 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002213 Diag(EndifToken, diag::err_pp_endif_without_if);
2214 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002215 }
Mike Stump11289f42009-09-09 15:08:12 +00002216
Chris Lattnerf64b3522008-03-09 01:54:53 +00002217 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002218 if (CurPPLexer->getConditionalStackDepth() == 0)
2219 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002220
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002221 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002222 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002223
2224 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002225 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002226}
2227
James Dennettf6333ac2012-06-22 05:46:07 +00002228/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002229///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002230void Preprocessor::HandleElseDirective(Token &Result) {
2231 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002232
Chris Lattnerf64b3522008-03-09 01:54:53 +00002233 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002234 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002235
Chris Lattnerf64b3522008-03-09 01:54:53 +00002236 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002237 if (CurPPLexer->popConditionalLevel(CI)) {
2238 Diag(Result, diag::pp_err_else_without_if);
2239 return;
2240 }
Mike Stump11289f42009-09-09 15:08:12 +00002241
Chris Lattnerf64b3522008-03-09 01:54:53 +00002242 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002243 if (CurPPLexer->getConditionalStackDepth() == 0)
2244 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002245
2246 // If this is a #else with a #else before it, report the error.
2247 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002248
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002249 if (Callbacks)
2250 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2251
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002252 // Finally, skip the rest of the contents of this block.
2253 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002254 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002255}
2256
James Dennettf6333ac2012-06-22 05:46:07 +00002257/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002258///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002259void Preprocessor::HandleElifDirective(Token &ElifToken) {
2260 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002261
Chris Lattnerf64b3522008-03-09 01:54:53 +00002262 // #elif directive in a non-skipping conditional... start skipping.
2263 // We don't care what the condition is, because we will always skip it (since
2264 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002265 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002266 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002267 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002268
2269 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002270 if (CurPPLexer->popConditionalLevel(CI)) {
2271 Diag(ElifToken, diag::pp_err_elif_without_if);
2272 return;
2273 }
Mike Stump11289f42009-09-09 15:08:12 +00002274
Chris Lattnerf64b3522008-03-09 01:54:53 +00002275 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002276 if (CurPPLexer->getConditionalStackDepth() == 0)
2277 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002278
Chris Lattnerf64b3522008-03-09 01:54:53 +00002279 // If this is a #elif with a #else before it, report the error.
2280 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002281
2282 if (Callbacks)
2283 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002284 SourceRange(ConditionalBegin, ConditionalEnd),
2285 true, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002286
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002287 // Finally, skip the rest of the contents of this block.
2288 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002289 /*FoundElse*/CI.FoundElse,
2290 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002291}