blob: 3e3312a9261a60f7c78bd821ee482890f89071bc [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattnerf64b3522008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner710bb872009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/LexDiagnostic.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/ModuleLoader.h"
24#include "clang/Lex/Pragma.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000025#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000026#include "llvm/Support/ErrorHandling.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000027#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000028using namespace clang;
29
30//===----------------------------------------------------------------------===//
31// Utility Methods for Preprocessor Directive Handling.
32//===----------------------------------------------------------------------===//
33
Chris Lattnerc0a585d2010-08-17 15:55:45 +000034MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000035 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000036
Ted Kremenekc8456f82010-10-19 22:15:20 +000037 if (MICache) {
38 MIChain = MICache;
39 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000040 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000041 else {
42 MIChain = BP.Allocate<MacroInfoChain>();
43 }
44
45 MIChain->Next = MIChainHead;
46 MIChain->Prev = 0;
47 if (MIChainHead)
48 MIChainHead->Prev = MIChain;
49 MIChainHead = MIChain;
50
51 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000052}
53
54MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
55 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000056 new (MI) MacroInfo(L);
57 return MI;
58}
59
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000060MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
61 unsigned SubModuleID) {
62 LLVM_STATIC_ASSERT(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
63 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000064 DeserializedMacroInfoChain *MIChain =
65 BP.Allocate<DeserializedMacroInfoChain>();
66 MIChain->Next = DeserialMIChainHead;
67 DeserialMIChainHead = MIChain;
68
69 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000070 new (MI) MacroInfo(L);
71 MI->FromASTFile = true;
72 MI->setOwningModuleID(SubModuleID);
73 return MI;
74}
75
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000076DefMacroDirective *
77Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc,
78 bool isImported) {
79 DefMacroDirective *MD = BP.Allocate<DefMacroDirective>();
80 new (MD) DefMacroDirective(MI, Loc, isImported);
81 return MD;
82}
83
84UndefMacroDirective *
85Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
86 UndefMacroDirective *MD = BP.Allocate<UndefMacroDirective>();
87 new (MD) UndefMacroDirective(UndefLoc);
88 return MD;
89}
90
91VisibilityMacroDirective *
92Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
93 bool isPublic) {
94 VisibilityMacroDirective *MD = BP.Allocate<VisibilityMacroDirective>();
95 new (MD) VisibilityMacroDirective(Loc, isPublic);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000096 return MD;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000097}
98
James Dennettf6333ac2012-06-22 05:46:07 +000099/// \brief Release the specified MacroInfo to be reused for allocating
100/// new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +0000101void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +0000102 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
103 if (MacroInfoChain *Prev = MIChain->Prev) {
104 MacroInfoChain *Next = MIChain->Next;
105 Prev->Next = Next;
106 if (Next)
107 Next->Prev = Prev;
108 }
109 else {
110 assert(MIChainHead == MIChain);
111 MIChainHead = MIChain->Next;
112 MIChainHead->Prev = 0;
113 }
114 MIChain->Next = MICache;
115 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +0000116
Ted Kremenekc8456f82010-10-19 22:15:20 +0000117 MI->Destroy();
118}
Chris Lattner666f7a42009-02-20 22:19:20 +0000119
James Dennettf6333ac2012-06-22 05:46:07 +0000120/// \brief Read and discard all tokens remaining on the current line until
121/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000122void Preprocessor::DiscardUntilEndOfDirective() {
123 Token Tmp;
124 do {
125 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000126 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000127 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000128}
129
James Dennettf6333ac2012-06-22 05:46:07 +0000130/// \brief Lex and validate a macro name, which occurs after a
131/// \#define or \#undef.
132///
133/// This sets the token kind to eod and discards the rest
134/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
135/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
136/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000137void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
138 // Read the token, don't allow macro expansion on it.
139 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000140
Douglas Gregor12785102010-08-24 20:21:13 +0000141 if (MacroNameTok.is(tok::code_completion)) {
142 if (CodeComplete)
143 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000144 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000145 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000146 }
147
Chris Lattnerf64b3522008-03-09 01:54:53 +0000148 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000149 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000150 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
151 return;
152 }
Mike Stump11289f42009-09-09 15:08:12 +0000153
Chris Lattnerf64b3522008-03-09 01:54:53 +0000154 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
155 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000156 bool Invalid = false;
157 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
158 if (Invalid)
159 return;
Nico Weber2e686202012-02-29 22:54:43 +0000160
Chris Lattner77c76ae2008-12-13 20:12:40 +0000161 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000162
163 // Allow #defining |and| and friends in microsoft mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000164 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weber2e686202012-02-29 22:54:43 +0000165 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
166 return;
167 }
168
Chris Lattner77c76ae2008-12-13 20:12:40 +0000169 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000170 // C++ 2.5p2: Alternative tokens behave the same as its primary token
171 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000172 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000173 else
174 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
175 // Fall through on error.
176 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Richard Smith7b242542013-03-06 00:46:00 +0000177 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000178 Diag(MacroNameTok, diag::err_defined_macro_name);
Richard Smith7b242542013-03-06 00:46:00 +0000179 } else if (isDefineUndef == 2 && II->hasMacroDefinition() &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000180 getMacroInfo(II)->isBuiltinMacro()) {
Richard Smith7b242542013-03-06 00:46:00 +0000181 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
182 // and C++ [cpp.predefined]p4], but allow it as an extension.
183 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
184 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000185 } else {
186 // Okay, we got a good identifier node. Return it.
187 return;
188 }
Mike Stump11289f42009-09-09 15:08:12 +0000189
Chris Lattnerf64b3522008-03-09 01:54:53 +0000190 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000191 // token kind to tok::eod.
192 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000193 return DiscardUntilEndOfDirective();
194}
195
James Dennettf6333ac2012-06-22 05:46:07 +0000196/// \brief Ensure that the next token is a tok::eod token.
197///
198/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000199/// true, then we consider macros that expand to zero tokens as being ok.
200void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000201 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000202 // Lex unexpanded tokens for most directives: macros might expand to zero
203 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
204 // #line) allow empty macros.
205 if (EnableMacros)
206 Lex(Tmp);
207 else
208 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000209
Chris Lattnerf64b3522008-03-09 01:54:53 +0000210 // There should be no tokens after the directive, but we allow them as an
211 // extension.
212 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
213 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000214
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000215 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000216 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000217 // or if this is a macro-style preprocessing directive, because it is more
218 // trouble than it is worth to insert /**/ and check that there is no /**/
219 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000220 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000221 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000222 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000223 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
224 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000225 DiscardUntilEndOfDirective();
226 }
227}
228
229
230
James Dennettf6333ac2012-06-22 05:46:07 +0000231/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
232/// decided that the subsequent tokens are in the \#if'd out portion of the
233/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000234/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000235/// this \#if directive, so \#else/\#elif blocks should never be entered.
236/// If ElseOk is true, then \#else directives are ok, if not, then we have
237/// already seen one so a \#else directive is a duplicate. When this returns,
238/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000239void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
240 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000241 bool FoundElse,
242 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000243 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000244 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000245
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000246 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000247 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000248
Ted Kremenek56572ab2008-12-12 18:34:08 +0000249 if (CurPTHLexer) {
250 PTHSkipExcludedConditionalBlock();
251 return;
252 }
Mike Stump11289f42009-09-09 15:08:12 +0000253
Chris Lattnerf64b3522008-03-09 01:54:53 +0000254 // Enter raw mode to disable identifier lookup (and thus macro expansion),
255 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000256 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000257 Token Tok;
258 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000259 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000260
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000261 if (Tok.is(tok::code_completion)) {
262 if (CodeComplete)
263 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000264 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000265 continue;
266 }
267
Chris Lattnerf64b3522008-03-09 01:54:53 +0000268 // If this is the end of the buffer, we have an error.
269 if (Tok.is(tok::eof)) {
270 // Emit errors for each unterminated conditional on the stack, including
271 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000272 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000273 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000274 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
275 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000276 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000277 }
278
Chris Lattnerf64b3522008-03-09 01:54:53 +0000279 // Just return and let the caller lex after this #include.
280 break;
281 }
Mike Stump11289f42009-09-09 15:08:12 +0000282
Chris Lattnerf64b3522008-03-09 01:54:53 +0000283 // If this token is not a preprocessor directive, just skip it.
284 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
285 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000286
Chris Lattnerf64b3522008-03-09 01:54:53 +0000287 // We just parsed a # character at the start of a line, so we're in
288 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000289 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000290 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000291 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000292
Mike Stump11289f42009-09-09 15:08:12 +0000293
Chris Lattnerf64b3522008-03-09 01:54:53 +0000294 // Read the next token, the directive flavor.
295 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000296
Chris Lattnerf64b3522008-03-09 01:54:53 +0000297 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
298 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000299 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000300 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000301 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000302 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000303 continue;
304 }
305
306 // If the first letter isn't i or e, it isn't intesting to us. We know that
307 // this is safe in the face of spelling differences, because there is no way
308 // to spell an i/e in a strange way that is another letter. Skipping this
309 // allows us to avoid looking up the identifier info for #define/#undef and
310 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000311 const char *RawCharData = Tok.getRawIdentifierData();
312
Chris Lattnerf64b3522008-03-09 01:54:53 +0000313 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000314 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000315 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000316 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000317 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000318 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000319 continue;
320 }
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chris Lattnerf64b3522008-03-09 01:54:53 +0000322 // Get the identifier name without trigraphs or embedded newlines. Note
323 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
324 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000325 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000326 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000327 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000328 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 } else {
330 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000331 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000332 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000333 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000334 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000335 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000336 continue;
337 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000338 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000339 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000340 }
Mike Stump11289f42009-09-09 15:08:12 +0000341
Benjamin Kramer144884642009-12-31 13:32:38 +0000342 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000343 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000344 if (Sub.empty() || // "if"
345 Sub == "def" || // "ifdef"
346 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000347 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
348 // bother parsing the condition.
349 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000350 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000351 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000352 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000353 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000354 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000355 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000356 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000357 PPConditionalInfo CondInfo;
358 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000359 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000360 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000361 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000362
Chris Lattnerf64b3522008-03-09 01:54:53 +0000363 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000364 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000365 // Restore the value of LexingRawMode so that trailing comments
366 // are handled correctly, if we've reached the outermost block.
367 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000368 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000369 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000370 if (Callbacks)
371 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000372 break;
Richard Smithd0124572012-06-21 00:35:03 +0000373 } else {
374 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000375 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000376 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000377 // #else directive in a skipping conditional. If not in some other
378 // skipping conditional, and if #else hasn't already been seen, enter it
379 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000380 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000381
Chris Lattnerf64b3522008-03-09 01:54:53 +0000382 // If this is a #else with a #else before it, report the error.
383 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000384
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385 // Note that we've seen a #else in this conditional.
386 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000387
Chris Lattnerf64b3522008-03-09 01:54:53 +0000388 // If the conditional is at the top level, and the #if block wasn't
389 // entered, enter the #else block now.
390 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
391 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000392 // Restore the value of LexingRawMode so that trailing comments
393 // are handled correctly.
394 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000395 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000396 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000397 if (Callbacks)
398 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000399 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000400 } else {
401 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000402 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000403 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000404 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000405
406 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000407 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000408 // If this is in a skipping block or if we're already handled this #if
409 // block, don't bother parsing the condition.
410 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
411 DiscardUntilEndOfDirective();
412 ShouldEnter = false;
413 } else {
414 // Restore the value of LexingRawMode so that identifiers are
415 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000416 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
417 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000418 IdentifierInfo *IfNDefMacro = 0;
419 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000420 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000421 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000422 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattnerf64b3522008-03-09 01:54:53 +0000424 // If this is a #elif with a #else before it, report the error.
425 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000426
Chris Lattnerf64b3522008-03-09 01:54:53 +0000427 // If this condition is true, enter it!
428 if (ShouldEnter) {
429 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000430 if (Callbacks)
431 Callbacks->Elif(Tok.getLocation(),
432 SourceRange(ConditionalBegin, ConditionalEnd),
433 CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000434 break;
435 }
436 }
437 }
Mike Stump11289f42009-09-09 15:08:12 +0000438
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000439 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000440 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000441 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000442 }
443
444 // Finally, if we are out of the conditional (saw an #endif or ran off the end
445 // of the file, just stop skipping and return to lexing whatever came after
446 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000447 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000448
449 if (Callbacks) {
450 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
451 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
452 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000453}
454
Ted Kremenek56572ab2008-12-12 18:34:08 +0000455void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000456
457 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000458 assert(CurPTHLexer);
459 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000460
Ted Kremenek56572ab2008-12-12 18:34:08 +0000461 // Skip to the next '#else', '#elif', or #endif.
462 if (CurPTHLexer->SkipBlock()) {
463 // We have reached an #endif. Both the '#' and 'endif' tokens
464 // have been consumed by the PTHLexer. Just pop off the condition level.
465 PPConditionalInfo CondInfo;
466 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000467 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000468 assert(!InCond && "Can't be skipping if not in a conditional!");
469 break;
470 }
Mike Stump11289f42009-09-09 15:08:12 +0000471
Ted Kremenek56572ab2008-12-12 18:34:08 +0000472 // We have reached a '#else' or '#elif'. Lex the next token to get
473 // the directive flavor.
474 Token Tok;
475 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000476
Ted Kremenek56572ab2008-12-12 18:34:08 +0000477 // We can actually look up the IdentifierInfo here since we aren't in
478 // raw mode.
479 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
480
481 if (K == tok::pp_else) {
482 // #else: Enter the else condition. We aren't in a nested condition
483 // since we skip those. We're always in the one matching the last
484 // blocked we skipped.
485 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
486 // Note that we've seen a #else in this conditional.
487 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000488
Ted Kremenek56572ab2008-12-12 18:34:08 +0000489 // If the #if block wasn't entered then enter the #else block now.
490 if (!CondInfo.FoundNonSkip) {
491 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000492
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000493 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000494 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000495 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000496 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000497
Ted Kremenek56572ab2008-12-12 18:34:08 +0000498 break;
499 }
Mike Stump11289f42009-09-09 15:08:12 +0000500
Ted Kremenek56572ab2008-12-12 18:34:08 +0000501 // Otherwise skip this block.
502 continue;
503 }
Mike Stump11289f42009-09-09 15:08:12 +0000504
Ted Kremenek56572ab2008-12-12 18:34:08 +0000505 assert(K == tok::pp_elif);
506 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
507
508 // If this is a #elif with a #else before it, report the error.
509 if (CondInfo.FoundElse)
510 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000511
Ted Kremenek56572ab2008-12-12 18:34:08 +0000512 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000513 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000514 if (CondInfo.FoundNonSkip)
515 continue;
516
517 // Evaluate the condition of the #elif.
518 IdentifierInfo *IfNDefMacro = 0;
519 CurPTHLexer->ParsingPreprocessorDirective = true;
520 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
521 CurPTHLexer->ParsingPreprocessorDirective = false;
522
523 // If this condition is true, enter it!
524 if (ShouldEnter) {
525 CondInfo.FoundNonSkip = true;
526 break;
527 }
528
529 // Otherwise, skip this block and go to the next one.
530 continue;
531 }
532}
533
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000534const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000535 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000536 bool isAngled,
537 const DirectoryLookup *FromDir,
538 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000539 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000540 SmallVectorImpl<char> *RelativePath,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000541 Module **SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000542 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000543 // If the header lookup mechanism may be relative to the current file, pass in
544 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000545 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000546 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000547 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000548 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattner022923a2009-02-04 19:45:07 +0000550 // If there is no file entry associated with this file, it must be the
551 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000552 // it won't be scanned for preprocessor directives. If we have the
553 // predefines buffer, resolve #include references (which come from the
554 // -include command line argument) as if they came from the main file, this
555 // affects file lookup etc.
556 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000557 FID = SourceMgr.getMainFileID();
558 CurFileEnt = SourceMgr.getFileEntryForID(FID);
559 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000560 }
Mike Stump11289f42009-09-09 15:08:12 +0000561
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000562 // Do a standard file entry lookup.
563 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000564 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000565 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000566 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerfde85352010-01-22 00:14:44 +0000567 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000568
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000569 // Otherwise, see if this is a subframework header. If so, this is relative
570 // to one of the headers on the #include stack. Walk the list of the current
571 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000572 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000573 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000574 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000575 SearchPath, RelativePath,
576 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000577 return FE;
578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000580 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
581 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000582 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000583 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000584 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000585 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000586 Filename, CurFileEnt, SearchPath, RelativePath,
587 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000588 return FE;
589 }
590 }
Mike Stump11289f42009-09-09 15:08:12 +0000591
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000592 // Otherwise, we really couldn't find the file.
593 return 0;
594}
595
Chris Lattnerf64b3522008-03-09 01:54:53 +0000596
597//===----------------------------------------------------------------------===//
598// Preprocessor Directive Handling.
599//===----------------------------------------------------------------------===//
600
David Blaikied5321242012-06-06 18:52:13 +0000601class Preprocessor::ResetMacroExpansionHelper {
602public:
603 ResetMacroExpansionHelper(Preprocessor *pp)
604 : PP(pp), save(pp->DisableMacroExpansion) {
605 if (pp->MacroExpansionInDirectivesOverride)
606 pp->DisableMacroExpansion = false;
607 }
608 ~ResetMacroExpansionHelper() {
609 PP->DisableMacroExpansion = save;
610 }
611private:
612 Preprocessor *PP;
613 bool save;
614};
615
Chris Lattnerf64b3522008-03-09 01:54:53 +0000616/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000617/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000618/// lexer/preprocessor state, and advances the lexer(s) so that the next token
619/// read is the correct one.
620void Preprocessor::HandleDirective(Token &Result) {
621 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000622
Chris Lattnerf64b3522008-03-09 01:54:53 +0000623 // We just parsed a # character at the start of a line, so we're in directive
624 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000625 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000626 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000627 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000628
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000629 bool ImmediatelyAfterTopLevelIfndef =
630 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
631 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
632
Chris Lattnerf64b3522008-03-09 01:54:53 +0000633 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000634
Chris Lattnerf64b3522008-03-09 01:54:53 +0000635 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000636 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000637 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000638 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000639
Chris Lattner2d17ab72009-03-18 21:00:25 +0000640 // Save the '#' token in case we need to return it later.
641 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000642
Chris Lattnerf64b3522008-03-09 01:54:53 +0000643 // Read the next token, the directive flavor. This isn't expanded due to
644 // C99 6.10.3p8.
645 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattnerf64b3522008-03-09 01:54:53 +0000647 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
648 // #define A(x) #x
649 // A(abc
650 // #warning blah
651 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000652 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
653 // not support this for #include-like directives, since that can result in
654 // terrible diagnostics, and does not work in GCC.
655 if (InMacroArgs) {
656 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
657 switch (II->getPPKeywordID()) {
658 case tok::pp_include:
659 case tok::pp_import:
660 case tok::pp_include_next:
661 case tok::pp___include_macros:
662 Diag(Result, diag::err_embedded_include) << II->getName();
663 DiscardUntilEndOfDirective();
664 return;
665 default:
666 break;
667 }
668 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000669 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000670 }
Mike Stump11289f42009-09-09 15:08:12 +0000671
David Blaikied5321242012-06-06 18:52:13 +0000672 // Temporarily enable macro expansion if set so
673 // and reset to previous state when returning from this function.
674 ResetMacroExpansionHelper helper(this);
675
Chris Lattnerf64b3522008-03-09 01:54:53 +0000676 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000677 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000678 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000679 case tok::code_completion:
680 if (CodeComplete)
681 CodeComplete->CodeCompleteDirective(
682 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000683 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000684 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000685 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000686 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000687 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000688 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000689 default:
690 IdentifierInfo *II = Result.getIdentifierInfo();
691 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000692
Chris Lattnerf64b3522008-03-09 01:54:53 +0000693 // Ask what the preprocessor keyword ID is.
694 switch (II->getPPKeywordID()) {
695 default: break;
696 // C99 6.10.1 - Conditional Inclusion.
697 case tok::pp_if:
698 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
699 case tok::pp_ifdef:
700 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
701 case tok::pp_ifndef:
702 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
703 case tok::pp_elif:
704 return HandleElifDirective(Result);
705 case tok::pp_else:
706 return HandleElseDirective(Result);
707 case tok::pp_endif:
708 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000709
Chris Lattnerf64b3522008-03-09 01:54:53 +0000710 // C99 6.10.2 - Source File Inclusion.
711 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000712 // Handle #include.
713 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000714 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000715 // Handle -imacros.
716 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000717
Chris Lattnerf64b3522008-03-09 01:54:53 +0000718 // C99 6.10.3 - Macro Replacement.
719 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000720 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000721 case tok::pp_undef:
722 return HandleUndefDirective(Result);
723
724 // C99 6.10.4 - Line Control.
725 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000726 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000727
Chris Lattnerf64b3522008-03-09 01:54:53 +0000728 // C99 6.10.5 - Error Directive.
729 case tok::pp_error:
730 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000731
Chris Lattnerf64b3522008-03-09 01:54:53 +0000732 // C99 6.10.6 - Pragma Directive.
733 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000734 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattnerf64b3522008-03-09 01:54:53 +0000736 // GNU Extensions.
737 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000738 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000739 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000740 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000741
Chris Lattnerf64b3522008-03-09 01:54:53 +0000742 case tok::pp_warning:
743 Diag(Result, diag::ext_pp_warning_directive);
744 return HandleUserDiagnosticDirective(Result, true);
745 case tok::pp_ident:
746 return HandleIdentSCCSDirective(Result);
747 case tok::pp_sccs:
748 return HandleIdentSCCSDirective(Result);
749 case tok::pp_assert:
750 //isExtension = true; // FIXME: implement #assert
751 break;
752 case tok::pp_unassert:
753 //isExtension = true; // FIXME: implement #unassert
754 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000755
Douglas Gregor663b48f2012-01-03 19:48:16 +0000756 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000757 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000758 return HandleMacroPublicDirective(Result);
759 break;
760
Douglas Gregor663b48f2012-01-03 19:48:16 +0000761 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000762 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000763 return HandleMacroPrivateDirective(Result);
764 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000765 }
766 break;
767 }
Mike Stump11289f42009-09-09 15:08:12 +0000768
Chris Lattner2d17ab72009-03-18 21:00:25 +0000769 // If this is a .S file, treat unknown # directives as non-preprocessor
770 // directives. This is important because # may be a comment or introduce
771 // various pseudo-ops. Just return the # token and push back the following
772 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000773 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000774 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000775 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000776 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000777 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000778
779 // If the second token is a hashhash token, then we need to translate it to
780 // unknown so the token lexer doesn't try to perform token pasting.
781 if (Result.is(tok::hashhash))
782 Toks[1].setKind(tok::unknown);
783
Chris Lattner2d17ab72009-03-18 21:00:25 +0000784 // Enter this token stream so that we re-lex the tokens. Make sure to
785 // enable macro expansion, in case the token after the # is an identifier
786 // that is expanded.
787 EnterTokenStream(Toks, 2, false, true);
788 return;
789 }
Mike Stump11289f42009-09-09 15:08:12 +0000790
Chris Lattnerf64b3522008-03-09 01:54:53 +0000791 // If we reached here, the preprocessing token is not valid!
792 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000793
Chris Lattnerf64b3522008-03-09 01:54:53 +0000794 // Read the rest of the PP line.
795 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000796
Chris Lattnerf64b3522008-03-09 01:54:53 +0000797 // Okay, we're done parsing the directive.
798}
799
Chris Lattner76e68962009-01-26 06:19:46 +0000800/// GetLineValue - Convert a numeric token into an unsigned value, emitting
801/// Diagnostic DiagID if it is invalid, and returning the value in Val.
802static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000803 unsigned DiagID, Preprocessor &PP,
804 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000805 if (DigitTok.isNot(tok::numeric_constant)) {
806 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000807
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000808 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000809 PP.DiscardUntilEndOfDirective();
810 return true;
811 }
Mike Stump11289f42009-09-09 15:08:12 +0000812
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000813 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000814 IntegerBuffer.resize(DigitTok.getLength());
815 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000816 bool Invalid = false;
817 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
818 if (Invalid)
819 return true;
820
Chris Lattnerd66f1722009-04-18 18:35:15 +0000821 // Verify that we have a simple digit-sequence, and compute the value. This
822 // is always a simple digit string computed in decimal, so we do this manually
823 // here.
824 Val = 0;
825 for (unsigned i = 0; i != ActualLength; ++i) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000826 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000827 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000828 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000829 PP.DiscardUntilEndOfDirective();
830 return true;
831 }
Mike Stump11289f42009-09-09 15:08:12 +0000832
Chris Lattnerd66f1722009-04-18 18:35:15 +0000833 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
834 if (NextVal < Val) { // overflow.
835 PP.Diag(DigitTok, DiagID);
836 PP.DiscardUntilEndOfDirective();
837 return true;
838 }
839 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000840 }
Mike Stump11289f42009-09-09 15:08:12 +0000841
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000842 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000843 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
844 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000845
Chris Lattner76e68962009-01-26 06:19:46 +0000846 return false;
847}
848
James Dennettf6333ac2012-06-22 05:46:07 +0000849/// \brief Handle a \#line directive: C99 6.10.4.
850///
851/// The two acceptable forms are:
852/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000853/// # line digit-sequence
854/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000855/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000856void Preprocessor::HandleLineDirective(Token &Tok) {
857 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
858 // expanded.
859 Token DigitTok;
860 Lex(DigitTok);
861
Chris Lattner100c65e2009-01-26 05:29:08 +0000862 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000863 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000864 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000865 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000866
867 if (LineNo == 0)
868 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000869
Chris Lattner76e68962009-01-26 06:19:46 +0000870 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
871 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000872 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000873 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000874 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000875 if (LineNo >= LineLimit)
876 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000877 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000878 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000880 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000881 Token StrTok;
882 Lex(StrTok);
883
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000884 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
885 // string followed by eod.
886 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000887 ; // ok
888 else if (StrTok.isNot(tok::string_literal)) {
889 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000890 return DiscardUntilEndOfDirective();
891 } else if (StrTok.hasUDSuffix()) {
892 Diag(StrTok, diag::err_invalid_string_udl);
893 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000894 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000895 // Parse and validate the string, converting it into a unique ID.
896 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000897 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000898 if (Literal.hadError)
899 return DiscardUntilEndOfDirective();
900 if (Literal.Pascal) {
901 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
902 return DiscardUntilEndOfDirective();
903 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000904 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000905
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000906 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000907 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
908 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000909 }
Mike Stump11289f42009-09-09 15:08:12 +0000910
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000911 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000912
Chris Lattner839150e2009-03-27 17:13:49 +0000913 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000914 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
915 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000916 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000917}
918
Chris Lattner76e68962009-01-26 06:19:46 +0000919/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
920/// marker directive.
921static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
922 bool &IsSystemHeader, bool &IsExternCHeader,
923 Preprocessor &PP) {
924 unsigned FlagVal;
925 Token FlagTok;
926 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000927 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000928 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
929 return true;
930
931 if (FlagVal == 1) {
932 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000933
Chris Lattner76e68962009-01-26 06:19:46 +0000934 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000935 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000936 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
937 return true;
938 } else if (FlagVal == 2) {
939 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattner1c967782009-02-04 06:25:26 +0000941 SourceManager &SM = PP.getSourceManager();
942 // If we are leaving the current presumed file, check to make sure the
943 // presumed include stack isn't empty!
944 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000945 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000946 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000947 if (PLoc.isInvalid())
948 return true;
949
Chris Lattner1c967782009-02-04 06:25:26 +0000950 // If there is no include loc (main file) or if the include loc is in a
951 // different physical file, then we aren't in a "1" line marker flag region.
952 SourceLocation IncLoc = PLoc.getIncludeLoc();
953 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000954 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000955 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
956 PP.DiscardUntilEndOfDirective();
957 return true;
958 }
Mike Stump11289f42009-09-09 15:08:12 +0000959
Chris Lattner76e68962009-01-26 06:19:46 +0000960 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000961 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000962 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
963 return true;
964 }
965
966 // We must have 3 if there are still flags.
967 if (FlagVal != 3) {
968 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000969 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000970 return true;
971 }
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattner76e68962009-01-26 06:19:46 +0000973 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattner76e68962009-01-26 06:19:46 +0000975 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000976 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000977 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000978 return true;
979
980 // We must have 4 if there is yet another flag.
981 if (FlagVal != 4) {
982 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000983 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000984 return true;
985 }
Mike Stump11289f42009-09-09 15:08:12 +0000986
Chris Lattner76e68962009-01-26 06:19:46 +0000987 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000988
Chris Lattner76e68962009-01-26 06:19:46 +0000989 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000990 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000991
992 // There are no more valid flags here.
993 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000994 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000995 return true;
996}
997
998/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
999/// one of the following forms:
1000///
1001/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001002/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001003/// # 42 "file" ('1' | '2')? '3' '4'?
1004///
1005void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1006 // Validate the number and convert it to an unsigned. GNU does not have a
1007 // line # limit other than it fit in 32-bits.
1008 unsigned LineNo;
1009 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001010 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001011 return;
Mike Stump11289f42009-09-09 15:08:12 +00001012
Chris Lattner76e68962009-01-26 06:19:46 +00001013 Token StrTok;
1014 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001015
Chris Lattner76e68962009-01-26 06:19:46 +00001016 bool IsFileEntry = false, IsFileExit = false;
1017 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001018 int FilenameID = -1;
1019
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001020 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1021 // string followed by eod.
1022 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001023 ; // ok
1024 else if (StrTok.isNot(tok::string_literal)) {
1025 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001026 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001027 } else if (StrTok.hasUDSuffix()) {
1028 Diag(StrTok, diag::err_invalid_string_udl);
1029 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001030 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001031 // Parse and validate the string, converting it into a unique ID.
1032 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001033 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001034 if (Literal.hadError)
1035 return DiscardUntilEndOfDirective();
1036 if (Literal.Pascal) {
1037 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1038 return DiscardUntilEndOfDirective();
1039 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001040 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001041
Chris Lattner76e68962009-01-26 06:19:46 +00001042 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001043 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001044 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001045 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001046 }
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001048 // Create a line note with this information.
1049 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001050 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001051 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Chris Lattner839150e2009-03-27 17:13:49 +00001053 // If the preprocessor has callbacks installed, notify them of the #line
1054 // change. This is used so that the line marker comes out in -E mode for
1055 // example.
1056 if (Callbacks) {
1057 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1058 if (IsFileEntry)
1059 Reason = PPCallbacks::EnterFile;
1060 else if (IsFileExit)
1061 Reason = PPCallbacks::ExitFile;
1062 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1063 if (IsExternCHeader)
1064 FileKind = SrcMgr::C_ExternCSystem;
1065 else if (IsSystemHeader)
1066 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001067
Chris Lattnerc745cec2010-04-14 04:28:50 +00001068 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001069 }
Chris Lattner76e68962009-01-26 06:19:46 +00001070}
1071
1072
Chris Lattner38d7fd22009-01-26 05:30:54 +00001073/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1074///
Mike Stump11289f42009-09-09 15:08:12 +00001075void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001076 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001077 // PTH doesn't emit #warning or #error directives.
1078 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001079 return CurPTHLexer->DiscardToEndOfLine();
1080
Chris Lattnerf64b3522008-03-09 01:54:53 +00001081 // Read the rest of the line raw. We do this because we don't want macros
1082 // to be expanded and we don't require that the tokens be valid preprocessing
1083 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1084 // collapse multiple consequtive white space between tokens, but this isn't
1085 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001086 SmallString<128> Message;
1087 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001088
1089 // Find the first non-whitespace character, so that we can make the
1090 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001091 StringRef Msg = Message.str().ltrim(" ");
1092
Chris Lattner100c65e2009-01-26 05:29:08 +00001093 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001094 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001095 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001096 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001097}
1098
1099/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1100///
1101void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1102 // Yes, this directive is an extension.
1103 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001104
Chris Lattnerf64b3522008-03-09 01:54:53 +00001105 // Read the string argument.
1106 Token StrTok;
1107 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001108
Chris Lattnerf64b3522008-03-09 01:54:53 +00001109 // If the token kind isn't a string, it's a malformed directive.
1110 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001111 StrTok.isNot(tok::wide_string_literal)) {
1112 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001113 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001114 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001115 return;
1116 }
Mike Stump11289f42009-09-09 15:08:12 +00001117
Richard Smithd67aea22012-03-06 03:21:47 +00001118 if (StrTok.hasUDSuffix()) {
1119 Diag(StrTok, diag::err_invalid_string_udl);
1120 return DiscardUntilEndOfDirective();
1121 }
1122
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001123 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001124 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001125
Douglas Gregordc970f02010-03-16 22:30:13 +00001126 if (Callbacks) {
1127 bool Invalid = false;
1128 std::string Str = getSpelling(StrTok, &Invalid);
1129 if (!Invalid)
1130 Callbacks->Ident(Tok.getLocation(), Str);
1131 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001132}
1133
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001134/// \brief Handle a #public directive.
1135void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001136 Token MacroNameTok;
1137 ReadMacroName(MacroNameTok, 2);
1138
1139 // Error reading macro name? If so, diagnostic already issued.
1140 if (MacroNameTok.is(tok::eod))
1141 return;
1142
Douglas Gregor663b48f2012-01-03 19:48:16 +00001143 // Check to see if this is the last token on the #__public_macro line.
1144 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001145
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001146 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001147 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001148 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001149
1150 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001151 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001152 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001153 return;
1154 }
1155
1156 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001157 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1158 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001159}
1160
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001161/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001162void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1163 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 #__private_macro line.
1171 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001172
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001173 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001174 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001175 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +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 Gregorebf00492011-10-17 15:32:29 +00001180 return;
1181 }
1182
1183 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001184 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1185 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001186}
1187
Chris Lattnerf64b3522008-03-09 01:54:53 +00001188//===----------------------------------------------------------------------===//
1189// Preprocessor Include Directive Handling.
1190//===----------------------------------------------------------------------===//
1191
1192/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001193/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001194/// true if the input filename was in <>'s or false if it were in ""'s. The
1195/// caller is expected to provide a buffer that is large enough to hold the
1196/// spelling of the filename, but is also expected to handle the case when
1197/// this method decides to use a different buffer.
1198bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001199 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001200 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001201 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001202
Chris Lattnerf64b3522008-03-09 01:54:53 +00001203 // Make sure the filename is <x> or "x".
1204 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001205 if (Buffer[0] == '<') {
1206 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001207 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001208 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001209 return true;
1210 }
1211 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001212 } else if (Buffer[0] == '"') {
1213 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001214 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001215 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001216 return true;
1217 }
1218 isAngled = false;
1219 } else {
1220 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001221 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001222 return true;
1223 }
Mike Stump11289f42009-09-09 15:08:12 +00001224
Chris Lattnerf64b3522008-03-09 01:54:53 +00001225 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001226 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001227 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001228 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001229 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001230 }
Mike Stump11289f42009-09-09 15:08:12 +00001231
Chris Lattnerf64b3522008-03-09 01:54:53 +00001232 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001233 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001234 return isAngled;
1235}
1236
James Dennettf6333ac2012-06-22 05:46:07 +00001237/// \brief Handle cases where the \#include name is expanded from a macro
1238/// as multiple tokens, which need to be glued together.
1239///
1240/// This occurs for code like:
1241/// \code
1242/// \#define FOO <a/b.h>
1243/// \#include FOO
1244/// \endcode
Chris Lattnerf64b3522008-03-09 01:54:53 +00001245/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1246///
1247/// This code concatenates and consumes tokens up to the '>' token. It returns
1248/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001249/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001250bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001251 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001252 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001253 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001254
John Thompsonb5353522009-10-30 13:49:06 +00001255 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001256 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001257 End = CurTok.getLocation();
1258
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001259 // FIXME: Provide code completion for #includes.
1260 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001261 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001262 Lex(CurTok);
1263 continue;
1264 }
1265
Chris Lattnerf64b3522008-03-09 01:54:53 +00001266 // Append the spelling of this token to the buffer. If there was a space
1267 // before it, add it now.
1268 if (CurTok.hasLeadingSpace())
1269 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001270
Chris Lattnerf64b3522008-03-09 01:54:53 +00001271 // Get the spelling of the token, directly into FilenameBuffer if possible.
1272 unsigned PreAppendSize = FilenameBuffer.size();
1273 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001274
Chris Lattnerf64b3522008-03-09 01:54:53 +00001275 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001276 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001277
Chris Lattnerf64b3522008-03-09 01:54:53 +00001278 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1279 if (BufPtr != &FilenameBuffer[PreAppendSize])
1280 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001281
Chris Lattnerf64b3522008-03-09 01:54:53 +00001282 // Resize FilenameBuffer to the correct size.
1283 if (CurTok.getLength() != ActualLen)
1284 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001285
Chris Lattnerf64b3522008-03-09 01:54:53 +00001286 // If we found the '>' marker, return success.
1287 if (CurTok.is(tok::greater))
1288 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001289
John Thompsonb5353522009-10-30 13:49:06 +00001290 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001291 }
1292
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001293 // If we hit the eod marker, emit an error and return true so that the caller
1294 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001295 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001296 return true;
1297}
1298
James Dennettf6333ac2012-06-22 05:46:07 +00001299/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1300/// the file to be included from the lexer, then include it! This is a common
1301/// routine with functionality shared between \#include, \#include_next and
1302/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001303/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001304void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1305 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001306 const DirectoryLookup *LookupFrom,
1307 bool isImport) {
1308
1309 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001310 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001311
Chris Lattnerf64b3522008-03-09 01:54:53 +00001312 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001313 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001314 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001315 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001316 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001317
Chris Lattnerf64b3522008-03-09 01:54:53 +00001318 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001319 case tok::eod:
1320 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001321 return;
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattnerf64b3522008-03-09 01:54:53 +00001323 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001324 case tok::string_literal:
1325 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001326 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001327 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001328 break;
Mike Stump11289f42009-09-09 15:08:12 +00001329
Chris Lattnerf64b3522008-03-09 01:54:53 +00001330 case tok::less:
1331 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1332 // case, glue the tokens together into FilenameBuffer and interpret those.
1333 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001334 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001335 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001336 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001337 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001338 break;
1339 default:
1340 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1341 DiscardUntilEndOfDirective();
1342 return;
1343 }
Mike Stump11289f42009-09-09 15:08:12 +00001344
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001345 CharSourceRange FilenameRange
1346 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001347 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001348 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001349 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001350 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1351 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001352 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001353 DiscardUntilEndOfDirective();
1354 return;
1355 }
Mike Stump11289f42009-09-09 15:08:12 +00001356
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001357 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001358 // we allow macros that expand to nothing after the filename, because this
1359 // falls into the category of "#include pp-tokens new-line" specified in
1360 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001361 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001362
1363 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001364 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1365 Diag(FilenameTok, diag::err_pp_include_too_deep);
1366 return;
1367 }
Mike Stump11289f42009-09-09 15:08:12 +00001368
John McCall32f5fe12011-09-30 05:12:12 +00001369 // Complain about attempts to #include files in an audit pragma.
1370 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1371 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1372 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1373
1374 // Immediately leave the pragma.
1375 PragmaARCCFCodeAuditedLoc = SourceLocation();
1376 }
1377
Aaron Ballman611306e2012-03-02 22:51:54 +00001378 if (HeaderInfo.HasIncludeAliasMap()) {
1379 // Map the filename with the brackets still attached. If the name doesn't
1380 // map to anything, fall back on the filename we've already gotten the
1381 // spelling for.
1382 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1383 if (!NewName.empty())
1384 Filename = NewName;
1385 }
1386
Chris Lattnerf64b3522008-03-09 01:54:53 +00001387 // Search include directories.
1388 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001389 SmallString<1024> SearchPath;
1390 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001391 // We get the raw path only if we have 'Callbacks' to which we later pass
1392 // the path.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001393 Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001394 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001395 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001396 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001397 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001398
Douglas Gregor11729f02011-11-30 18:12:06 +00001399 if (Callbacks) {
1400 if (!File) {
1401 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001402 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001403 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1404 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1405 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001406 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001407 HeaderInfo.AddSearchPath(DL, isAngled);
1408
1409 // Try the lookup again, skipping the cache.
1410 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001411 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001412 /*SkipCache*/true);
1413 }
1414 }
1415 }
1416
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001417 if (!SuggestedModule) {
1418 // Notify the callback object that we've seen an inclusion directive.
1419 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1420 FilenameRange, File,
1421 SearchPath, RelativePath,
1422 /*ImportedModule=*/0);
1423 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001424 }
1425
1426 if (File == 0) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001427 if (!SuppressIncludeNotFoundError) {
1428 // If the file could not be located and it was included via angle
1429 // brackets, we can attempt a lookup as though it were a quoted path to
1430 // provide the user with a possible fixit.
1431 if (isAngled) {
1432 File = LookupFile(Filename, false, LookupFrom, CurDir,
1433 Callbacks ? &SearchPath : 0,
1434 Callbacks ? &RelativePath : 0,
1435 getLangOpts().Modules ? &SuggestedModule : 0);
1436 if (File) {
1437 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1438 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1439 Filename <<
1440 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1441 }
1442 }
1443 // If the file is still not found, just go with the vanilla diagnostic
1444 if (!File)
1445 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1446 }
1447 if (!File)
1448 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001449 }
1450
Douglas Gregor97eec242011-09-15 22:00:41 +00001451 // If we are supposed to import a module rather than including the header,
1452 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001453 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001454 // Compute the module access path corresponding to this module.
1455 // FIXME: Should we have a second loadModule() overload to avoid this
1456 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001457 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregorde3ef502011-11-30 23:21:26 +00001458 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001459 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1460 FilenameTok.getLocation()));
1461 std::reverse(Path.begin(), Path.end());
1462
Douglas Gregor41e115a2011-11-30 18:02:36 +00001463 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001464 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001465 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1466 if (I)
1467 PathString += '.';
1468 PathString += Path[I].first->getName();
1469 }
1470 int IncludeKind = 0;
1471
1472 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1473 case tok::pp_include:
1474 IncludeKind = 0;
1475 break;
1476
1477 case tok::pp_import:
1478 IncludeKind = 1;
1479 break;
1480
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001481 case tok::pp_include_next:
1482 IncludeKind = 2;
1483 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001484
1485 case tok::pp___include_macros:
1486 IncludeKind = 3;
1487 break;
1488
1489 default:
1490 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001491 }
1492
Douglas Gregor2537a362011-12-08 17:01:29 +00001493 // Determine whether we are actually building the module that this
1494 // include directive maps to.
1495 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001496 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001497
David Blaikiebbafb8a2012-03-11 07:00:24 +00001498 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001499 // If we're not building the imported module, warn that we're going
1500 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001501 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001502 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1503 /*IsTokenRange=*/false);
1504 Diag(HashLoc, diag::warn_auto_module_import)
1505 << IncludeKind << PathString
1506 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001507 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001508 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001509
Douglas Gregor71944202011-11-30 00:36:36 +00001510 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001511 // If this was an #__include_macros directive, only make macros visible.
1512 Module::NameVisibilityKind Visibility
1513 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001514 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001515 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1516 /*IsIncludeDirective=*/true);
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001517 assert((Imported == 0 || Imported == SuggestedModule) &&
1518 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001519
1520 if (!Imported && hadModuleLoaderFatalFailure()) {
1521 // With a fatal failure in the module loader, we abort parsing.
1522 Token &Result = IncludeTok;
1523 if (CurLexer) {
1524 Result.startToken();
1525 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1526 CurLexer->cutOffLexing();
1527 } else {
1528 assert(CurPTHLexer && "#include but no current lexer set!");
1529 CurPTHLexer->getEOF(Result);
1530 }
1531 return;
1532 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001533
1534 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001535 if (!BuildingImportedModule && Imported) {
1536 if (Callbacks) {
1537 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1538 FilenameRange, File,
1539 SearchPath, RelativePath, Imported);
1540 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001541 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001542 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001543
1544 // If we failed to find a submodule that we expected to find, we can
1545 // continue. Otherwise, there's an error in the included file, so we
1546 // don't want to include it.
1547 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1548 return;
1549 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001550 }
1551
1552 if (Callbacks && SuggestedModule) {
1553 // We didn't notify the callback object that we've seen an inclusion
1554 // directive before. Now that we are parsing the include normally and not
1555 // turning it to a module import, notify the callback object.
1556 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1557 FilenameRange, File,
1558 SearchPath, RelativePath,
1559 /*ImportedModule=*/0);
Douglas Gregor97eec242011-09-15 22:00:41 +00001560 }
1561
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001562 // The #included file will be considered to be a system header if either it is
1563 // in a system include directory, or if the #includer is a system include
1564 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001565 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001566 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001567 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001568
Chris Lattner72286d62010-04-19 20:44:31 +00001569 // Ask HeaderInfo if we should enter this #include file. If not, #including
1570 // this file will have no effect.
1571 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001572 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001573 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001574 return;
1575 }
1576
Chris Lattnerf64b3522008-03-09 01:54:53 +00001577 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001578 SourceLocation IncludePos = End;
1579 // If the filename string was the result of macro expansions, set the include
1580 // position on the file where it will be included and after the expansions.
1581 if (IncludePos.isMacroID())
1582 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1583 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001584 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001585
1586 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001587 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001588}
1589
James Dennettf6333ac2012-06-22 05:46:07 +00001590/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001591///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001592void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1593 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001594 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001595
Chris Lattnerf64b3522008-03-09 01:54:53 +00001596 // #include_next is like #include, except that we start searching after
1597 // the current found directory. If we can't do this, issue a
1598 // diagnostic.
1599 const DirectoryLookup *Lookup = CurDirLookup;
1600 if (isInPrimaryFile()) {
1601 Lookup = 0;
1602 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1603 } else if (Lookup == 0) {
1604 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1605 } else {
1606 // Start looking up in the next directory.
1607 ++Lookup;
1608 }
Mike Stump11289f42009-09-09 15:08:12 +00001609
Douglas Gregor796d76a2010-10-20 22:00:55 +00001610 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001611}
1612
James Dennettf6333ac2012-06-22 05:46:07 +00001613/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001614void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1615 // The Microsoft #import directive takes a type library and generates header
1616 // files from it, and includes those. This is beyond the scope of what clang
1617 // does, so we ignore it and error out. However, #import can optionally have
1618 // trailing attributes that span multiple lines. We're going to eat those
1619 // so we can continue processing from there.
1620 Diag(Tok, diag::err_pp_import_directive_ms );
1621
1622 // Read tokens until we get to the end of the directive. Note that the
1623 // directive can be split over multiple lines using the backslash character.
1624 DiscardUntilEndOfDirective();
1625}
1626
James Dennettf6333ac2012-06-22 05:46:07 +00001627/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001628///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001629void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1630 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001631 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1632 if (LangOpts.MicrosoftMode)
1633 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001634 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001635 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001636 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001637}
1638
Chris Lattner58a1eb02009-04-08 18:46:40 +00001639/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1640/// pseudo directive in the predefines buffer. This handles it by sucking all
1641/// tokens through the preprocessor and discarding them (only keeping the side
1642/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001643void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1644 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001645 // This directive should only occur in the predefines buffer. If not, emit an
1646 // error and reject it.
1647 SourceLocation Loc = IncludeMacrosTok.getLocation();
1648 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1649 Diag(IncludeMacrosTok.getLocation(),
1650 diag::pp_include_macros_out_of_predefines);
1651 DiscardUntilEndOfDirective();
1652 return;
1653 }
Mike Stump11289f42009-09-09 15:08:12 +00001654
Chris Lattnere01d82b2009-04-08 20:53:24 +00001655 // Treat this as a normal #include for checking purposes. If this is
1656 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001657 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001658
Chris Lattnere01d82b2009-04-08 20:53:24 +00001659 Token TmpTok;
1660 do {
1661 Lex(TmpTok);
1662 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1663 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001664}
1665
Chris Lattnerf64b3522008-03-09 01:54:53 +00001666//===----------------------------------------------------------------------===//
1667// Preprocessor Macro Directive Handling.
1668//===----------------------------------------------------------------------===//
1669
1670/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1671/// definition has just been read. Lex the rest of the arguments and the
1672/// closing ), updating MI with what we learn. Return true if an error occurs
1673/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001674bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001675 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001676
Chris Lattnerf64b3522008-03-09 01:54:53 +00001677 while (1) {
1678 LexUnexpandedToken(Tok);
1679 switch (Tok.getKind()) {
1680 case tok::r_paren:
1681 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001682 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001683 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001684 // Otherwise we have #define FOO(A,)
1685 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1686 return true;
1687 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001688 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001689 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001690 diag::warn_cxx98_compat_variadic_macro :
1691 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001692
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001693 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1694 if (LangOpts.OpenCL) {
1695 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1696 return true;
1697 }
1698
Chris Lattnerf64b3522008-03-09 01:54:53 +00001699 // Lex the token after the identifier.
1700 LexUnexpandedToken(Tok);
1701 if (Tok.isNot(tok::r_paren)) {
1702 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1703 return true;
1704 }
1705 // Add the __VA_ARGS__ identifier as an argument.
1706 Arguments.push_back(Ident__VA_ARGS__);
1707 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001708 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001709 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001710 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001711 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1712 return true;
1713 default:
1714 // Handle keywords and identifiers here to accept things like
1715 // #define Foo(for) for.
1716 IdentifierInfo *II = Tok.getIdentifierInfo();
1717 if (II == 0) {
1718 // #define X(1
1719 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1720 return true;
1721 }
1722
1723 // If this is already used as an argument, it is used multiple times (e.g.
1724 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001725 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001726 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001727 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001728 return true;
1729 }
Mike Stump11289f42009-09-09 15:08:12 +00001730
Chris Lattnerf64b3522008-03-09 01:54:53 +00001731 // Add the argument to the macro info.
1732 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001733
Chris Lattnerf64b3522008-03-09 01:54:53 +00001734 // Lex the token after the identifier.
1735 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001736
Chris Lattnerf64b3522008-03-09 01:54:53 +00001737 switch (Tok.getKind()) {
1738 default: // #define X(A B
1739 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1740 return true;
1741 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001742 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001743 return false;
1744 case tok::comma: // #define X(A,
1745 break;
1746 case tok::ellipsis: // #define X(A... -> GCC extension
1747 // Diagnose extension.
1748 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001749
Chris Lattnerf64b3522008-03-09 01:54:53 +00001750 // Lex the token after the identifier.
1751 LexUnexpandedToken(Tok);
1752 if (Tok.isNot(tok::r_paren)) {
1753 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1754 return true;
1755 }
Mike Stump11289f42009-09-09 15:08:12 +00001756
Chris Lattnerf64b3522008-03-09 01:54:53 +00001757 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001758 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001759 return false;
1760 }
1761 }
1762 }
1763}
1764
James Dennettf6333ac2012-06-22 05:46:07 +00001765/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001766/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001767void Preprocessor::HandleDefineDirective(Token &DefineTok,
1768 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001769 ++NumDefined;
1770
1771 Token MacroNameTok;
1772 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001773
Chris Lattnerf64b3522008-03-09 01:54:53 +00001774 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001775 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001776 return;
1777
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001778 Token LastTok = MacroNameTok;
1779
Chris Lattnerf64b3522008-03-09 01:54:53 +00001780 // If we are supposed to keep comments in #defines, reenable comment saving
1781 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001782 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001783
Chris Lattnerf64b3522008-03-09 01:54:53 +00001784 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001785 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001786
Chris Lattnerf64b3522008-03-09 01:54:53 +00001787 Token Tok;
1788 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001789
Chris Lattnerf64b3522008-03-09 01:54:53 +00001790 // If this is a function-like macro definition, parse the argument list,
1791 // marking each of the identifiers as being used as macro arguments. Also,
1792 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001793 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001794 if (ImmediatelyAfterHeaderGuard) {
1795 // Save this macro information since it may part of a header guard.
1796 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
1797 MacroNameTok.getLocation());
1798 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001799 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001800 } else if (Tok.hasLeadingSpace()) {
1801 // This is a normal token with leading space. Clear the leading space
1802 // marker on the first token to get proper expansion.
1803 Tok.clearFlag(Token::LeadingSpace);
1804 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001805 // This is a function-like macro definition. Read the argument list.
1806 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001807 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001808 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001809 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001810 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001811 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001812 DiscardUntilEndOfDirective();
1813 return;
1814 }
1815
Chris Lattner249c38b2009-04-19 18:26:34 +00001816 // If this is a definition of a variadic C99 function-like macro, not using
1817 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001818
Chris Lattner249c38b2009-04-19 18:26:34 +00001819 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1820 // This gets unpoisoned where it is allowed.
1821 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1822 if (MI->isC99Varargs())
1823 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001824
Chris Lattnerf64b3522008-03-09 01:54:53 +00001825 // Read the first token after the arg list for down below.
1826 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001827 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001828 // C99 requires whitespace between the macro definition and the body. Emit
1829 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001830 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001831 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001832 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1833 // first character of a replacement list is not a character required by
1834 // subclause 5.2.1, then there shall be white-space separation between the
1835 // identifier and the replacement list.". 5.2.1 lists this set:
1836 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1837 // is irrelevant here.
1838 bool isInvalid = false;
1839 if (Tok.is(tok::at)) // @ is not in the list above.
1840 isInvalid = true;
1841 else if (Tok.is(tok::unknown)) {
1842 // If we have an unknown token, it is something strange like "`". Since
1843 // all of valid characters would have lexed into a single character
1844 // token of some sort, we know this is not a valid case.
1845 isInvalid = true;
1846 }
1847 if (isInvalid)
1848 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1849 else
1850 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001851 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001852
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001853 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001854 LastTok = Tok;
1855
Chris Lattnerf64b3522008-03-09 01:54:53 +00001856 // Read the rest of the macro body.
1857 if (MI->isObjectLike()) {
1858 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001859 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001860 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001861 MI->AddTokenToBody(Tok);
1862 // Get the next token of the macro.
1863 LexUnexpandedToken(Tok);
1864 }
Mike Stump11289f42009-09-09 15:08:12 +00001865
Chris Lattnerf64b3522008-03-09 01:54:53 +00001866 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001867 // Otherwise, read the body of a function-like macro. While we are at it,
1868 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1869 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001870 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001871 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001872
Eli Friedman14d3c792012-11-14 02:18:46 +00001873 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001874 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001875
Chris Lattnerf64b3522008-03-09 01:54:53 +00001876 // Get the next token of the macro.
1877 LexUnexpandedToken(Tok);
1878 continue;
1879 }
Mike Stump11289f42009-09-09 15:08:12 +00001880
Eli Friedman14d3c792012-11-14 02:18:46 +00001881 if (Tok.is(tok::hashhash)) {
1882
1883 // If we see token pasting, check if it looks like the gcc comma
1884 // pasting extension. We'll use this information to suppress
1885 // diagnostics later on.
1886
1887 // Get the next token of the macro.
1888 LexUnexpandedToken(Tok);
1889
1890 if (Tok.is(tok::eod)) {
1891 MI->AddTokenToBody(LastTok);
1892 break;
1893 }
1894
1895 unsigned NumTokens = MI->getNumTokens();
1896 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1897 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1898 MI->setHasCommaPasting();
1899
1900 // Things look ok, add the '##' and param name tokens to the macro.
1901 MI->AddTokenToBody(LastTok);
1902 MI->AddTokenToBody(Tok);
1903 LastTok = Tok;
1904
1905 // Get the next token of the macro.
1906 LexUnexpandedToken(Tok);
1907 continue;
1908 }
1909
Chris Lattnerf64b3522008-03-09 01:54:53 +00001910 // Get the next token of the macro.
1911 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001912
Chris Lattner83bd8282009-05-25 17:16:10 +00001913 // Check for a valid macro arg identifier.
1914 if (Tok.getIdentifierInfo() == 0 ||
1915 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1916
1917 // If this is assembler-with-cpp mode, we accept random gibberish after
1918 // the '#' because '#' is often a comment character. However, change
1919 // the kind of the token to tok::unknown so that the preprocessor isn't
1920 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001921 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001922 LastTok.setKind(tok::unknown);
1923 } else {
1924 Diag(Tok, diag::err_pp_stringize_not_parameter);
1925 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001926
Chris Lattner83bd8282009-05-25 17:16:10 +00001927 // Disable __VA_ARGS__ again.
1928 Ident__VA_ARGS__->setIsPoisoned(true);
1929 return;
1930 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001931 }
Mike Stump11289f42009-09-09 15:08:12 +00001932
Chris Lattner83bd8282009-05-25 17:16:10 +00001933 // Things look ok, add the '#' and param name tokens to the macro.
1934 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001935 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001936 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001937
Chris Lattnerf64b3522008-03-09 01:54:53 +00001938 // Get the next token of the macro.
1939 LexUnexpandedToken(Tok);
1940 }
1941 }
Mike Stump11289f42009-09-09 15:08:12 +00001942
1943
Chris Lattnerf64b3522008-03-09 01:54:53 +00001944 // Disable __VA_ARGS__ again.
1945 Ident__VA_ARGS__->setIsPoisoned(true);
1946
Chris Lattner57540c52011-04-15 05:22:18 +00001947 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001948 // replacement list.
1949 unsigned NumTokens = MI->getNumTokens();
1950 if (NumTokens != 0) {
1951 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1952 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001953 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001954 return;
1955 }
1956 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1957 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001958 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001959 return;
1960 }
1961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001963 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001964
Chris Lattnerf64b3522008-03-09 01:54:53 +00001965 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00001966 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001967 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001968 // It is very common for system headers to have tons of macro redefinitions
1969 // and for warnings to be disabled in system headers. If this is the case,
1970 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001971 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001972 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001973 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001974 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001975
Richard Smith7b242542013-03-06 00:46:00 +00001976 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
1977 // C++ [cpp.predefined]p4, but allow it as an extension.
1978 if (OtherMI->isBuiltinMacro())
1979 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001980 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00001981 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00001982 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00001983 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001984 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1985 << MacroNameTok.getIdentifierInfo();
1986 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1987 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001988 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001989 if (OtherMI->isWarnIfUnused())
1990 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001991 }
Mike Stump11289f42009-09-09 15:08:12 +00001992
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001993 DefMacroDirective *MD =
1994 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001995
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001996 assert(!MI->isUsed());
1997 // If we need warning for not using the macro, add its location in the
1998 // warn-because-unused-macro set. If it gets used it will be removed from set.
1999 if (isInPrimaryFile() && // don't warn for include'd macros.
2000 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00002001 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002002 MI->setIsWarnIfUnused(true);
2003 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2004 }
2005
Chris Lattner928e9092009-04-12 01:39:54 +00002006 // If the callbacks want to know, tell them about the macro definition.
2007 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002008 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002009}
2010
James Dennettf6333ac2012-06-22 05:46:07 +00002011/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002012///
2013void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2014 ++NumUndefined;
2015
2016 Token MacroNameTok;
2017 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00002018
Chris Lattnerf64b3522008-03-09 01:54:53 +00002019 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002020 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002021 return;
Mike Stump11289f42009-09-09 15:08:12 +00002022
Chris Lattnerf64b3522008-03-09 01:54:53 +00002023 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002024 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002025
Chris Lattnerf64b3522008-03-09 01:54:53 +00002026 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002027 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002028 const MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Mike Stump11289f42009-09-09 15:08:12 +00002029
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002030 // If the callbacks want to know, tell them about the macro #undef.
2031 // Note: no matter if the macro was defined or not.
2032 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002033 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002034
Chris Lattnerf64b3522008-03-09 01:54:53 +00002035 // If the macro is not defined, this is a noop undef, just return.
2036 if (MI == 0) return;
2037
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002038 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002039 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002040
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002041 if (MI->isWarnIfUnused())
2042 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2043
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002044 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2045 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002046}
2047
2048
2049//===----------------------------------------------------------------------===//
2050// Preprocessor Conditional Directive Handling.
2051//===----------------------------------------------------------------------===//
2052
James Dennettf6333ac2012-06-22 05:46:07 +00002053/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2054/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2055/// true if any tokens have been returned or pp-directives activated before this
2056/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002057///
2058void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2059 bool ReadAnyTokensBeforeDirective) {
2060 ++NumIf;
2061 Token DirectiveTok = Result;
2062
2063 Token MacroNameTok;
2064 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002065
Chris Lattnerf64b3522008-03-09 01:54:53 +00002066 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002067 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002068 // Skip code until we get to #endif. This helps with recovery by not
2069 // emitting an error when the #endif is reached.
2070 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2071 /*Foundnonskip*/false, /*FoundElse*/false);
2072 return;
2073 }
Mike Stump11289f42009-09-09 15:08:12 +00002074
Chris Lattnerf64b3522008-03-09 01:54:53 +00002075 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002076 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002077
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002078 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002079 MacroDirective *MD = getMacroDirective(MII);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002080 MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002081
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002082 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002083 // If the start of a top-level #ifdef and if the macro is not defined,
2084 // inform MIOpt that this might be the start of a proper include guard.
2085 // Otherwise it is some other form of unknown conditional which we can't
2086 // handle.
2087 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002088 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002089 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002090 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002091 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002092 }
2093
Chris Lattnerf64b3522008-03-09 01:54:53 +00002094 // If there is a macro, process it.
2095 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002096 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002097
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002098 if (Callbacks) {
2099 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002100 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002101 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002102 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002103 }
2104
Chris Lattnerf64b3522008-03-09 01:54:53 +00002105 // Should we include the stuff contained by this directive?
2106 if (!MI == isIfndef) {
2107 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002108 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2109 /*wasskip*/false, /*foundnonskip*/true,
2110 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002111 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002112 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002113 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002114 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002115 /*FoundElse*/false);
2116 }
2117}
2118
James Dennettf6333ac2012-06-22 05:46:07 +00002119/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002120///
2121void Preprocessor::HandleIfDirective(Token &IfToken,
2122 bool ReadAnyTokensBeforeDirective) {
2123 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002124
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002125 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002126 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002127 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2128 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2129 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002130
2131 // If this condition is equivalent to #ifndef X, and if this is the first
2132 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002133 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002134 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002135 // FIXME: Pass in the location of the macro name, not the 'if' token.
2136 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002137 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002138 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002139 }
2140
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002141 if (Callbacks)
2142 Callbacks->If(IfToken.getLocation(),
2143 SourceRange(ConditionalBegin, ConditionalEnd));
2144
Chris Lattnerf64b3522008-03-09 01:54:53 +00002145 // Should we include the stuff contained by this directive?
2146 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002147 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002148 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002149 /*foundnonskip*/true, /*foundelse*/false);
2150 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002151 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002152 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002153 /*FoundElse*/false);
2154 }
2155}
2156
James Dennettf6333ac2012-06-22 05:46:07 +00002157/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002158///
2159void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2160 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002161
Chris Lattnerf64b3522008-03-09 01:54:53 +00002162 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002163 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002164
Chris Lattnerf64b3522008-03-09 01:54:53 +00002165 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002166 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002167 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002168 Diag(EndifToken, diag::err_pp_endif_without_if);
2169 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002170 }
Mike Stump11289f42009-09-09 15:08:12 +00002171
Chris Lattnerf64b3522008-03-09 01:54:53 +00002172 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002173 if (CurPPLexer->getConditionalStackDepth() == 0)
2174 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002175
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002176 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002177 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002178
2179 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002180 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002181}
2182
James Dennettf6333ac2012-06-22 05:46:07 +00002183/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002184///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002185void Preprocessor::HandleElseDirective(Token &Result) {
2186 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002187
Chris Lattnerf64b3522008-03-09 01:54:53 +00002188 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002189 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002190
Chris Lattnerf64b3522008-03-09 01:54:53 +00002191 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002192 if (CurPPLexer->popConditionalLevel(CI)) {
2193 Diag(Result, diag::pp_err_else_without_if);
2194 return;
2195 }
Mike Stump11289f42009-09-09 15:08:12 +00002196
Chris Lattnerf64b3522008-03-09 01:54:53 +00002197 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002198 if (CurPPLexer->getConditionalStackDepth() == 0)
2199 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002200
2201 // If this is a #else with a #else before it, report the error.
2202 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002203
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002204 if (Callbacks)
2205 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2206
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002207 // Finally, skip the rest of the contents of this block.
2208 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002209 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002210}
2211
James Dennettf6333ac2012-06-22 05:46:07 +00002212/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002213///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002214void Preprocessor::HandleElifDirective(Token &ElifToken) {
2215 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002216
Chris Lattnerf64b3522008-03-09 01:54:53 +00002217 // #elif directive in a non-skipping conditional... start skipping.
2218 // We don't care what the condition is, because we will always skip it (since
2219 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002220 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002221 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002222 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002223
2224 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002225 if (CurPPLexer->popConditionalLevel(CI)) {
2226 Diag(ElifToken, diag::pp_err_elif_without_if);
2227 return;
2228 }
Mike Stump11289f42009-09-09 15:08:12 +00002229
Chris Lattnerf64b3522008-03-09 01:54:53 +00002230 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002231 if (CurPPLexer->getConditionalStackDepth() == 0)
2232 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002233
Chris Lattnerf64b3522008-03-09 01:54:53 +00002234 // If this is a #elif with a #else before it, report the error.
2235 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002236
2237 if (Callbacks)
2238 Callbacks->Elif(ElifToken.getLocation(),
2239 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002240
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002241 // Finally, skip the rest of the contents of this block.
2242 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002243 /*FoundElse*/CI.FoundElse,
2244 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002245}