blob: 3fc19e41f818be8f5be5e86caf2461199ad26aa5 [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");
64 MacroInfo *MI =
65 (MacroInfo*)BP.Allocate(sizeof(MacroInfo) + sizeof(SubModuleID),
66 llvm::AlignOf<MacroInfo>::Alignment);
67 new (MI) MacroInfo(L);
68 MI->FromASTFile = true;
69 MI->setOwningModuleID(SubModuleID);
70 return MI;
71}
72
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000073DefMacroDirective *
74Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc,
75 bool isImported) {
76 DefMacroDirective *MD = BP.Allocate<DefMacroDirective>();
77 new (MD) DefMacroDirective(MI, Loc, isImported);
78 return MD;
79}
80
81UndefMacroDirective *
82Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
83 UndefMacroDirective *MD = BP.Allocate<UndefMacroDirective>();
84 new (MD) UndefMacroDirective(UndefLoc);
85 return MD;
86}
87
88VisibilityMacroDirective *
89Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
90 bool isPublic) {
91 VisibilityMacroDirective *MD = BP.Allocate<VisibilityMacroDirective>();
92 new (MD) VisibilityMacroDirective(Loc, isPublic);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000093 return MD;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000094}
95
James Dennettf6333ac2012-06-22 05:46:07 +000096/// \brief Release the specified MacroInfo to be reused for allocating
97/// new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +000098void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +000099 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
100 if (MacroInfoChain *Prev = MIChain->Prev) {
101 MacroInfoChain *Next = MIChain->Next;
102 Prev->Next = Next;
103 if (Next)
104 Next->Prev = Prev;
105 }
106 else {
107 assert(MIChainHead == MIChain);
108 MIChainHead = MIChain->Next;
109 MIChainHead->Prev = 0;
110 }
111 MIChain->Next = MICache;
112 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +0000113
Ted Kremenekc8456f82010-10-19 22:15:20 +0000114 MI->Destroy();
115}
Chris Lattner666f7a42009-02-20 22:19:20 +0000116
James Dennettf6333ac2012-06-22 05:46:07 +0000117/// \brief Read and discard all tokens remaining on the current line until
118/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000119void Preprocessor::DiscardUntilEndOfDirective() {
120 Token Tmp;
121 do {
122 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000123 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000124 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000125}
126
James Dennettf6333ac2012-06-22 05:46:07 +0000127/// \brief Lex and validate a macro name, which occurs after a
128/// \#define or \#undef.
129///
130/// This sets the token kind to eod and discards the rest
131/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
132/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
133/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000134void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
135 // Read the token, don't allow macro expansion on it.
136 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000137
Douglas Gregor12785102010-08-24 20:21:13 +0000138 if (MacroNameTok.is(tok::code_completion)) {
139 if (CodeComplete)
140 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000141 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000142 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000143 }
144
Chris Lattnerf64b3522008-03-09 01:54:53 +0000145 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000146 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000147 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
148 return;
149 }
Mike Stump11289f42009-09-09 15:08:12 +0000150
Chris Lattnerf64b3522008-03-09 01:54:53 +0000151 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
152 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000153 bool Invalid = false;
154 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
155 if (Invalid)
156 return;
Nico Weber2e686202012-02-29 22:54:43 +0000157
Chris Lattner77c76ae2008-12-13 20:12:40 +0000158 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000159
160 // Allow #defining |and| and friends in microsoft mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000161 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weber2e686202012-02-29 22:54:43 +0000162 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
163 return;
164 }
165
Chris Lattner77c76ae2008-12-13 20:12:40 +0000166 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000167 // C++ 2.5p2: Alternative tokens behave the same as its primary token
168 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000169 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000170 else
171 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
172 // Fall through on error.
173 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Richard Smith7b242542013-03-06 00:46:00 +0000174 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000175 Diag(MacroNameTok, diag::err_defined_macro_name);
Richard Smith7b242542013-03-06 00:46:00 +0000176 } else if (isDefineUndef == 2 && II->hasMacroDefinition() &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000177 getMacroInfo(II)->isBuiltinMacro()) {
Richard Smith7b242542013-03-06 00:46:00 +0000178 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
179 // and C++ [cpp.predefined]p4], but allow it as an extension.
180 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
181 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000182 } else {
183 // Okay, we got a good identifier node. Return it.
184 return;
185 }
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattnerf64b3522008-03-09 01:54:53 +0000187 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000188 // token kind to tok::eod.
189 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000190 return DiscardUntilEndOfDirective();
191}
192
James Dennettf6333ac2012-06-22 05:46:07 +0000193/// \brief Ensure that the next token is a tok::eod token.
194///
195/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000196/// true, then we consider macros that expand to zero tokens as being ok.
197void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000198 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000199 // Lex unexpanded tokens for most directives: macros might expand to zero
200 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
201 // #line) allow empty macros.
202 if (EnableMacros)
203 Lex(Tmp);
204 else
205 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000206
Chris Lattnerf64b3522008-03-09 01:54:53 +0000207 // There should be no tokens after the directive, but we allow them as an
208 // extension.
209 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
210 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000211
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000212 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000213 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000214 // or if this is a macro-style preprocessing directive, because it is more
215 // trouble than it is worth to insert /**/ and check that there is no /**/
216 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000217 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000218 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000219 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000220 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
221 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000222 DiscardUntilEndOfDirective();
223 }
224}
225
226
227
James Dennettf6333ac2012-06-22 05:46:07 +0000228/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
229/// decided that the subsequent tokens are in the \#if'd out portion of the
230/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000231/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000232/// this \#if directive, so \#else/\#elif blocks should never be entered.
233/// If ElseOk is true, then \#else directives are ok, if not, then we have
234/// already seen one so a \#else directive is a duplicate. When this returns,
235/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000236void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
237 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000238 bool FoundElse,
239 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000240 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000241 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000242
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000243 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000244 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000245
Ted Kremenek56572ab2008-12-12 18:34:08 +0000246 if (CurPTHLexer) {
247 PTHSkipExcludedConditionalBlock();
248 return;
249 }
Mike Stump11289f42009-09-09 15:08:12 +0000250
Chris Lattnerf64b3522008-03-09 01:54:53 +0000251 // Enter raw mode to disable identifier lookup (and thus macro expansion),
252 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000253 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000254 Token Tok;
255 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000256 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000257
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000258 if (Tok.is(tok::code_completion)) {
259 if (CodeComplete)
260 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000261 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000262 continue;
263 }
264
Chris Lattnerf64b3522008-03-09 01:54:53 +0000265 // If this is the end of the buffer, we have an error.
266 if (Tok.is(tok::eof)) {
267 // Emit errors for each unterminated conditional on the stack, including
268 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000269 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000270 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000271 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
272 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000273 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000274 }
275
Chris Lattnerf64b3522008-03-09 01:54:53 +0000276 // Just return and let the caller lex after this #include.
277 break;
278 }
Mike Stump11289f42009-09-09 15:08:12 +0000279
Chris Lattnerf64b3522008-03-09 01:54:53 +0000280 // If this token is not a preprocessor directive, just skip it.
281 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
282 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000283
Chris Lattnerf64b3522008-03-09 01:54:53 +0000284 // We just parsed a # character at the start of a line, so we're in
285 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000286 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000287 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000288 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000289
Mike Stump11289f42009-09-09 15:08:12 +0000290
Chris Lattnerf64b3522008-03-09 01:54:53 +0000291 // Read the next token, the directive flavor.
292 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000293
Chris Lattnerf64b3522008-03-09 01:54:53 +0000294 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
295 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000296 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000297 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000298 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000299 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000300 continue;
301 }
302
303 // If the first letter isn't i or e, it isn't intesting to us. We know that
304 // this is safe in the face of spelling differences, because there is no way
305 // to spell an i/e in a strange way that is another letter. Skipping this
306 // allows us to avoid looking up the identifier info for #define/#undef and
307 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000308 const char *RawCharData = Tok.getRawIdentifierData();
309
Chris Lattnerf64b3522008-03-09 01:54:53 +0000310 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000311 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000312 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000313 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000315 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000316 continue;
317 }
Mike Stump11289f42009-09-09 15:08:12 +0000318
Chris Lattnerf64b3522008-03-09 01:54:53 +0000319 // Get the identifier name without trigraphs or embedded newlines. Note
320 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
321 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000322 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000323 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000324 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000325 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000326 } else {
327 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000328 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000330 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000331 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000332 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000333 continue;
334 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000335 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000336 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000337 }
Mike Stump11289f42009-09-09 15:08:12 +0000338
Benjamin Kramer144884642009-12-31 13:32:38 +0000339 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000340 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000341 if (Sub.empty() || // "if"
342 Sub == "def" || // "ifdef"
343 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000344 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
345 // bother parsing the condition.
346 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000347 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000348 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000349 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000350 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000351 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000352 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000353 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000354 PPConditionalInfo CondInfo;
355 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000356 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000357 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000358 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000359
Chris Lattnerf64b3522008-03-09 01:54:53 +0000360 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000361 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000362 // Restore the value of LexingRawMode so that trailing comments
363 // are handled correctly, if we've reached the outermost block.
364 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000365 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000366 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000367 if (Callbacks)
368 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000369 break;
Richard Smithd0124572012-06-21 00:35:03 +0000370 } else {
371 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000372 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000373 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000374 // #else directive in a skipping conditional. If not in some other
375 // skipping conditional, and if #else hasn't already been seen, enter it
376 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000377 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000378
Chris Lattnerf64b3522008-03-09 01:54:53 +0000379 // If this is a #else with a #else before it, report the error.
380 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Chris Lattnerf64b3522008-03-09 01:54:53 +0000382 // Note that we've seen a #else in this conditional.
383 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000384
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385 // If the conditional is at the top level, and the #if block wasn't
386 // entered, enter the #else block now.
387 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
388 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000389 // Restore the value of LexingRawMode so that trailing comments
390 // are handled correctly.
391 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000392 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000393 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000394 if (Callbacks)
395 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000396 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000397 } else {
398 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000399 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000400 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000401 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000402
403 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000404 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000405 // If this is in a skipping block or if we're already handled this #if
406 // block, don't bother parsing the condition.
407 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
408 DiscardUntilEndOfDirective();
409 ShouldEnter = false;
410 } else {
411 // Restore the value of LexingRawMode so that identifiers are
412 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000413 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
414 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000415 IdentifierInfo *IfNDefMacro = 0;
416 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000417 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000418 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000419 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000420
Chris Lattnerf64b3522008-03-09 01:54:53 +0000421 // If this is a #elif with a #else before it, report the error.
422 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattnerf64b3522008-03-09 01:54:53 +0000424 // If this condition is true, enter it!
425 if (ShouldEnter) {
426 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000427 if (Callbacks)
428 Callbacks->Elif(Tok.getLocation(),
429 SourceRange(ConditionalBegin, ConditionalEnd),
430 CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000431 break;
432 }
433 }
434 }
Mike Stump11289f42009-09-09 15:08:12 +0000435
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000436 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000437 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000438 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000439 }
440
441 // Finally, if we are out of the conditional (saw an #endif or ran off the end
442 // of the file, just stop skipping and return to lexing whatever came after
443 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000444 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000445
446 if (Callbacks) {
447 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
448 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
449 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000450}
451
Ted Kremenek56572ab2008-12-12 18:34:08 +0000452void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000453
454 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000455 assert(CurPTHLexer);
456 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000457
Ted Kremenek56572ab2008-12-12 18:34:08 +0000458 // Skip to the next '#else', '#elif', or #endif.
459 if (CurPTHLexer->SkipBlock()) {
460 // We have reached an #endif. Both the '#' and 'endif' tokens
461 // have been consumed by the PTHLexer. Just pop off the condition level.
462 PPConditionalInfo CondInfo;
463 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000464 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000465 assert(!InCond && "Can't be skipping if not in a conditional!");
466 break;
467 }
Mike Stump11289f42009-09-09 15:08:12 +0000468
Ted Kremenek56572ab2008-12-12 18:34:08 +0000469 // We have reached a '#else' or '#elif'. Lex the next token to get
470 // the directive flavor.
471 Token Tok;
472 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000473
Ted Kremenek56572ab2008-12-12 18:34:08 +0000474 // We can actually look up the IdentifierInfo here since we aren't in
475 // raw mode.
476 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
477
478 if (K == tok::pp_else) {
479 // #else: Enter the else condition. We aren't in a nested condition
480 // since we skip those. We're always in the one matching the last
481 // blocked we skipped.
482 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
483 // Note that we've seen a #else in this conditional.
484 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000485
Ted Kremenek56572ab2008-12-12 18:34:08 +0000486 // If the #if block wasn't entered then enter the #else block now.
487 if (!CondInfo.FoundNonSkip) {
488 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000489
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000490 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000491 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000492 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000493 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000494
Ted Kremenek56572ab2008-12-12 18:34:08 +0000495 break;
496 }
Mike Stump11289f42009-09-09 15:08:12 +0000497
Ted Kremenek56572ab2008-12-12 18:34:08 +0000498 // Otherwise skip this block.
499 continue;
500 }
Mike Stump11289f42009-09-09 15:08:12 +0000501
Ted Kremenek56572ab2008-12-12 18:34:08 +0000502 assert(K == tok::pp_elif);
503 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
504
505 // If this is a #elif with a #else before it, report the error.
506 if (CondInfo.FoundElse)
507 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000508
Ted Kremenek56572ab2008-12-12 18:34:08 +0000509 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000510 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000511 if (CondInfo.FoundNonSkip)
512 continue;
513
514 // Evaluate the condition of the #elif.
515 IdentifierInfo *IfNDefMacro = 0;
516 CurPTHLexer->ParsingPreprocessorDirective = true;
517 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
518 CurPTHLexer->ParsingPreprocessorDirective = false;
519
520 // If this condition is true, enter it!
521 if (ShouldEnter) {
522 CondInfo.FoundNonSkip = true;
523 break;
524 }
525
526 // Otherwise, skip this block and go to the next one.
527 continue;
528 }
529}
530
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000531const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000532 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000533 bool isAngled,
534 const DirectoryLookup *FromDir,
535 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000536 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000537 SmallVectorImpl<char> *RelativePath,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000538 Module **SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000539 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000540 // If the header lookup mechanism may be relative to the current file, pass in
541 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000542 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000543 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000544 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000545 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000546
Chris Lattner022923a2009-02-04 19:45:07 +0000547 // If there is no file entry associated with this file, it must be the
548 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000549 // it won't be scanned for preprocessor directives. If we have the
550 // predefines buffer, resolve #include references (which come from the
551 // -include command line argument) as if they came from the main file, this
552 // affects file lookup etc.
553 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000554 FID = SourceMgr.getMainFileID();
555 CurFileEnt = SourceMgr.getFileEntryForID(FID);
556 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000557 }
Mike Stump11289f42009-09-09 15:08:12 +0000558
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000559 // Do a standard file entry lookup.
560 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000561 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000562 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000563 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerfde85352010-01-22 00:14:44 +0000564 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000565
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000566 // Otherwise, see if this is a subframework header. If so, this is relative
567 // to one of the headers on the #include stack. Walk the list of the current
568 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000569 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000570 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000571 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000572 SearchPath, RelativePath,
573 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000574 return FE;
575 }
Mike Stump11289f42009-09-09 15:08:12 +0000576
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000577 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
578 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000579 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000580 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000581 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000582 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000583 Filename, CurFileEnt, SearchPath, RelativePath,
584 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000585 return FE;
586 }
587 }
Mike Stump11289f42009-09-09 15:08:12 +0000588
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000589 // Otherwise, we really couldn't find the file.
590 return 0;
591}
592
Chris Lattnerf64b3522008-03-09 01:54:53 +0000593
594//===----------------------------------------------------------------------===//
595// Preprocessor Directive Handling.
596//===----------------------------------------------------------------------===//
597
David Blaikied5321242012-06-06 18:52:13 +0000598class Preprocessor::ResetMacroExpansionHelper {
599public:
600 ResetMacroExpansionHelper(Preprocessor *pp)
601 : PP(pp), save(pp->DisableMacroExpansion) {
602 if (pp->MacroExpansionInDirectivesOverride)
603 pp->DisableMacroExpansion = false;
604 }
605 ~ResetMacroExpansionHelper() {
606 PP->DisableMacroExpansion = save;
607 }
608private:
609 Preprocessor *PP;
610 bool save;
611};
612
Chris Lattnerf64b3522008-03-09 01:54:53 +0000613/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000614/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000615/// lexer/preprocessor state, and advances the lexer(s) so that the next token
616/// read is the correct one.
617void Preprocessor::HandleDirective(Token &Result) {
618 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000619
Chris Lattnerf64b3522008-03-09 01:54:53 +0000620 // We just parsed a # character at the start of a line, so we're in directive
621 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000622 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000623 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000624 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000625
Chris Lattnerf64b3522008-03-09 01:54:53 +0000626 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000627
Chris Lattnerf64b3522008-03-09 01:54:53 +0000628 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000629 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000630 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000631 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000632
Chris Lattner2d17ab72009-03-18 21:00:25 +0000633 // Save the '#' token in case we need to return it later.
634 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000635
Chris Lattnerf64b3522008-03-09 01:54:53 +0000636 // Read the next token, the directive flavor. This isn't expanded due to
637 // C99 6.10.3p8.
638 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000639
Chris Lattnerf64b3522008-03-09 01:54:53 +0000640 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
641 // #define A(x) #x
642 // A(abc
643 // #warning blah
644 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000645 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
646 // not support this for #include-like directives, since that can result in
647 // terrible diagnostics, and does not work in GCC.
648 if (InMacroArgs) {
649 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
650 switch (II->getPPKeywordID()) {
651 case tok::pp_include:
652 case tok::pp_import:
653 case tok::pp_include_next:
654 case tok::pp___include_macros:
655 Diag(Result, diag::err_embedded_include) << II->getName();
656 DiscardUntilEndOfDirective();
657 return;
658 default:
659 break;
660 }
661 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000662 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000663 }
Mike Stump11289f42009-09-09 15:08:12 +0000664
David Blaikied5321242012-06-06 18:52:13 +0000665 // Temporarily enable macro expansion if set so
666 // and reset to previous state when returning from this function.
667 ResetMacroExpansionHelper helper(this);
668
Chris Lattnerf64b3522008-03-09 01:54:53 +0000669 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000670 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000671 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000672 case tok::code_completion:
673 if (CodeComplete)
674 CodeComplete->CodeCompleteDirective(
675 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000676 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000677 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000678 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000679 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000680 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000681 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000682 default:
683 IdentifierInfo *II = Result.getIdentifierInfo();
684 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000685
Chris Lattnerf64b3522008-03-09 01:54:53 +0000686 // Ask what the preprocessor keyword ID is.
687 switch (II->getPPKeywordID()) {
688 default: break;
689 // C99 6.10.1 - Conditional Inclusion.
690 case tok::pp_if:
691 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
692 case tok::pp_ifdef:
693 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
694 case tok::pp_ifndef:
695 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
696 case tok::pp_elif:
697 return HandleElifDirective(Result);
698 case tok::pp_else:
699 return HandleElseDirective(Result);
700 case tok::pp_endif:
701 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000702
Chris Lattnerf64b3522008-03-09 01:54:53 +0000703 // C99 6.10.2 - Source File Inclusion.
704 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000705 // Handle #include.
706 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000707 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000708 // Handle -imacros.
709 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000710
Chris Lattnerf64b3522008-03-09 01:54:53 +0000711 // C99 6.10.3 - Macro Replacement.
712 case tok::pp_define:
713 return HandleDefineDirective(Result);
714 case tok::pp_undef:
715 return HandleUndefDirective(Result);
716
717 // C99 6.10.4 - Line Control.
718 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000719 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000720
Chris Lattnerf64b3522008-03-09 01:54:53 +0000721 // C99 6.10.5 - Error Directive.
722 case tok::pp_error:
723 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000724
Chris Lattnerf64b3522008-03-09 01:54:53 +0000725 // C99 6.10.6 - Pragma Directive.
726 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000727 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000728
Chris Lattnerf64b3522008-03-09 01:54:53 +0000729 // GNU Extensions.
730 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000731 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000732 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000733 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000734
Chris Lattnerf64b3522008-03-09 01:54:53 +0000735 case tok::pp_warning:
736 Diag(Result, diag::ext_pp_warning_directive);
737 return HandleUserDiagnosticDirective(Result, true);
738 case tok::pp_ident:
739 return HandleIdentSCCSDirective(Result);
740 case tok::pp_sccs:
741 return HandleIdentSCCSDirective(Result);
742 case tok::pp_assert:
743 //isExtension = true; // FIXME: implement #assert
744 break;
745 case tok::pp_unassert:
746 //isExtension = true; // FIXME: implement #unassert
747 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000748
Douglas Gregor663b48f2012-01-03 19:48:16 +0000749 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000750 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000751 return HandleMacroPublicDirective(Result);
752 break;
753
Douglas Gregor663b48f2012-01-03 19:48:16 +0000754 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000755 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000756 return HandleMacroPrivateDirective(Result);
757 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000758 }
759 break;
760 }
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattner2d17ab72009-03-18 21:00:25 +0000762 // If this is a .S file, treat unknown # directives as non-preprocessor
763 // directives. This is important because # may be a comment or introduce
764 // various pseudo-ops. Just return the # token and push back the following
765 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000766 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000767 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000768 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000769 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000770 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000771
772 // If the second token is a hashhash token, then we need to translate it to
773 // unknown so the token lexer doesn't try to perform token pasting.
774 if (Result.is(tok::hashhash))
775 Toks[1].setKind(tok::unknown);
776
Chris Lattner2d17ab72009-03-18 21:00:25 +0000777 // Enter this token stream so that we re-lex the tokens. Make sure to
778 // enable macro expansion, in case the token after the # is an identifier
779 // that is expanded.
780 EnterTokenStream(Toks, 2, false, true);
781 return;
782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattnerf64b3522008-03-09 01:54:53 +0000784 // If we reached here, the preprocessing token is not valid!
785 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000786
Chris Lattnerf64b3522008-03-09 01:54:53 +0000787 // Read the rest of the PP line.
788 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000789
Chris Lattnerf64b3522008-03-09 01:54:53 +0000790 // Okay, we're done parsing the directive.
791}
792
Chris Lattner76e68962009-01-26 06:19:46 +0000793/// GetLineValue - Convert a numeric token into an unsigned value, emitting
794/// Diagnostic DiagID if it is invalid, and returning the value in Val.
795static bool GetLineValue(Token &DigitTok, unsigned &Val,
796 unsigned DiagID, Preprocessor &PP) {
797 if (DigitTok.isNot(tok::numeric_constant)) {
798 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000799
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000800 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000801 PP.DiscardUntilEndOfDirective();
802 return true;
803 }
Mike Stump11289f42009-09-09 15:08:12 +0000804
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000805 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000806 IntegerBuffer.resize(DigitTok.getLength());
807 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000808 bool Invalid = false;
809 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
810 if (Invalid)
811 return true;
812
Chris Lattnerd66f1722009-04-18 18:35:15 +0000813 // Verify that we have a simple digit-sequence, and compute the value. This
814 // is always a simple digit string computed in decimal, so we do this manually
815 // here.
816 Val = 0;
817 for (unsigned i = 0; i != ActualLength; ++i) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000818 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000819 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
820 diag::err_pp_line_digit_sequence);
821 PP.DiscardUntilEndOfDirective();
822 return true;
823 }
Mike Stump11289f42009-09-09 15:08:12 +0000824
Chris Lattnerd66f1722009-04-18 18:35:15 +0000825 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
826 if (NextVal < Val) { // overflow.
827 PP.Diag(DigitTok, DiagID);
828 PP.DiscardUntilEndOfDirective();
829 return true;
830 }
831 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000832 }
Mike Stump11289f42009-09-09 15:08:12 +0000833
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000834 if (DigitTokBegin[0] == '0' && Val)
Chris Lattnerd66f1722009-04-18 18:35:15 +0000835 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattner76e68962009-01-26 06:19:46 +0000837 return false;
838}
839
James Dennettf6333ac2012-06-22 05:46:07 +0000840/// \brief Handle a \#line directive: C99 6.10.4.
841///
842/// The two acceptable forms are:
843/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000844/// # line digit-sequence
845/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000846/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000847void Preprocessor::HandleLineDirective(Token &Tok) {
848 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
849 // expanded.
850 Token DigitTok;
851 Lex(DigitTok);
852
Chris Lattner100c65e2009-01-26 05:29:08 +0000853 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000854 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000855 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000856 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000857
858 if (LineNo == 0)
859 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000860
Chris Lattner76e68962009-01-26 06:19:46 +0000861 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
862 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000863 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000864 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000865 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000866 if (LineNo >= LineLimit)
867 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000868 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000869 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000870
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000871 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000872 Token StrTok;
873 Lex(StrTok);
874
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000875 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
876 // string followed by eod.
877 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000878 ; // ok
879 else if (StrTok.isNot(tok::string_literal)) {
880 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000881 return DiscardUntilEndOfDirective();
882 } else if (StrTok.hasUDSuffix()) {
883 Diag(StrTok, diag::err_invalid_string_udl);
884 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000885 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000886 // Parse and validate the string, converting it into a unique ID.
887 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000888 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000889 if (Literal.hadError)
890 return DiscardUntilEndOfDirective();
891 if (Literal.Pascal) {
892 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
893 return DiscardUntilEndOfDirective();
894 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000895 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000896
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000897 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000898 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
899 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000900 }
Mike Stump11289f42009-09-09 15:08:12 +0000901
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000902 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000903
Chris Lattner839150e2009-03-27 17:13:49 +0000904 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000905 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
906 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000907 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000908}
909
Chris Lattner76e68962009-01-26 06:19:46 +0000910/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
911/// marker directive.
912static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
913 bool &IsSystemHeader, bool &IsExternCHeader,
914 Preprocessor &PP) {
915 unsigned FlagVal;
916 Token FlagTok;
917 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000918 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000919 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
920 return true;
921
922 if (FlagVal == 1) {
923 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattner76e68962009-01-26 06:19:46 +0000925 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000926 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000927 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
928 return true;
929 } else if (FlagVal == 2) {
930 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000931
Chris Lattner1c967782009-02-04 06:25:26 +0000932 SourceManager &SM = PP.getSourceManager();
933 // If we are leaving the current presumed file, check to make sure the
934 // presumed include stack isn't empty!
935 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000936 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000937 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000938 if (PLoc.isInvalid())
939 return true;
940
Chris Lattner1c967782009-02-04 06:25:26 +0000941 // If there is no include loc (main file) or if the include loc is in a
942 // different physical file, then we aren't in a "1" line marker flag region.
943 SourceLocation IncLoc = PLoc.getIncludeLoc();
944 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000945 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000946 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
947 PP.DiscardUntilEndOfDirective();
948 return true;
949 }
Mike Stump11289f42009-09-09 15:08:12 +0000950
Chris Lattner76e68962009-01-26 06:19:46 +0000951 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000952 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000953 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
954 return true;
955 }
956
957 // We must have 3 if there are still flags.
958 if (FlagVal != 3) {
959 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000960 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000961 return true;
962 }
Mike Stump11289f42009-09-09 15:08:12 +0000963
Chris Lattner76e68962009-01-26 06:19:46 +0000964 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000965
Chris Lattner76e68962009-01-26 06:19:46 +0000966 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000967 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000968 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000969 return true;
970
971 // We must have 4 if there is yet another flag.
972 if (FlagVal != 4) {
973 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000974 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000975 return true;
976 }
Mike Stump11289f42009-09-09 15:08:12 +0000977
Chris Lattner76e68962009-01-26 06:19:46 +0000978 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000979
Chris Lattner76e68962009-01-26 06:19:46 +0000980 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000981 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000982
983 // There are no more valid flags here.
984 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000985 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000986 return true;
987}
988
989/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
990/// one of the following forms:
991///
992/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000993/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000994/// # 42 "file" ('1' | '2')? '3' '4'?
995///
996void Preprocessor::HandleDigitDirective(Token &DigitTok) {
997 // Validate the number and convert it to an unsigned. GNU does not have a
998 // line # limit other than it fit in 32-bits.
999 unsigned LineNo;
1000 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
1001 *this))
1002 return;
Mike Stump11289f42009-09-09 15:08:12 +00001003
Chris Lattner76e68962009-01-26 06:19:46 +00001004 Token StrTok;
1005 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001006
Chris Lattner76e68962009-01-26 06:19:46 +00001007 bool IsFileEntry = false, IsFileExit = false;
1008 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001009 int FilenameID = -1;
1010
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001011 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1012 // string followed by eod.
1013 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001014 ; // ok
1015 else if (StrTok.isNot(tok::string_literal)) {
1016 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001017 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001018 } else if (StrTok.hasUDSuffix()) {
1019 Diag(StrTok, diag::err_invalid_string_udl);
1020 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001021 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001022 // Parse and validate the string, converting it into a unique ID.
1023 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001024 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001025 if (Literal.hadError)
1026 return DiscardUntilEndOfDirective();
1027 if (Literal.Pascal) {
1028 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1029 return DiscardUntilEndOfDirective();
1030 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001031 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001032
Chris Lattner76e68962009-01-26 06:19:46 +00001033 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001034 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001035 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001036 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001037 }
Mike Stump11289f42009-09-09 15:08:12 +00001038
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001039 // Create a line note with this information.
1040 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001041 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001042 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001043
Chris Lattner839150e2009-03-27 17:13:49 +00001044 // If the preprocessor has callbacks installed, notify them of the #line
1045 // change. This is used so that the line marker comes out in -E mode for
1046 // example.
1047 if (Callbacks) {
1048 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1049 if (IsFileEntry)
1050 Reason = PPCallbacks::EnterFile;
1051 else if (IsFileExit)
1052 Reason = PPCallbacks::ExitFile;
1053 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1054 if (IsExternCHeader)
1055 FileKind = SrcMgr::C_ExternCSystem;
1056 else if (IsSystemHeader)
1057 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001058
Chris Lattnerc745cec2010-04-14 04:28:50 +00001059 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001060 }
Chris Lattner76e68962009-01-26 06:19:46 +00001061}
1062
1063
Chris Lattner38d7fd22009-01-26 05:30:54 +00001064/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1065///
Mike Stump11289f42009-09-09 15:08:12 +00001066void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001067 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001068 // PTH doesn't emit #warning or #error directives.
1069 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001070 return CurPTHLexer->DiscardToEndOfLine();
1071
Chris Lattnerf64b3522008-03-09 01:54:53 +00001072 // Read the rest of the line raw. We do this because we don't want macros
1073 // to be expanded and we don't require that the tokens be valid preprocessing
1074 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1075 // collapse multiple consequtive white space between tokens, but this isn't
1076 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001077 SmallString<128> Message;
1078 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001079
1080 // Find the first non-whitespace character, so that we can make the
1081 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001082 StringRef Msg = Message.str().ltrim(" ");
1083
Chris Lattner100c65e2009-01-26 05:29:08 +00001084 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001085 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001086 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001087 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001088}
1089
1090/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1091///
1092void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1093 // Yes, this directive is an extension.
1094 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001095
Chris Lattnerf64b3522008-03-09 01:54:53 +00001096 // Read the string argument.
1097 Token StrTok;
1098 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001099
Chris Lattnerf64b3522008-03-09 01:54:53 +00001100 // If the token kind isn't a string, it's a malformed directive.
1101 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001102 StrTok.isNot(tok::wide_string_literal)) {
1103 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001104 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001105 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001106 return;
1107 }
Mike Stump11289f42009-09-09 15:08:12 +00001108
Richard Smithd67aea22012-03-06 03:21:47 +00001109 if (StrTok.hasUDSuffix()) {
1110 Diag(StrTok, diag::err_invalid_string_udl);
1111 return DiscardUntilEndOfDirective();
1112 }
1113
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001114 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001115 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001116
Douglas Gregordc970f02010-03-16 22:30:13 +00001117 if (Callbacks) {
1118 bool Invalid = false;
1119 std::string Str = getSpelling(StrTok, &Invalid);
1120 if (!Invalid)
1121 Callbacks->Ident(Tok.getLocation(), Str);
1122 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001123}
1124
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001125/// \brief Handle a #public directive.
1126void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001127 Token MacroNameTok;
1128 ReadMacroName(MacroNameTok, 2);
1129
1130 // Error reading macro name? If so, diagnostic already issued.
1131 if (MacroNameTok.is(tok::eod))
1132 return;
1133
Douglas Gregor663b48f2012-01-03 19:48:16 +00001134 // Check to see if this is the last token on the #__public_macro line.
1135 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001136
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001137 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001138 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001139 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001140
1141 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001142 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001143 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001144 return;
1145 }
1146
1147 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001148 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1149 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001150}
1151
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001152/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001153void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1154 Token MacroNameTok;
1155 ReadMacroName(MacroNameTok, 2);
1156
1157 // Error reading macro name? If so, diagnostic already issued.
1158 if (MacroNameTok.is(tok::eod))
1159 return;
1160
Douglas Gregor663b48f2012-01-03 19:48:16 +00001161 // Check to see if this is the last token on the #__private_macro line.
1162 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001163
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001164 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001165 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001166 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001167
1168 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001169 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001170 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001171 return;
1172 }
1173
1174 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001175 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1176 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001177}
1178
Chris Lattnerf64b3522008-03-09 01:54:53 +00001179//===----------------------------------------------------------------------===//
1180// Preprocessor Include Directive Handling.
1181//===----------------------------------------------------------------------===//
1182
1183/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001184/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001185/// true if the input filename was in <>'s or false if it were in ""'s. The
1186/// caller is expected to provide a buffer that is large enough to hold the
1187/// spelling of the filename, but is also expected to handle the case when
1188/// this method decides to use a different buffer.
1189bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001190 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001191 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001192 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001193
Chris Lattnerf64b3522008-03-09 01:54:53 +00001194 // Make sure the filename is <x> or "x".
1195 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001196 if (Buffer[0] == '<') {
1197 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001198 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001199 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001200 return true;
1201 }
1202 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001203 } else if (Buffer[0] == '"') {
1204 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001205 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001206 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001207 return true;
1208 }
1209 isAngled = false;
1210 } else {
1211 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001212 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001213 return true;
1214 }
Mike Stump11289f42009-09-09 15:08:12 +00001215
Chris Lattnerf64b3522008-03-09 01:54:53 +00001216 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001217 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001218 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001219 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001220 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001221 }
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattnerf64b3522008-03-09 01:54:53 +00001223 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001224 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001225 return isAngled;
1226}
1227
James Dennettf6333ac2012-06-22 05:46:07 +00001228/// \brief Handle cases where the \#include name is expanded from a macro
1229/// as multiple tokens, which need to be glued together.
1230///
1231/// This occurs for code like:
1232/// \code
1233/// \#define FOO <a/b.h>
1234/// \#include FOO
1235/// \endcode
Chris Lattnerf64b3522008-03-09 01:54:53 +00001236/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1237///
1238/// This code concatenates and consumes tokens up to the '>' token. It returns
1239/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001240/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001241bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001242 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001243 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001244 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001245
John Thompsonb5353522009-10-30 13:49:06 +00001246 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001247 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001248 End = CurTok.getLocation();
1249
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001250 // FIXME: Provide code completion for #includes.
1251 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001252 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001253 Lex(CurTok);
1254 continue;
1255 }
1256
Chris Lattnerf64b3522008-03-09 01:54:53 +00001257 // Append the spelling of this token to the buffer. If there was a space
1258 // before it, add it now.
1259 if (CurTok.hasLeadingSpace())
1260 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattnerf64b3522008-03-09 01:54:53 +00001262 // Get the spelling of the token, directly into FilenameBuffer if possible.
1263 unsigned PreAppendSize = FilenameBuffer.size();
1264 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001265
Chris Lattnerf64b3522008-03-09 01:54:53 +00001266 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001267 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001268
Chris Lattnerf64b3522008-03-09 01:54:53 +00001269 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1270 if (BufPtr != &FilenameBuffer[PreAppendSize])
1271 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001272
Chris Lattnerf64b3522008-03-09 01:54:53 +00001273 // Resize FilenameBuffer to the correct size.
1274 if (CurTok.getLength() != ActualLen)
1275 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001276
Chris Lattnerf64b3522008-03-09 01:54:53 +00001277 // If we found the '>' marker, return success.
1278 if (CurTok.is(tok::greater))
1279 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001280
John Thompsonb5353522009-10-30 13:49:06 +00001281 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001282 }
1283
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001284 // If we hit the eod marker, emit an error and return true so that the caller
1285 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001286 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001287 return true;
1288}
1289
James Dennettf6333ac2012-06-22 05:46:07 +00001290/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1291/// the file to be included from the lexer, then include it! This is a common
1292/// routine with functionality shared between \#include, \#include_next and
1293/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001294/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001295void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1296 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001297 const DirectoryLookup *LookupFrom,
1298 bool isImport) {
1299
1300 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001301 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001302
Chris Lattnerf64b3522008-03-09 01:54:53 +00001303 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001304 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001305 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001306 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001307 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001308
Chris Lattnerf64b3522008-03-09 01:54:53 +00001309 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001310 case tok::eod:
1311 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001312 return;
Mike Stump11289f42009-09-09 15:08:12 +00001313
Chris Lattnerf64b3522008-03-09 01:54:53 +00001314 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001315 case tok::string_literal:
1316 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001317 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001318 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001319 break;
Mike Stump11289f42009-09-09 15:08:12 +00001320
Chris Lattnerf64b3522008-03-09 01:54:53 +00001321 case tok::less:
1322 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1323 // case, glue the tokens together into FilenameBuffer and interpret those.
1324 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001325 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001326 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001327 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001328 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001329 break;
1330 default:
1331 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1332 DiscardUntilEndOfDirective();
1333 return;
1334 }
Mike Stump11289f42009-09-09 15:08:12 +00001335
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001336 CharSourceRange FilenameRange
1337 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001338 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001339 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001340 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001341 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1342 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001343 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001344 DiscardUntilEndOfDirective();
1345 return;
1346 }
Mike Stump11289f42009-09-09 15:08:12 +00001347
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001348 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001349 // we allow macros that expand to nothing after the filename, because this
1350 // falls into the category of "#include pp-tokens new-line" specified in
1351 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001352 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001353
1354 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001355 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1356 Diag(FilenameTok, diag::err_pp_include_too_deep);
1357 return;
1358 }
Mike Stump11289f42009-09-09 15:08:12 +00001359
John McCall32f5fe12011-09-30 05:12:12 +00001360 // Complain about attempts to #include files in an audit pragma.
1361 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1362 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1363 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1364
1365 // Immediately leave the pragma.
1366 PragmaARCCFCodeAuditedLoc = SourceLocation();
1367 }
1368
Aaron Ballman611306e2012-03-02 22:51:54 +00001369 if (HeaderInfo.HasIncludeAliasMap()) {
1370 // Map the filename with the brackets still attached. If the name doesn't
1371 // map to anything, fall back on the filename we've already gotten the
1372 // spelling for.
1373 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1374 if (!NewName.empty())
1375 Filename = NewName;
1376 }
1377
Chris Lattnerf64b3522008-03-09 01:54:53 +00001378 // Search include directories.
1379 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001380 SmallString<1024> SearchPath;
1381 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001382 // We get the raw path only if we have 'Callbacks' to which we later pass
1383 // the path.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001384 Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001385 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001386 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001387 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001388 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001389
Douglas Gregor11729f02011-11-30 18:12:06 +00001390 if (Callbacks) {
1391 if (!File) {
1392 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001393 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001394 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1395 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1396 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001397 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001398 HeaderInfo.AddSearchPath(DL, isAngled);
1399
1400 // Try the lookup again, skipping the cache.
1401 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001402 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001403 /*SkipCache*/true);
1404 }
1405 }
1406 }
1407
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001408 if (!SuggestedModule) {
1409 // Notify the callback object that we've seen an inclusion directive.
1410 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1411 FilenameRange, File,
1412 SearchPath, RelativePath,
1413 /*ImportedModule=*/0);
1414 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001415 }
1416
1417 if (File == 0) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001418 if (!SuppressIncludeNotFoundError) {
1419 // If the file could not be located and it was included via angle
1420 // brackets, we can attempt a lookup as though it were a quoted path to
1421 // provide the user with a possible fixit.
1422 if (isAngled) {
1423 File = LookupFile(Filename, false, LookupFrom, CurDir,
1424 Callbacks ? &SearchPath : 0,
1425 Callbacks ? &RelativePath : 0,
1426 getLangOpts().Modules ? &SuggestedModule : 0);
1427 if (File) {
1428 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1429 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1430 Filename <<
1431 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1432 }
1433 }
1434 // If the file is still not found, just go with the vanilla diagnostic
1435 if (!File)
1436 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1437 }
1438 if (!File)
1439 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001440 }
1441
Douglas Gregor97eec242011-09-15 22:00:41 +00001442 // If we are supposed to import a module rather than including the header,
1443 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001444 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001445 // Compute the module access path corresponding to this module.
1446 // FIXME: Should we have a second loadModule() overload to avoid this
1447 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001448 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregorde3ef502011-11-30 23:21:26 +00001449 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001450 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1451 FilenameTok.getLocation()));
1452 std::reverse(Path.begin(), Path.end());
1453
Douglas Gregor41e115a2011-11-30 18:02:36 +00001454 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001455 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001456 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1457 if (I)
1458 PathString += '.';
1459 PathString += Path[I].first->getName();
1460 }
1461 int IncludeKind = 0;
1462
1463 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1464 case tok::pp_include:
1465 IncludeKind = 0;
1466 break;
1467
1468 case tok::pp_import:
1469 IncludeKind = 1;
1470 break;
1471
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001472 case tok::pp_include_next:
1473 IncludeKind = 2;
1474 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001475
1476 case tok::pp___include_macros:
1477 IncludeKind = 3;
1478 break;
1479
1480 default:
1481 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001482 }
1483
Douglas Gregor2537a362011-12-08 17:01:29 +00001484 // Determine whether we are actually building the module that this
1485 // include directive maps to.
1486 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001487 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001488
David Blaikiebbafb8a2012-03-11 07:00:24 +00001489 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001490 // If we're not building the imported module, warn that we're going
1491 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001492 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001493 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1494 /*IsTokenRange=*/false);
1495 Diag(HashLoc, diag::warn_auto_module_import)
1496 << IncludeKind << PathString
1497 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001498 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001499 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001500
Douglas Gregor71944202011-11-30 00:36:36 +00001501 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001502 // If this was an #__include_macros directive, only make macros visible.
1503 Module::NameVisibilityKind Visibility
1504 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001505 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001506 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1507 /*IsIncludeDirective=*/true);
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001508 assert((Imported == 0 || Imported == SuggestedModule) &&
1509 "the imported module is different than the suggested one");
Douglas Gregor2537a362011-12-08 17:01:29 +00001510
1511 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001512 if (!BuildingImportedModule && Imported) {
1513 if (Callbacks) {
1514 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1515 FilenameRange, File,
1516 SearchPath, RelativePath, Imported);
1517 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001518 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001519 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001520
1521 // If we failed to find a submodule that we expected to find, we can
1522 // continue. Otherwise, there's an error in the included file, so we
1523 // don't want to include it.
1524 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1525 return;
1526 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001527 }
1528
1529 if (Callbacks && SuggestedModule) {
1530 // We didn't notify the callback object that we've seen an inclusion
1531 // directive before. Now that we are parsing the include normally and not
1532 // turning it to a module import, notify the callback object.
1533 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1534 FilenameRange, File,
1535 SearchPath, RelativePath,
1536 /*ImportedModule=*/0);
Douglas Gregor97eec242011-09-15 22:00:41 +00001537 }
1538
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001539 // The #included file will be considered to be a system header if either it is
1540 // in a system include directory, or if the #includer is a system include
1541 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001542 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001543 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001544 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001545
Chris Lattner72286d62010-04-19 20:44:31 +00001546 // Ask HeaderInfo if we should enter this #include file. If not, #including
1547 // this file will have no effect.
1548 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001549 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001550 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001551 return;
1552 }
1553
Chris Lattnerf64b3522008-03-09 01:54:53 +00001554 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001555 SourceLocation IncludePos = End;
1556 // If the filename string was the result of macro expansions, set the include
1557 // position on the file where it will be included and after the expansions.
1558 if (IncludePos.isMacroID())
1559 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1560 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001561 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001562
1563 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001564 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001565}
1566
James Dennettf6333ac2012-06-22 05:46:07 +00001567/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001568///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001569void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1570 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001571 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattnerf64b3522008-03-09 01:54:53 +00001573 // #include_next is like #include, except that we start searching after
1574 // the current found directory. If we can't do this, issue a
1575 // diagnostic.
1576 const DirectoryLookup *Lookup = CurDirLookup;
1577 if (isInPrimaryFile()) {
1578 Lookup = 0;
1579 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1580 } else if (Lookup == 0) {
1581 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1582 } else {
1583 // Start looking up in the next directory.
1584 ++Lookup;
1585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
Douglas Gregor796d76a2010-10-20 22:00:55 +00001587 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001588}
1589
James Dennettf6333ac2012-06-22 05:46:07 +00001590/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001591void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1592 // The Microsoft #import directive takes a type library and generates header
1593 // files from it, and includes those. This is beyond the scope of what clang
1594 // does, so we ignore it and error out. However, #import can optionally have
1595 // trailing attributes that span multiple lines. We're going to eat those
1596 // so we can continue processing from there.
1597 Diag(Tok, diag::err_pp_import_directive_ms );
1598
1599 // Read tokens until we get to the end of the directive. Note that the
1600 // directive can be split over multiple lines using the backslash character.
1601 DiscardUntilEndOfDirective();
1602}
1603
James Dennettf6333ac2012-06-22 05:46:07 +00001604/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001605///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001606void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1607 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001608 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1609 if (LangOpts.MicrosoftMode)
1610 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001611 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001612 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001613 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001614}
1615
Chris Lattner58a1eb02009-04-08 18:46:40 +00001616/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1617/// pseudo directive in the predefines buffer. This handles it by sucking all
1618/// tokens through the preprocessor and discarding them (only keeping the side
1619/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001620void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1621 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001622 // This directive should only occur in the predefines buffer. If not, emit an
1623 // error and reject it.
1624 SourceLocation Loc = IncludeMacrosTok.getLocation();
1625 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1626 Diag(IncludeMacrosTok.getLocation(),
1627 diag::pp_include_macros_out_of_predefines);
1628 DiscardUntilEndOfDirective();
1629 return;
1630 }
Mike Stump11289f42009-09-09 15:08:12 +00001631
Chris Lattnere01d82b2009-04-08 20:53:24 +00001632 // Treat this as a normal #include for checking purposes. If this is
1633 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001634 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001635
Chris Lattnere01d82b2009-04-08 20:53:24 +00001636 Token TmpTok;
1637 do {
1638 Lex(TmpTok);
1639 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1640 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001641}
1642
Chris Lattnerf64b3522008-03-09 01:54:53 +00001643//===----------------------------------------------------------------------===//
1644// Preprocessor Macro Directive Handling.
1645//===----------------------------------------------------------------------===//
1646
1647/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1648/// definition has just been read. Lex the rest of the arguments and the
1649/// closing ), updating MI with what we learn. Return true if an error occurs
1650/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001651bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001652 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001653
Chris Lattnerf64b3522008-03-09 01:54:53 +00001654 while (1) {
1655 LexUnexpandedToken(Tok);
1656 switch (Tok.getKind()) {
1657 case tok::r_paren:
1658 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001659 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001660 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001661 // Otherwise we have #define FOO(A,)
1662 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1663 return true;
1664 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001665 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001666 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001667 diag::warn_cxx98_compat_variadic_macro :
1668 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001669
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001670 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1671 if (LangOpts.OpenCL) {
1672 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1673 return true;
1674 }
1675
Chris Lattnerf64b3522008-03-09 01:54:53 +00001676 // Lex the token after the identifier.
1677 LexUnexpandedToken(Tok);
1678 if (Tok.isNot(tok::r_paren)) {
1679 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1680 return true;
1681 }
1682 // Add the __VA_ARGS__ identifier as an argument.
1683 Arguments.push_back(Ident__VA_ARGS__);
1684 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001685 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001686 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001687 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001688 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1689 return true;
1690 default:
1691 // Handle keywords and identifiers here to accept things like
1692 // #define Foo(for) for.
1693 IdentifierInfo *II = Tok.getIdentifierInfo();
1694 if (II == 0) {
1695 // #define X(1
1696 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1697 return true;
1698 }
1699
1700 // If this is already used as an argument, it is used multiple times (e.g.
1701 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001702 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001703 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001704 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001705 return true;
1706 }
Mike Stump11289f42009-09-09 15:08:12 +00001707
Chris Lattnerf64b3522008-03-09 01:54:53 +00001708 // Add the argument to the macro info.
1709 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001710
Chris Lattnerf64b3522008-03-09 01:54:53 +00001711 // Lex the token after the identifier.
1712 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001713
Chris Lattnerf64b3522008-03-09 01:54:53 +00001714 switch (Tok.getKind()) {
1715 default: // #define X(A B
1716 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1717 return true;
1718 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001719 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001720 return false;
1721 case tok::comma: // #define X(A,
1722 break;
1723 case tok::ellipsis: // #define X(A... -> GCC extension
1724 // Diagnose extension.
1725 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001726
Chris Lattnerf64b3522008-03-09 01:54:53 +00001727 // Lex the token after the identifier.
1728 LexUnexpandedToken(Tok);
1729 if (Tok.isNot(tok::r_paren)) {
1730 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1731 return true;
1732 }
Mike Stump11289f42009-09-09 15:08:12 +00001733
Chris Lattnerf64b3522008-03-09 01:54:53 +00001734 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001735 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001736 return false;
1737 }
1738 }
1739 }
1740}
1741
James Dennettf6333ac2012-06-22 05:46:07 +00001742/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001743/// line then lets the caller lex the next real token.
1744void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1745 ++NumDefined;
1746
1747 Token MacroNameTok;
1748 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001749
Chris Lattnerf64b3522008-03-09 01:54:53 +00001750 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001751 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001752 return;
1753
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001754 Token LastTok = MacroNameTok;
1755
Chris Lattnerf64b3522008-03-09 01:54:53 +00001756 // If we are supposed to keep comments in #defines, reenable comment saving
1757 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001758 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001759
Chris Lattnerf64b3522008-03-09 01:54:53 +00001760 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001761 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001762
Chris Lattnerf64b3522008-03-09 01:54:53 +00001763 Token Tok;
1764 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001765
Chris Lattnerf64b3522008-03-09 01:54:53 +00001766 // If this is a function-like macro definition, parse the argument list,
1767 // marking each of the identifiers as being used as macro arguments. Also,
1768 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001769 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001770 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001771 } else if (Tok.hasLeadingSpace()) {
1772 // This is a normal token with leading space. Clear the leading space
1773 // marker on the first token to get proper expansion.
1774 Tok.clearFlag(Token::LeadingSpace);
1775 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001776 // This is a function-like macro definition. Read the argument list.
1777 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001778 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001779 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001780 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001781 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001782 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001783 DiscardUntilEndOfDirective();
1784 return;
1785 }
1786
Chris Lattner249c38b2009-04-19 18:26:34 +00001787 // If this is a definition of a variadic C99 function-like macro, not using
1788 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001789
Chris Lattner249c38b2009-04-19 18:26:34 +00001790 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1791 // This gets unpoisoned where it is allowed.
1792 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1793 if (MI->isC99Varargs())
1794 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001795
Chris Lattnerf64b3522008-03-09 01:54:53 +00001796 // Read the first token after the arg list for down below.
1797 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001798 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001799 // C99 requires whitespace between the macro definition and the body. Emit
1800 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001801 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001802 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001803 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1804 // first character of a replacement list is not a character required by
1805 // subclause 5.2.1, then there shall be white-space separation between the
1806 // identifier and the replacement list.". 5.2.1 lists this set:
1807 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1808 // is irrelevant here.
1809 bool isInvalid = false;
1810 if (Tok.is(tok::at)) // @ is not in the list above.
1811 isInvalid = true;
1812 else if (Tok.is(tok::unknown)) {
1813 // If we have an unknown token, it is something strange like "`". Since
1814 // all of valid characters would have lexed into a single character
1815 // token of some sort, we know this is not a valid case.
1816 isInvalid = true;
1817 }
1818 if (isInvalid)
1819 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1820 else
1821 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001822 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001823
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001824 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001825 LastTok = Tok;
1826
Chris Lattnerf64b3522008-03-09 01:54:53 +00001827 // Read the rest of the macro body.
1828 if (MI->isObjectLike()) {
1829 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001830 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001831 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001832 MI->AddTokenToBody(Tok);
1833 // Get the next token of the macro.
1834 LexUnexpandedToken(Tok);
1835 }
Mike Stump11289f42009-09-09 15:08:12 +00001836
Chris Lattnerf64b3522008-03-09 01:54:53 +00001837 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001838 // Otherwise, read the body of a function-like macro. While we are at it,
1839 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1840 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001841 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001842 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001843
Eli Friedman14d3c792012-11-14 02:18:46 +00001844 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001845 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001846
Chris Lattnerf64b3522008-03-09 01:54:53 +00001847 // Get the next token of the macro.
1848 LexUnexpandedToken(Tok);
1849 continue;
1850 }
Mike Stump11289f42009-09-09 15:08:12 +00001851
Eli Friedman14d3c792012-11-14 02:18:46 +00001852 if (Tok.is(tok::hashhash)) {
1853
1854 // If we see token pasting, check if it looks like the gcc comma
1855 // pasting extension. We'll use this information to suppress
1856 // diagnostics later on.
1857
1858 // Get the next token of the macro.
1859 LexUnexpandedToken(Tok);
1860
1861 if (Tok.is(tok::eod)) {
1862 MI->AddTokenToBody(LastTok);
1863 break;
1864 }
1865
1866 unsigned NumTokens = MI->getNumTokens();
1867 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1868 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1869 MI->setHasCommaPasting();
1870
1871 // Things look ok, add the '##' and param name tokens to the macro.
1872 MI->AddTokenToBody(LastTok);
1873 MI->AddTokenToBody(Tok);
1874 LastTok = Tok;
1875
1876 // Get the next token of the macro.
1877 LexUnexpandedToken(Tok);
1878 continue;
1879 }
1880
Chris Lattnerf64b3522008-03-09 01:54:53 +00001881 // Get the next token of the macro.
1882 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001883
Chris Lattner83bd8282009-05-25 17:16:10 +00001884 // Check for a valid macro arg identifier.
1885 if (Tok.getIdentifierInfo() == 0 ||
1886 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1887
1888 // If this is assembler-with-cpp mode, we accept random gibberish after
1889 // the '#' because '#' is often a comment character. However, change
1890 // the kind of the token to tok::unknown so that the preprocessor isn't
1891 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001892 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001893 LastTok.setKind(tok::unknown);
1894 } else {
1895 Diag(Tok, diag::err_pp_stringize_not_parameter);
1896 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001897
Chris Lattner83bd8282009-05-25 17:16:10 +00001898 // Disable __VA_ARGS__ again.
1899 Ident__VA_ARGS__->setIsPoisoned(true);
1900 return;
1901 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001902 }
Mike Stump11289f42009-09-09 15:08:12 +00001903
Chris Lattner83bd8282009-05-25 17:16:10 +00001904 // Things look ok, add the '#' and param name tokens to the macro.
1905 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001906 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001907 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001908
Chris Lattnerf64b3522008-03-09 01:54:53 +00001909 // Get the next token of the macro.
1910 LexUnexpandedToken(Tok);
1911 }
1912 }
Mike Stump11289f42009-09-09 15:08:12 +00001913
1914
Chris Lattnerf64b3522008-03-09 01:54:53 +00001915 // Disable __VA_ARGS__ again.
1916 Ident__VA_ARGS__->setIsPoisoned(true);
1917
Chris Lattner57540c52011-04-15 05:22:18 +00001918 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001919 // replacement list.
1920 unsigned NumTokens = MI->getNumTokens();
1921 if (NumTokens != 0) {
1922 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1923 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001924 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001925 return;
1926 }
1927 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1928 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001929 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001930 return;
1931 }
1932 }
Mike Stump11289f42009-09-09 15:08:12 +00001933
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001934 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001935
Chris Lattnerf64b3522008-03-09 01:54:53 +00001936 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00001937 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001938 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001939 // It is very common for system headers to have tons of macro redefinitions
1940 // and for warnings to be disabled in system headers. If this is the case,
1941 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001942 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001943 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001944 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001945 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001946
Richard Smith7b242542013-03-06 00:46:00 +00001947 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
1948 // C++ [cpp.predefined]p4, but allow it as an extension.
1949 if (OtherMI->isBuiltinMacro())
1950 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001951 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001952 // separation must be the same. C99 6.10.3.2.
Richard Smith7b242542013-03-06 00:46:00 +00001953 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
1954 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001955 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1956 << MacroNameTok.getIdentifierInfo();
1957 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1958 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001959 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001960 if (OtherMI->isWarnIfUnused())
1961 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001964 DefMacroDirective *MD =
1965 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001966
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001967 assert(!MI->isUsed());
1968 // If we need warning for not using the macro, add its location in the
1969 // warn-because-unused-macro set. If it gets used it will be removed from set.
1970 if (isInPrimaryFile() && // don't warn for include'd macros.
1971 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00001972 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001973 MI->setIsWarnIfUnused(true);
1974 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1975 }
1976
Chris Lattner928e9092009-04-12 01:39:54 +00001977 // If the callbacks want to know, tell them about the macro definition.
1978 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00001979 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001980}
1981
James Dennettf6333ac2012-06-22 05:46:07 +00001982/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001983///
1984void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1985 ++NumUndefined;
1986
1987 Token MacroNameTok;
1988 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001989
Chris Lattnerf64b3522008-03-09 01:54:53 +00001990 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001991 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001992 return;
Mike Stump11289f42009-09-09 15:08:12 +00001993
Chris Lattnerf64b3522008-03-09 01:54:53 +00001994 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001995 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001996
Chris Lattnerf64b3522008-03-09 01:54:53 +00001997 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001998 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001999 const MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Mike Stump11289f42009-09-09 15:08:12 +00002000
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002001 // If the callbacks want to know, tell them about the macro #undef.
2002 // Note: no matter if the macro was defined or not.
2003 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002004 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002005
Chris Lattnerf64b3522008-03-09 01:54:53 +00002006 // If the macro is not defined, this is a noop undef, just return.
2007 if (MI == 0) return;
2008
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002009 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002010 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002011
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002012 if (MI->isWarnIfUnused())
2013 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2014
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002015 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2016 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002017}
2018
2019
2020//===----------------------------------------------------------------------===//
2021// Preprocessor Conditional Directive Handling.
2022//===----------------------------------------------------------------------===//
2023
James Dennettf6333ac2012-06-22 05:46:07 +00002024/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2025/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2026/// true if any tokens have been returned or pp-directives activated before this
2027/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002028///
2029void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2030 bool ReadAnyTokensBeforeDirective) {
2031 ++NumIf;
2032 Token DirectiveTok = Result;
2033
2034 Token MacroNameTok;
2035 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002036
Chris Lattnerf64b3522008-03-09 01:54:53 +00002037 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002038 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002039 // Skip code until we get to #endif. This helps with recovery by not
2040 // emitting an error when the #endif is reached.
2041 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2042 /*Foundnonskip*/false, /*FoundElse*/false);
2043 return;
2044 }
Mike Stump11289f42009-09-09 15:08:12 +00002045
Chris Lattnerf64b3522008-03-09 01:54:53 +00002046 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002047 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002048
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002049 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002050 MacroDirective *MD = getMacroDirective(MII);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002051 MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002052
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002053 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002054 // If the start of a top-level #ifdef and if the macro is not defined,
2055 // inform MIOpt that this might be the start of a proper include guard.
2056 // Otherwise it is some other form of unknown conditional which we can't
2057 // handle.
2058 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002059 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002060 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002061 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002062 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002063 }
2064
Chris Lattnerf64b3522008-03-09 01:54:53 +00002065 // If there is a macro, process it.
2066 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002067 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002068
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002069 if (Callbacks) {
2070 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002071 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002072 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002073 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002074 }
2075
Chris Lattnerf64b3522008-03-09 01:54:53 +00002076 // Should we include the stuff contained by this directive?
2077 if (!MI == isIfndef) {
2078 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002079 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2080 /*wasskip*/false, /*foundnonskip*/true,
2081 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002082 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002083 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002084 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002085 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002086 /*FoundElse*/false);
2087 }
2088}
2089
James Dennettf6333ac2012-06-22 05:46:07 +00002090/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002091///
2092void Preprocessor::HandleIfDirective(Token &IfToken,
2093 bool ReadAnyTokensBeforeDirective) {
2094 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002095
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002096 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002097 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002098 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2099 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2100 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002101
2102 // If this condition is equivalent to #ifndef X, and if this is the first
2103 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002104 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002105 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002106 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00002107 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002108 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002109 }
2110
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002111 if (Callbacks)
2112 Callbacks->If(IfToken.getLocation(),
2113 SourceRange(ConditionalBegin, ConditionalEnd));
2114
Chris Lattnerf64b3522008-03-09 01:54:53 +00002115 // Should we include the stuff contained by this directive?
2116 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002117 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002118 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002119 /*foundnonskip*/true, /*foundelse*/false);
2120 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002121 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002122 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002123 /*FoundElse*/false);
2124 }
2125}
2126
James Dennettf6333ac2012-06-22 05:46:07 +00002127/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002128///
2129void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2130 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002131
Chris Lattnerf64b3522008-03-09 01:54:53 +00002132 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002133 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002134
Chris Lattnerf64b3522008-03-09 01:54:53 +00002135 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002136 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002137 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002138 Diag(EndifToken, diag::err_pp_endif_without_if);
2139 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002140 }
Mike Stump11289f42009-09-09 15:08:12 +00002141
Chris Lattnerf64b3522008-03-09 01:54:53 +00002142 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002143 if (CurPPLexer->getConditionalStackDepth() == 0)
2144 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002145
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002146 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002147 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002148
2149 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002150 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002151}
2152
James Dennettf6333ac2012-06-22 05:46:07 +00002153/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002154///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002155void Preprocessor::HandleElseDirective(Token &Result) {
2156 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002157
Chris Lattnerf64b3522008-03-09 01:54:53 +00002158 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002159 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002160
Chris Lattnerf64b3522008-03-09 01:54:53 +00002161 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002162 if (CurPPLexer->popConditionalLevel(CI)) {
2163 Diag(Result, diag::pp_err_else_without_if);
2164 return;
2165 }
Mike Stump11289f42009-09-09 15:08:12 +00002166
Chris Lattnerf64b3522008-03-09 01:54:53 +00002167 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002168 if (CurPPLexer->getConditionalStackDepth() == 0)
2169 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002170
2171 // If this is a #else with a #else before it, report the error.
2172 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002173
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002174 if (Callbacks)
2175 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2176
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002177 // Finally, skip the rest of the contents of this block.
2178 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002179 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002180}
2181
James Dennettf6333ac2012-06-22 05:46:07 +00002182/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002183///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002184void Preprocessor::HandleElifDirective(Token &ElifToken) {
2185 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002186
Chris Lattnerf64b3522008-03-09 01:54:53 +00002187 // #elif directive in a non-skipping conditional... start skipping.
2188 // We don't care what the condition is, because we will always skip it (since
2189 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002190 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002191 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002192 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002193
2194 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002195 if (CurPPLexer->popConditionalLevel(CI)) {
2196 Diag(ElifToken, diag::pp_err_elif_without_if);
2197 return;
2198 }
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chris Lattnerf64b3522008-03-09 01:54:53 +00002200 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002201 if (CurPPLexer->getConditionalStackDepth() == 0)
2202 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002203
Chris Lattnerf64b3522008-03-09 01:54:53 +00002204 // If this is a #elif with a #else before it, report the error.
2205 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002206
2207 if (Callbacks)
2208 Callbacks->Elif(ElifToken.getLocation(),
2209 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002210
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002211 // Finally, skip the rest of the contents of this block.
2212 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002213 /*FoundElse*/CI.FoundElse,
2214 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002215}