blob: cea0798f6e514758c918b83b6acd1f5dd3d0d7b2 [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//===----------------------------------------------------------------------===//
9//
10// This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor3a7ad252010-08-24 19:08:16 +000019#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregorc7d65762010-09-09 22:45:38 +000020#include "clang/Lex/Pragma.h"
Chris Lattner710bb872009-11-30 04:18:44 +000021#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000023#include "llvm/ADT/APInt.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000024using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Utility Methods for Preprocessor Directive Handling.
28//===----------------------------------------------------------------------===//
29
Chris Lattnerc0a585d2010-08-17 15:55:45 +000030MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000031 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000032
Ted Kremenekc8456f82010-10-19 22:15:20 +000033 if (MICache) {
34 MIChain = MICache;
35 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000036 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000037 else {
38 MIChain = BP.Allocate<MacroInfoChain>();
39 }
40
41 MIChain->Next = MIChainHead;
42 MIChain->Prev = 0;
43 if (MIChainHead)
44 MIChainHead->Prev = MIChain;
45 MIChainHead = MIChain;
46
47 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000048}
49
50MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
51 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000052 new (MI) MacroInfo(L);
53 return MI;
54}
55
Chris Lattnerc0a585d2010-08-17 15:55:45 +000056MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
57 MacroInfo *MI = AllocateMacroInfo();
58 new (MI) MacroInfo(MacroToClone, BP);
59 return MI;
60}
61
Chris Lattner666f7a42009-02-20 22:19:20 +000062/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
63/// be reused for allocating new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +000064void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +000065 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
66 if (MacroInfoChain *Prev = MIChain->Prev) {
67 MacroInfoChain *Next = MIChain->Next;
68 Prev->Next = Next;
69 if (Next)
70 Next->Prev = Prev;
71 }
72 else {
73 assert(MIChainHead == MIChain);
74 MIChainHead = MIChain->Next;
75 MIChainHead->Prev = 0;
76 }
77 MIChain->Next = MICache;
78 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +000079
Ted Kremenekc8456f82010-10-19 22:15:20 +000080 MI->Destroy();
81}
Chris Lattner666f7a42009-02-20 22:19:20 +000082
Chris Lattnerf64b3522008-03-09 01:54:53 +000083/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000084/// current line until the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000085void Preprocessor::DiscardUntilEndOfDirective() {
86 Token Tmp;
87 do {
88 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000089 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000090 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000091}
92
Chris Lattnerf64b3522008-03-09 01:54:53 +000093/// ReadMacroName - Lex and validate a macro name, which occurs after a
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000094/// #define or #undef. This sets the token kind to eod and discards the rest
Chris Lattnerf64b3522008-03-09 01:54:53 +000095/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
96/// this is due to a a #define, 2 if #undef directive, 0 if it is something
97/// else (e.g. #ifdef).
98void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
99 // Read the token, don't allow macro expansion on it.
100 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000101
Douglas Gregor12785102010-08-24 20:21:13 +0000102 if (MacroNameTok.is(tok::code_completion)) {
103 if (CodeComplete)
104 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
105 LexUnexpandedToken(MacroNameTok);
106 return;
107 }
108
Chris Lattnerf64b3522008-03-09 01:54:53 +0000109 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000110 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000111 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
112 return;
113 }
Mike Stump11289f42009-09-09 15:08:12 +0000114
Chris Lattnerf64b3522008-03-09 01:54:53 +0000115 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
116 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000117 bool Invalid = false;
118 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
119 if (Invalid)
120 return;
121
Chris Lattner77c76ae2008-12-13 20:12:40 +0000122 const IdentifierInfo &Info = Identifiers.get(Spelling);
123 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000124 // C++ 2.5p2: Alternative tokens behave the same as its primary token
125 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000126 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000127 else
128 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
129 // Fall through on error.
130 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
131 // Error if defining "defined": C99 6.10.8.4.
132 Diag(MacroNameTok, diag::err_defined_macro_name);
133 } else if (isDefineUndef && II->hasMacroDefinition() &&
134 getMacroInfo(II)->isBuiltinMacro()) {
135 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
136 if (isDefineUndef == 1)
137 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
138 else
139 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
140 } else {
141 // Okay, we got a good identifier node. Return it.
142 return;
143 }
Mike Stump11289f42009-09-09 15:08:12 +0000144
Chris Lattnerf64b3522008-03-09 01:54:53 +0000145 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000146 // token kind to tok::eod.
147 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000148 return DiscardUntilEndOfDirective();
149}
150
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000151/// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
152/// not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000153/// true, then we consider macros that expand to zero tokens as being ok.
154void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000155 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000156 // Lex unexpanded tokens for most directives: macros might expand to zero
157 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
158 // #line) allow empty macros.
159 if (EnableMacros)
160 Lex(Tmp);
161 else
162 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000163
Chris Lattnerf64b3522008-03-09 01:54:53 +0000164 // There should be no tokens after the directive, but we allow them as an
165 // extension.
166 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
167 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000168
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000169 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000170 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000171 // or if this is a macro-style preprocessing directive, because it is more
172 // trouble than it is worth to insert /**/ and check that there is no /**/
173 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000174 FixItHint Hint;
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000175 if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
176 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000177 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
178 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000179 DiscardUntilEndOfDirective();
180 }
181}
182
183
184
185/// SkipExcludedConditionalBlock - We just read a #if or related directive and
186/// decided that the subsequent tokens are in the #if'd out portion of the
187/// file. Lex the rest of the file, until we see an #endif. If
188/// FoundNonSkipPortion is true, then we have already emitted code for part of
189/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
190/// is true, then #else directives are ok, if not, then we have already seen one
191/// so a #else directive is a duplicate. When this returns, the caller can lex
192/// the first valid token.
193void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
194 bool FoundNonSkipPortion,
195 bool FoundElse) {
196 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000197 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000198
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000199 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000200 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000201
Ted Kremenek56572ab2008-12-12 18:34:08 +0000202 if (CurPTHLexer) {
203 PTHSkipExcludedConditionalBlock();
204 return;
205 }
Mike Stump11289f42009-09-09 15:08:12 +0000206
Chris Lattnerf64b3522008-03-09 01:54:53 +0000207 // Enter raw mode to disable identifier lookup (and thus macro expansion),
208 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000209 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000210 Token Tok;
211 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000212 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000213
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000214 if (Tok.is(tok::code_completion)) {
215 if (CodeComplete)
216 CodeComplete->CodeCompleteInConditionalExclusion();
217 continue;
218 }
219
Chris Lattnerf64b3522008-03-09 01:54:53 +0000220 // If this is the end of the buffer, we have an error.
221 if (Tok.is(tok::eof)) {
222 // Emit errors for each unterminated conditional on the stack, including
223 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000224 while (!CurPPLexer->ConditionalStack.empty()) {
Douglas Gregor02690ba2010-08-12 17:04:55 +0000225 if (!isCodeCompletionFile(Tok.getLocation()))
226 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
227 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000228 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000229 }
230
Chris Lattnerf64b3522008-03-09 01:54:53 +0000231 // Just return and let the caller lex after this #include.
232 break;
233 }
Mike Stump11289f42009-09-09 15:08:12 +0000234
Chris Lattnerf64b3522008-03-09 01:54:53 +0000235 // If this token is not a preprocessor directive, just skip it.
236 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
237 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000238
Chris Lattnerf64b3522008-03-09 01:54:53 +0000239 // We just parsed a # character at the start of a line, so we're in
240 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000241 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000242 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000243 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000244
Mike Stump11289f42009-09-09 15:08:12 +0000245
Chris Lattnerf64b3522008-03-09 01:54:53 +0000246 // Read the next token, the directive flavor.
247 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattnerf64b3522008-03-09 01:54:53 +0000249 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
250 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000251 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000252 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000253 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000254 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000255 continue;
256 }
257
258 // If the first letter isn't i or e, it isn't intesting to us. We know that
259 // this is safe in the face of spelling differences, because there is no way
260 // to spell an i/e in a strange way that is another letter. Skipping this
261 // allows us to avoid looking up the identifier info for #define/#undef and
262 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000263 const char *RawCharData = Tok.getRawIdentifierData();
264
Chris Lattnerf64b3522008-03-09 01:54:53 +0000265 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000266 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000267 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000268 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000269 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000270 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000271 continue;
272 }
Mike Stump11289f42009-09-09 15:08:12 +0000273
Chris Lattnerf64b3522008-03-09 01:54:53 +0000274 // Get the identifier name without trigraphs or embedded newlines. Note
275 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
276 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000277 char DirectiveBuf[20];
278 llvm::StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000279 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramer144884642009-12-31 13:32:38 +0000280 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000281 } else {
282 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000283 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000284 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000285 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000286 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000287 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000288 continue;
289 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000290 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
291 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000292 }
Mike Stump11289f42009-09-09 15:08:12 +0000293
Benjamin Kramer144884642009-12-31 13:32:38 +0000294 if (Directive.startswith("if")) {
295 llvm::StringRef Sub = Directive.substr(2);
296 if (Sub.empty() || // "if"
297 Sub == "def" || // "ifdef"
298 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000299 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
300 // bother parsing the condition.
301 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000302 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000303 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000304 /*foundelse*/false);
305
306 if (Callbacks)
307 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000308 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000309 } else if (Directive[0] == 'e') {
310 llvm::StringRef Sub = Directive.substr(1);
311 if (Sub == "ndif") { // "endif"
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000312 CheckEndOfDirective("endif");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000313 PPConditionalInfo CondInfo;
314 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000315 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000316 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000317 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000318
Chris Lattnerf64b3522008-03-09 01:54:53 +0000319 // If we popped the outermost skipping block, we're done skipping!
320 if (!CondInfo.WasSkipping)
321 break;
Benjamin Kramer144884642009-12-31 13:32:38 +0000322 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000323 // #else directive in a skipping conditional. If not in some other
324 // skipping conditional, and if #else hasn't already been seen, enter it
325 // as a non-skipping conditional.
Chris Lattnerbc63de12009-04-18 01:34:22 +0000326 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000327 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000328
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 // If this is a #else with a #else before it, report the error.
330 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000331
Chris Lattnerf64b3522008-03-09 01:54:53 +0000332 // Note that we've seen a #else in this conditional.
333 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000334
Chandler Carruth540960f2011-01-03 17:40:17 +0000335 if (Callbacks)
336 Callbacks->Else();
337
Chris Lattnerf64b3522008-03-09 01:54:53 +0000338 // If the conditional is at the top level, and the #if block wasn't
339 // entered, enter the #else block now.
340 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
341 CondInfo.FoundNonSkip = true;
342 break;
343 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000344 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000345 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000346
347 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000348 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000349 // If this is in a skipping block or if we're already handled this #if
350 // block, don't bother parsing the condition.
351 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
352 DiscardUntilEndOfDirective();
353 ShouldEnter = false;
354 } else {
355 // Restore the value of LexingRawMode so that identifiers are
356 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000357 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
358 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000359 IdentifierInfo *IfNDefMacro = 0;
360 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000361 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000363 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000364
Chris Lattnerf64b3522008-03-09 01:54:53 +0000365 // If this is a #elif with a #else before it, report the error.
366 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chandler Carruth540960f2011-01-03 17:40:17 +0000368 if (Callbacks)
369 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
370
Chris Lattnerf64b3522008-03-09 01:54:53 +0000371 // If this condition is true, enter it!
372 if (ShouldEnter) {
373 CondInfo.FoundNonSkip = true;
374 break;
375 }
376 }
377 }
Mike Stump11289f42009-09-09 15:08:12 +0000378
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000379 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000380 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000381 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000382 }
383
384 // Finally, if we are out of the conditional (saw an #endif or ran off the end
385 // of the file, just stop skipping and return to lexing whatever came after
386 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000387 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000388}
389
Ted Kremenek56572ab2008-12-12 18:34:08 +0000390void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000391
392 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000393 assert(CurPTHLexer);
394 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000395
Ted Kremenek56572ab2008-12-12 18:34:08 +0000396 // Skip to the next '#else', '#elif', or #endif.
397 if (CurPTHLexer->SkipBlock()) {
398 // We have reached an #endif. Both the '#' and 'endif' tokens
399 // have been consumed by the PTHLexer. Just pop off the condition level.
400 PPConditionalInfo CondInfo;
401 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000402 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000403 assert(!InCond && "Can't be skipping if not in a conditional!");
404 break;
405 }
Mike Stump11289f42009-09-09 15:08:12 +0000406
Ted Kremenek56572ab2008-12-12 18:34:08 +0000407 // We have reached a '#else' or '#elif'. Lex the next token to get
408 // the directive flavor.
409 Token Tok;
410 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000411
Ted Kremenek56572ab2008-12-12 18:34:08 +0000412 // We can actually look up the IdentifierInfo here since we aren't in
413 // raw mode.
414 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
415
416 if (K == tok::pp_else) {
417 // #else: Enter the else condition. We aren't in a nested condition
418 // since we skip those. We're always in the one matching the last
419 // blocked we skipped.
420 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
421 // Note that we've seen a #else in this conditional.
422 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000423
Ted Kremenek56572ab2008-12-12 18:34:08 +0000424 // If the #if block wasn't entered then enter the #else block now.
425 if (!CondInfo.FoundNonSkip) {
426 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000427
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000428 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000429 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000430 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000431 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000432
Ted Kremenek56572ab2008-12-12 18:34:08 +0000433 break;
434 }
Mike Stump11289f42009-09-09 15:08:12 +0000435
Ted Kremenek56572ab2008-12-12 18:34:08 +0000436 // Otherwise skip this block.
437 continue;
438 }
Mike Stump11289f42009-09-09 15:08:12 +0000439
Ted Kremenek56572ab2008-12-12 18:34:08 +0000440 assert(K == tok::pp_elif);
441 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
442
443 // If this is a #elif with a #else before it, report the error.
444 if (CondInfo.FoundElse)
445 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000446
Ted Kremenek56572ab2008-12-12 18:34:08 +0000447 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000448 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000449 if (CondInfo.FoundNonSkip)
450 continue;
451
452 // Evaluate the condition of the #elif.
453 IdentifierInfo *IfNDefMacro = 0;
454 CurPTHLexer->ParsingPreprocessorDirective = true;
455 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
456 CurPTHLexer->ParsingPreprocessorDirective = false;
457
458 // If this condition is true, enter it!
459 if (ShouldEnter) {
460 CondInfo.FoundNonSkip = true;
461 break;
462 }
463
464 // Otherwise, skip this block and go to the next one.
465 continue;
466 }
467}
468
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000469/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
470/// return null on failure. isAngled indicates whether the file reference is
471/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000472const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000473 bool isAngled,
474 const DirectoryLookup *FromDir,
475 const DirectoryLookup *&CurDir) {
476 // If the header lookup mechanism may be relative to the current file, pass in
477 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000478 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000479 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000480 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000481 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000482
Chris Lattner022923a2009-02-04 19:45:07 +0000483 // If there is no file entry associated with this file, it must be the
484 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000485 // it won't be scanned for preprocessor directives. If we have the
486 // predefines buffer, resolve #include references (which come from the
487 // -include command line argument) as if they came from the main file, this
488 // affects file lookup etc.
489 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000490 FID = SourceMgr.getMainFileID();
491 CurFileEnt = SourceMgr.getFileEntryForID(FID);
492 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000493 }
Mike Stump11289f42009-09-09 15:08:12 +0000494
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000495 // Do a standard file entry lookup.
496 CurDir = CurDirLookup;
497 const FileEntry *FE =
Douglas Gregor618e64a2010-08-08 07:49:23 +0000498 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerfde85352010-01-22 00:14:44 +0000499 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000500
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000501 // Otherwise, see if this is a subframework header. If so, this is relative
502 // to one of the headers on the #include stack. Walk the list of the current
503 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000504 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000505 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000506 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000507 return FE;
508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000510 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
511 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000512 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000513 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000514 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000515 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000516 return FE;
517 }
518 }
Mike Stump11289f42009-09-09 15:08:12 +0000519
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000520 // Otherwise, we really couldn't find the file.
521 return 0;
522}
523
Chris Lattnerf64b3522008-03-09 01:54:53 +0000524
525//===----------------------------------------------------------------------===//
526// Preprocessor Directive Handling.
527//===----------------------------------------------------------------------===//
528
529/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000530/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000531/// lexer/preprocessor state, and advances the lexer(s) so that the next token
532/// read is the correct one.
533void Preprocessor::HandleDirective(Token &Result) {
534 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000535
Chris Lattnerf64b3522008-03-09 01:54:53 +0000536 // We just parsed a # character at the start of a line, so we're in directive
537 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000538 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000539 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000540
Chris Lattnerf64b3522008-03-09 01:54:53 +0000541 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000542
Chris Lattnerf64b3522008-03-09 01:54:53 +0000543 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000544 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000545 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000546 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000547
Chris Lattner2d17ab72009-03-18 21:00:25 +0000548 // Save the '#' token in case we need to return it later.
549 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000550
Chris Lattnerf64b3522008-03-09 01:54:53 +0000551 // Read the next token, the directive flavor. This isn't expanded due to
552 // C99 6.10.3p8.
553 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattnerf64b3522008-03-09 01:54:53 +0000555 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
556 // #define A(x) #x
557 // A(abc
558 // #warning blah
559 // def)
560 // If so, the user is relying on non-portable behavior, emit a diagnostic.
561 if (InMacroArgs)
562 Diag(Result, diag::ext_embedded_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000563
Chris Lattnerf64b3522008-03-09 01:54:53 +0000564TryAgain:
565 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000566 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000567 return; // null directive.
568 case tok::comment:
569 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
570 LexUnexpandedToken(Result);
571 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000572 case tok::code_completion:
573 if (CodeComplete)
574 CodeComplete->CodeCompleteDirective(
575 CurPPLexer->getConditionalStackDepth() > 0);
576 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000577 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000578 if (getLangOptions().AsmPreprocessor)
579 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000580 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000581 default:
582 IdentifierInfo *II = Result.getIdentifierInfo();
583 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000584
Chris Lattnerf64b3522008-03-09 01:54:53 +0000585 // Ask what the preprocessor keyword ID is.
586 switch (II->getPPKeywordID()) {
587 default: break;
588 // C99 6.10.1 - Conditional Inclusion.
589 case tok::pp_if:
590 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
591 case tok::pp_ifdef:
592 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
593 case tok::pp_ifndef:
594 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
595 case tok::pp_elif:
596 return HandleElifDirective(Result);
597 case tok::pp_else:
598 return HandleElseDirective(Result);
599 case tok::pp_endif:
600 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000601
Chris Lattnerf64b3522008-03-09 01:54:53 +0000602 // C99 6.10.2 - Source File Inclusion.
603 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000604 // Handle #include.
605 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000606 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000607 // Handle -imacros.
608 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000609
Chris Lattnerf64b3522008-03-09 01:54:53 +0000610 // C99 6.10.3 - Macro Replacement.
611 case tok::pp_define:
612 return HandleDefineDirective(Result);
613 case tok::pp_undef:
614 return HandleUndefDirective(Result);
615
616 // C99 6.10.4 - Line Control.
617 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000618 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000619
Chris Lattnerf64b3522008-03-09 01:54:53 +0000620 // C99 6.10.5 - Error Directive.
621 case tok::pp_error:
622 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000623
Chris Lattnerf64b3522008-03-09 01:54:53 +0000624 // C99 6.10.6 - Pragma Directive.
625 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000626 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000627
Chris Lattnerf64b3522008-03-09 01:54:53 +0000628 // GNU Extensions.
629 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000630 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000631 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000632 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000633
Chris Lattnerf64b3522008-03-09 01:54:53 +0000634 case tok::pp_warning:
635 Diag(Result, diag::ext_pp_warning_directive);
636 return HandleUserDiagnosticDirective(Result, true);
637 case tok::pp_ident:
638 return HandleIdentSCCSDirective(Result);
639 case tok::pp_sccs:
640 return HandleIdentSCCSDirective(Result);
641 case tok::pp_assert:
642 //isExtension = true; // FIXME: implement #assert
643 break;
644 case tok::pp_unassert:
645 //isExtension = true; // FIXME: implement #unassert
646 break;
647 }
648 break;
649 }
Mike Stump11289f42009-09-09 15:08:12 +0000650
Chris Lattner2d17ab72009-03-18 21:00:25 +0000651 // If this is a .S file, treat unknown # directives as non-preprocessor
652 // directives. This is important because # may be a comment or introduce
653 // various pseudo-ops. Just return the # token and push back the following
654 // token to be lexed next time.
655 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000656 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000657 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000658 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000659 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000660
661 // If the second token is a hashhash token, then we need to translate it to
662 // unknown so the token lexer doesn't try to perform token pasting.
663 if (Result.is(tok::hashhash))
664 Toks[1].setKind(tok::unknown);
665
Chris Lattner2d17ab72009-03-18 21:00:25 +0000666 // Enter this token stream so that we re-lex the tokens. Make sure to
667 // enable macro expansion, in case the token after the # is an identifier
668 // that is expanded.
669 EnterTokenStream(Toks, 2, false, true);
670 return;
671 }
Mike Stump11289f42009-09-09 15:08:12 +0000672
Chris Lattnerf64b3522008-03-09 01:54:53 +0000673 // If we reached here, the preprocessing token is not valid!
674 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000675
Chris Lattnerf64b3522008-03-09 01:54:53 +0000676 // Read the rest of the PP line.
677 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000678
Chris Lattnerf64b3522008-03-09 01:54:53 +0000679 // Okay, we're done parsing the directive.
680}
681
Chris Lattner76e68962009-01-26 06:19:46 +0000682/// GetLineValue - Convert a numeric token into an unsigned value, emitting
683/// Diagnostic DiagID if it is invalid, and returning the value in Val.
684static bool GetLineValue(Token &DigitTok, unsigned &Val,
685 unsigned DiagID, Preprocessor &PP) {
686 if (DigitTok.isNot(tok::numeric_constant)) {
687 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000688
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000689 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000690 PP.DiscardUntilEndOfDirective();
691 return true;
692 }
Mike Stump11289f42009-09-09 15:08:12 +0000693
Chris Lattner76e68962009-01-26 06:19:46 +0000694 llvm::SmallString<64> IntegerBuffer;
695 IntegerBuffer.resize(DigitTok.getLength());
696 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000697 bool Invalid = false;
698 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
699 if (Invalid)
700 return true;
701
Chris Lattnerd66f1722009-04-18 18:35:15 +0000702 // Verify that we have a simple digit-sequence, and compute the value. This
703 // is always a simple digit string computed in decimal, so we do this manually
704 // here.
705 Val = 0;
706 for (unsigned i = 0; i != ActualLength; ++i) {
707 if (!isdigit(DigitTokBegin[i])) {
708 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
709 diag::err_pp_line_digit_sequence);
710 PP.DiscardUntilEndOfDirective();
711 return true;
712 }
Mike Stump11289f42009-09-09 15:08:12 +0000713
Chris Lattnerd66f1722009-04-18 18:35:15 +0000714 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
715 if (NextVal < Val) { // overflow.
716 PP.Diag(DigitTok, DiagID);
717 PP.DiscardUntilEndOfDirective();
718 return true;
719 }
720 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000721 }
Mike Stump11289f42009-09-09 15:08:12 +0000722
723 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000724 if (Val == 0) {
725 PP.Diag(DigitTok, DiagID);
726 PP.DiscardUntilEndOfDirective();
727 return true;
728 }
Mike Stump11289f42009-09-09 15:08:12 +0000729
Chris Lattnerd66f1722009-04-18 18:35:15 +0000730 if (DigitTokBegin[0] == '0')
731 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattner76e68962009-01-26 06:19:46 +0000733 return false;
734}
735
Mike Stump11289f42009-09-09 15:08:12 +0000736/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner100c65e2009-01-26 05:29:08 +0000737/// acceptable forms are:
738/// # line digit-sequence
739/// # line digit-sequence "s-char-sequence"
740void Preprocessor::HandleLineDirective(Token &Tok) {
741 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
742 // expanded.
743 Token DigitTok;
744 Lex(DigitTok);
745
Chris Lattner100c65e2009-01-26 05:29:08 +0000746 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000747 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000748 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000749 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000750
Chris Lattner76e68962009-01-26 06:19:46 +0000751 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
752 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner100c65e2009-01-26 05:29:08 +0000753 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
754 if (LineNo >= LineLimit)
755 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump11289f42009-09-09 15:08:12 +0000756
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000757 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000758 Token StrTok;
759 Lex(StrTok);
760
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000761 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
762 // string followed by eod.
763 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000764 ; // ok
765 else if (StrTok.isNot(tok::string_literal)) {
766 Diag(StrTok, diag::err_pp_line_invalid_filename);
767 DiscardUntilEndOfDirective();
768 return;
769 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000770 // Parse and validate the string, converting it into a unique ID.
771 StringLiteralParser Literal(&StrTok, 1, *this);
772 assert(!Literal.AnyWide && "Didn't allow wide strings in");
773 if (Literal.hadError)
774 return DiscardUntilEndOfDirective();
775 if (Literal.Pascal) {
776 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
777 return DiscardUntilEndOfDirective();
778 }
779 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
780 Literal.GetStringLength());
Mike Stump11289f42009-09-09 15:08:12 +0000781
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000782 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000783 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
784 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000785 }
Mike Stump11289f42009-09-09 15:08:12 +0000786
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000787 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000788
Chris Lattner839150e2009-03-27 17:13:49 +0000789 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000790 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
791 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000792 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000793}
794
Chris Lattner76e68962009-01-26 06:19:46 +0000795/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
796/// marker directive.
797static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
798 bool &IsSystemHeader, bool &IsExternCHeader,
799 Preprocessor &PP) {
800 unsigned FlagVal;
801 Token FlagTok;
802 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000803 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000804 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
805 return true;
806
807 if (FlagVal == 1) {
808 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000809
Chris Lattner76e68962009-01-26 06:19:46 +0000810 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000811 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000812 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
813 return true;
814 } else if (FlagVal == 2) {
815 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000816
Chris Lattner1c967782009-02-04 06:25:26 +0000817 SourceManager &SM = PP.getSourceManager();
818 // If we are leaving the current presumed file, check to make sure the
819 // presumed include stack isn't empty!
820 FileID CurFileID =
821 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
822 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000823 if (PLoc.isInvalid())
824 return true;
825
Chris Lattner1c967782009-02-04 06:25:26 +0000826 // If there is no include loc (main file) or if the include loc is in a
827 // different physical file, then we aren't in a "1" line marker flag region.
828 SourceLocation IncLoc = PLoc.getIncludeLoc();
829 if (IncLoc.isInvalid() ||
830 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
831 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
832 PP.DiscardUntilEndOfDirective();
833 return true;
834 }
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chris Lattner76e68962009-01-26 06:19:46 +0000836 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000837 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000838 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
839 return true;
840 }
841
842 // We must have 3 if there are still flags.
843 if (FlagVal != 3) {
844 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000845 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000846 return true;
847 }
Mike Stump11289f42009-09-09 15:08:12 +0000848
Chris Lattner76e68962009-01-26 06:19:46 +0000849 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000850
Chris Lattner76e68962009-01-26 06:19:46 +0000851 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000852 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000853 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000854 return true;
855
856 // We must have 4 if there is yet another flag.
857 if (FlagVal != 4) {
858 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000859 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000860 return true;
861 }
Mike Stump11289f42009-09-09 15:08:12 +0000862
Chris Lattner76e68962009-01-26 06:19:46 +0000863 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000864
Chris Lattner76e68962009-01-26 06:19:46 +0000865 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000866 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000867
868 // There are no more valid flags here.
869 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000870 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000871 return true;
872}
873
874/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
875/// one of the following forms:
876///
877/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000878/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000879/// # 42 "file" ('1' | '2')? '3' '4'?
880///
881void Preprocessor::HandleDigitDirective(Token &DigitTok) {
882 // Validate the number and convert it to an unsigned. GNU does not have a
883 // line # limit other than it fit in 32-bits.
884 unsigned LineNo;
885 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
886 *this))
887 return;
Mike Stump11289f42009-09-09 15:08:12 +0000888
Chris Lattner76e68962009-01-26 06:19:46 +0000889 Token StrTok;
890 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000891
Chris Lattner76e68962009-01-26 06:19:46 +0000892 bool IsFileEntry = false, IsFileExit = false;
893 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000894 int FilenameID = -1;
895
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000896 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
897 // string followed by eod.
898 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000899 ; // ok
900 else if (StrTok.isNot(tok::string_literal)) {
901 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000902 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000903 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000904 // Parse and validate the string, converting it into a unique ID.
905 StringLiteralParser Literal(&StrTok, 1, *this);
906 assert(!Literal.AnyWide && "Didn't allow wide strings in");
907 if (Literal.hadError)
908 return DiscardUntilEndOfDirective();
909 if (Literal.Pascal) {
910 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
911 return DiscardUntilEndOfDirective();
912 }
913 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
914 Literal.GetStringLength());
Mike Stump11289f42009-09-09 15:08:12 +0000915
Chris Lattner76e68962009-01-26 06:19:46 +0000916 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +0000917 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000918 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +0000919 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000920 }
Mike Stump11289f42009-09-09 15:08:12 +0000921
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000922 // Create a line note with this information.
923 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +0000924 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000925 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +0000926
Chris Lattner839150e2009-03-27 17:13:49 +0000927 // If the preprocessor has callbacks installed, notify them of the #line
928 // change. This is used so that the line marker comes out in -E mode for
929 // example.
930 if (Callbacks) {
931 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
932 if (IsFileEntry)
933 Reason = PPCallbacks::EnterFile;
934 else if (IsFileExit)
935 Reason = PPCallbacks::ExitFile;
936 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
937 if (IsExternCHeader)
938 FileKind = SrcMgr::C_ExternCSystem;
939 else if (IsSystemHeader)
940 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattnerc745cec2010-04-14 04:28:50 +0000942 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +0000943 }
Chris Lattner76e68962009-01-26 06:19:46 +0000944}
945
946
Chris Lattner38d7fd22009-01-26 05:30:54 +0000947/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
948///
Mike Stump11289f42009-09-09 15:08:12 +0000949void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000950 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +0000951 // PTH doesn't emit #warning or #error directives.
952 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +0000953 return CurPTHLexer->DiscardToEndOfLine();
954
Chris Lattnerf64b3522008-03-09 01:54:53 +0000955 // Read the rest of the line raw. We do this because we don't want macros
956 // to be expanded and we don't require that the tokens be valid preprocessing
957 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
958 // collapse multiple consequtive white space between tokens, but this isn't
959 // specified by the standard.
Chris Lattner100c65e2009-01-26 05:29:08 +0000960 std::string Message = CurLexer->ReadToEndOfLine();
961 if (isWarning)
962 Diag(Tok, diag::pp_hash_warning) << Message;
963 else
964 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000965}
966
967/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
968///
969void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
970 // Yes, this directive is an extension.
971 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattnerf64b3522008-03-09 01:54:53 +0000973 // Read the string argument.
974 Token StrTok;
975 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000976
Chris Lattnerf64b3522008-03-09 01:54:53 +0000977 // If the token kind isn't a string, it's a malformed directive.
978 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +0000979 StrTok.isNot(tok::wide_string_literal)) {
980 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000981 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +0000982 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000983 return;
984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000986 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000987 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000988
Douglas Gregordc970f02010-03-16 22:30:13 +0000989 if (Callbacks) {
990 bool Invalid = false;
991 std::string Str = getSpelling(StrTok, &Invalid);
992 if (!Invalid)
993 Callbacks->Ident(Tok.getLocation(), Str);
994 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000995}
996
997//===----------------------------------------------------------------------===//
998// Preprocessor Include Directive Handling.
999//===----------------------------------------------------------------------===//
1000
1001/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1002/// checked and spelled filename, e.g. as an operand of #include. This returns
1003/// true if the input filename was in <>'s or false if it were in ""'s. The
1004/// caller is expected to provide a buffer that is large enough to hold the
1005/// spelling of the filename, but is also expected to handle the case when
1006/// this method decides to use a different buffer.
1007bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001008 llvm::StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001009 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001010 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattnerf64b3522008-03-09 01:54:53 +00001012 // Make sure the filename is <x> or "x".
1013 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001014 if (Buffer[0] == '<') {
1015 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001016 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001017 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001018 return true;
1019 }
1020 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001021 } else if (Buffer[0] == '"') {
1022 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001023 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001024 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001025 return true;
1026 }
1027 isAngled = false;
1028 } else {
1029 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001030 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001031 return true;
1032 }
Mike Stump11289f42009-09-09 15:08:12 +00001033
Chris Lattnerf64b3522008-03-09 01:54:53 +00001034 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001035 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001036 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001037 Buffer = llvm::StringRef();
1038 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040
Chris Lattnerf64b3522008-03-09 01:54:53 +00001041 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001042 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001043 return isAngled;
1044}
1045
1046/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1047/// from a macro as multiple tokens, which need to be glued together. This
1048/// occurs for code like:
1049/// #define FOO <a/b.h>
1050/// #include FOO
1051/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1052///
1053/// This code concatenates and consumes tokens up to the '>' token. It returns
1054/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001055/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001056bool Preprocessor::ConcatenateIncludeName(
Douglas Gregor796d76a2010-10-20 22:00:55 +00001057 llvm::SmallString<128> &FilenameBuffer,
1058 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001059 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001060
John Thompsonb5353522009-10-30 13:49:06 +00001061 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001062 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001063 End = CurTok.getLocation();
1064
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001065 // FIXME: Provide code completion for #includes.
1066 if (CurTok.is(tok::code_completion)) {
1067 Lex(CurTok);
1068 continue;
1069 }
1070
Chris Lattnerf64b3522008-03-09 01:54:53 +00001071 // Append the spelling of this token to the buffer. If there was a space
1072 // before it, add it now.
1073 if (CurTok.hasLeadingSpace())
1074 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001075
Chris Lattnerf64b3522008-03-09 01:54:53 +00001076 // Get the spelling of the token, directly into FilenameBuffer if possible.
1077 unsigned PreAppendSize = FilenameBuffer.size();
1078 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001079
Chris Lattnerf64b3522008-03-09 01:54:53 +00001080 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001081 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001082
Chris Lattnerf64b3522008-03-09 01:54:53 +00001083 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1084 if (BufPtr != &FilenameBuffer[PreAppendSize])
1085 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001086
Chris Lattnerf64b3522008-03-09 01:54:53 +00001087 // Resize FilenameBuffer to the correct size.
1088 if (CurTok.getLength() != ActualLen)
1089 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001090
Chris Lattnerf64b3522008-03-09 01:54:53 +00001091 // If we found the '>' marker, return success.
1092 if (CurTok.is(tok::greater))
1093 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001094
John Thompsonb5353522009-10-30 13:49:06 +00001095 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001096 }
1097
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001098 // If we hit the eod marker, emit an error and return true so that the caller
1099 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001100 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001101 return true;
1102}
1103
1104/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1105/// file to be included from the lexer, then include it! This is a common
1106/// routine with functionality shared between #include, #include_next and
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001107/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001108/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001109void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1110 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001111 const DirectoryLookup *LookupFrom,
1112 bool isImport) {
1113
1114 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001115 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001116
Chris Lattnerf64b3522008-03-09 01:54:53 +00001117 // Reserve a buffer to get the spelling.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001118 llvm::SmallString<128> FilenameBuffer;
1119 llvm::StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001120 SourceLocation End;
1121
Chris Lattnerf64b3522008-03-09 01:54:53 +00001122 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001123 case tok::eod:
1124 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001125 return;
Mike Stump11289f42009-09-09 15:08:12 +00001126
Chris Lattnerf64b3522008-03-09 01:54:53 +00001127 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001128 case tok::string_literal:
1129 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001130 End = FilenameTok.getLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001131 break;
Mike Stump11289f42009-09-09 15:08:12 +00001132
Chris Lattnerf64b3522008-03-09 01:54:53 +00001133 case tok::less:
1134 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1135 // case, glue the tokens together into FilenameBuffer and interpret those.
1136 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001137 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001138 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001139 Filename = FilenameBuffer.str();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001140 break;
1141 default:
1142 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1143 DiscardUntilEndOfDirective();
1144 return;
1145 }
Mike Stump11289f42009-09-09 15:08:12 +00001146
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001147 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001148 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001149 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1150 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001151 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001152 DiscardUntilEndOfDirective();
1153 return;
1154 }
Mike Stump11289f42009-09-09 15:08:12 +00001155
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001156 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001157 // we allow macros that expand to nothing after the filename, because this
1158 // falls into the category of "#include pp-tokens new-line" specified in
1159 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001160 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001161
1162 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001163 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1164 Diag(FilenameTok, diag::err_pp_include_too_deep);
1165 return;
1166 }
Mike Stump11289f42009-09-09 15:08:12 +00001167
Chris Lattnerf64b3522008-03-09 01:54:53 +00001168 // Search include directories.
1169 const DirectoryLookup *CurDir;
Chris Lattnerfde85352010-01-22 00:14:44 +00001170 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner907dfe92008-11-18 07:59:24 +00001171 if (File == 0) {
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001172 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner907dfe92008-11-18 07:59:24 +00001173 return;
1174 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001175
Douglas Gregor796d76a2010-10-20 22:00:55 +00001176 // Notify the callback object that we've seen an inclusion directive.
1177 if (Callbacks)
1178 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1179 End);
1180
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001181 // The #included file will be considered to be a system header if either it is
1182 // in a system include directory, or if the #includer is a system include
1183 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001184 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001185 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001186 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001187
Chris Lattner72286d62010-04-19 20:44:31 +00001188 // Ask HeaderInfo if we should enter this #include file. If not, #including
1189 // this file will have no effect.
1190 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001191 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001192 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001193 return;
1194 }
1195
Chris Lattnerf64b3522008-03-09 01:54:53 +00001196 // Look up the file, create a File ID for it.
Chris Lattnerd32480d2009-01-17 06:22:33 +00001197 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1198 FileCharacter);
1199 if (FID.isInvalid()) {
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001200 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +00001201 return;
1202 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001203
1204 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001205 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001206}
1207
1208/// HandleIncludeNextDirective - Implements #include_next.
1209///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001210void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1211 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001212 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001213
Chris Lattnerf64b3522008-03-09 01:54:53 +00001214 // #include_next is like #include, except that we start searching after
1215 // the current found directory. If we can't do this, issue a
1216 // diagnostic.
1217 const DirectoryLookup *Lookup = CurDirLookup;
1218 if (isInPrimaryFile()) {
1219 Lookup = 0;
1220 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1221 } else if (Lookup == 0) {
1222 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1223 } else {
1224 // Start looking up in the next directory.
1225 ++Lookup;
1226 }
Mike Stump11289f42009-09-09 15:08:12 +00001227
Douglas Gregor796d76a2010-10-20 22:00:55 +00001228 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001229}
1230
1231/// HandleImportDirective - Implements #import.
1232///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001233void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1234 Token &ImportTok) {
Chris Lattnerd4a96732009-03-06 04:28:03 +00001235 if (!Features.ObjC1) // #import is standard for ObjC.
1236 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001237
Douglas Gregor796d76a2010-10-20 22:00:55 +00001238 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001239}
1240
Chris Lattner58a1eb02009-04-08 18:46:40 +00001241/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1242/// pseudo directive in the predefines buffer. This handles it by sucking all
1243/// tokens through the preprocessor and discarding them (only keeping the side
1244/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001245void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1246 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001247 // This directive should only occur in the predefines buffer. If not, emit an
1248 // error and reject it.
1249 SourceLocation Loc = IncludeMacrosTok.getLocation();
1250 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1251 Diag(IncludeMacrosTok.getLocation(),
1252 diag::pp_include_macros_out_of_predefines);
1253 DiscardUntilEndOfDirective();
1254 return;
1255 }
Mike Stump11289f42009-09-09 15:08:12 +00001256
Chris Lattnere01d82b2009-04-08 20:53:24 +00001257 // Treat this as a normal #include for checking purposes. If this is
1258 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001259 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001260
Chris Lattnere01d82b2009-04-08 20:53:24 +00001261 Token TmpTok;
1262 do {
1263 Lex(TmpTok);
1264 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1265 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001266}
1267
Chris Lattnerf64b3522008-03-09 01:54:53 +00001268//===----------------------------------------------------------------------===//
1269// Preprocessor Macro Directive Handling.
1270//===----------------------------------------------------------------------===//
1271
1272/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1273/// definition has just been read. Lex the rest of the arguments and the
1274/// closing ), updating MI with what we learn. Return true if an error occurs
1275/// parsing the arg list.
1276bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1277 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001278
Chris Lattnerf64b3522008-03-09 01:54:53 +00001279 Token Tok;
1280 while (1) {
1281 LexUnexpandedToken(Tok);
1282 switch (Tok.getKind()) {
1283 case tok::r_paren:
1284 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001285 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001286 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001287 // Otherwise we have #define FOO(A,)
1288 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1289 return true;
1290 case tok::ellipsis: // #define X(... -> C99 varargs
1291 // Warn if use of C99 feature in non-C99 mode.
1292 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1293
1294 // Lex the token after the identifier.
1295 LexUnexpandedToken(Tok);
1296 if (Tok.isNot(tok::r_paren)) {
1297 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1298 return true;
1299 }
1300 // Add the __VA_ARGS__ identifier as an argument.
1301 Arguments.push_back(Ident__VA_ARGS__);
1302 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001303 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001304 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001305 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001306 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1307 return true;
1308 default:
1309 // Handle keywords and identifiers here to accept things like
1310 // #define Foo(for) for.
1311 IdentifierInfo *II = Tok.getIdentifierInfo();
1312 if (II == 0) {
1313 // #define X(1
1314 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1315 return true;
1316 }
1317
1318 // If this is already used as an argument, it is used multiple times (e.g.
1319 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001320 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001321 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001322 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001323 return true;
1324 }
Mike Stump11289f42009-09-09 15:08:12 +00001325
Chris Lattnerf64b3522008-03-09 01:54:53 +00001326 // Add the argument to the macro info.
1327 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001328
Chris Lattnerf64b3522008-03-09 01:54:53 +00001329 // Lex the token after the identifier.
1330 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001331
Chris Lattnerf64b3522008-03-09 01:54:53 +00001332 switch (Tok.getKind()) {
1333 default: // #define X(A B
1334 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1335 return true;
1336 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001337 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001338 return false;
1339 case tok::comma: // #define X(A,
1340 break;
1341 case tok::ellipsis: // #define X(A... -> GCC extension
1342 // Diagnose extension.
1343 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001344
Chris Lattnerf64b3522008-03-09 01:54:53 +00001345 // Lex the token after the identifier.
1346 LexUnexpandedToken(Tok);
1347 if (Tok.isNot(tok::r_paren)) {
1348 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1349 return true;
1350 }
Mike Stump11289f42009-09-09 15:08:12 +00001351
Chris Lattnerf64b3522008-03-09 01:54:53 +00001352 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001353 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001354 return false;
1355 }
1356 }
1357 }
1358}
1359
1360/// HandleDefineDirective - Implements #define. This consumes the entire macro
1361/// line then lets the caller lex the next real token.
1362void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1363 ++NumDefined;
1364
1365 Token MacroNameTok;
1366 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001367
Chris Lattnerf64b3522008-03-09 01:54:53 +00001368 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001369 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001370 return;
1371
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001372 Token LastTok = MacroNameTok;
1373
Chris Lattnerf64b3522008-03-09 01:54:53 +00001374 // If we are supposed to keep comments in #defines, reenable comment saving
1375 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001376 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001377
Chris Lattnerf64b3522008-03-09 01:54:53 +00001378 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001379 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001380
Chris Lattnerf64b3522008-03-09 01:54:53 +00001381 Token Tok;
1382 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001383
Chris Lattnerf64b3522008-03-09 01:54:53 +00001384 // If this is a function-like macro definition, parse the argument list,
1385 // marking each of the identifiers as being used as macro arguments. Also,
1386 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001387 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001388 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001389 } else if (Tok.hasLeadingSpace()) {
1390 // This is a normal token with leading space. Clear the leading space
1391 // marker on the first token to get proper expansion.
1392 Tok.clearFlag(Token::LeadingSpace);
1393 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001394 // This is a function-like macro definition. Read the argument list.
1395 MI->setIsFunctionLike();
1396 if (ReadMacroDefinitionArgList(MI)) {
1397 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001398 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001399 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001400 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001401 DiscardUntilEndOfDirective();
1402 return;
1403 }
1404
Chris Lattner249c38b2009-04-19 18:26:34 +00001405 // If this is a definition of a variadic C99 function-like macro, not using
1406 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001407
Chris Lattner249c38b2009-04-19 18:26:34 +00001408 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1409 // This gets unpoisoned where it is allowed.
1410 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1411 if (MI->isC99Varargs())
1412 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001413
Chris Lattnerf64b3522008-03-09 01:54:53 +00001414 // Read the first token after the arg list for down below.
1415 LexUnexpandedToken(Tok);
Chris Lattner2425bcb2009-04-18 02:23:25 +00001416 } else if (Features.C99) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001417 // C99 requires whitespace between the macro definition and the body. Emit
1418 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001419 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001420 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001421 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1422 // first character of a replacement list is not a character required by
1423 // subclause 5.2.1, then there shall be white-space separation between the
1424 // identifier and the replacement list.". 5.2.1 lists this set:
1425 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1426 // is irrelevant here.
1427 bool isInvalid = false;
1428 if (Tok.is(tok::at)) // @ is not in the list above.
1429 isInvalid = true;
1430 else if (Tok.is(tok::unknown)) {
1431 // If we have an unknown token, it is something strange like "`". Since
1432 // all of valid characters would have lexed into a single character
1433 // token of some sort, we know this is not a valid case.
1434 isInvalid = true;
1435 }
1436 if (isInvalid)
1437 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1438 else
1439 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001440 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001441
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001442 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001443 LastTok = Tok;
1444
Chris Lattnerf64b3522008-03-09 01:54:53 +00001445 // Read the rest of the macro body.
1446 if (MI->isObjectLike()) {
1447 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001448 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001449 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001450 MI->AddTokenToBody(Tok);
1451 // Get the next token of the macro.
1452 LexUnexpandedToken(Tok);
1453 }
Mike Stump11289f42009-09-09 15:08:12 +00001454
Chris Lattnerf64b3522008-03-09 01:54:53 +00001455 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001456 // Otherwise, read the body of a function-like macro. While we are at it,
1457 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1458 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001459 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001460 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001461
Chris Lattnerf64b3522008-03-09 01:54:53 +00001462 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001463 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001464
Chris Lattnerf64b3522008-03-09 01:54:53 +00001465 // Get the next token of the macro.
1466 LexUnexpandedToken(Tok);
1467 continue;
1468 }
Mike Stump11289f42009-09-09 15:08:12 +00001469
Chris Lattnerf64b3522008-03-09 01:54:53 +00001470 // Get the next token of the macro.
1471 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001472
Chris Lattner83bd8282009-05-25 17:16:10 +00001473 // Check for a valid macro arg identifier.
1474 if (Tok.getIdentifierInfo() == 0 ||
1475 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1476
1477 // If this is assembler-with-cpp mode, we accept random gibberish after
1478 // the '#' because '#' is often a comment character. However, change
1479 // the kind of the token to tok::unknown so that the preprocessor isn't
1480 // confused.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001481 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001482 LastTok.setKind(tok::unknown);
1483 } else {
1484 Diag(Tok, diag::err_pp_stringize_not_parameter);
1485 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001486
Chris Lattner83bd8282009-05-25 17:16:10 +00001487 // Disable __VA_ARGS__ again.
1488 Ident__VA_ARGS__->setIsPoisoned(true);
1489 return;
1490 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001491 }
Mike Stump11289f42009-09-09 15:08:12 +00001492
Chris Lattner83bd8282009-05-25 17:16:10 +00001493 // Things look ok, add the '#' and param name tokens to the macro.
1494 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001495 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001496 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001497
Chris Lattnerf64b3522008-03-09 01:54:53 +00001498 // Get the next token of the macro.
1499 LexUnexpandedToken(Tok);
1500 }
1501 }
Mike Stump11289f42009-09-09 15:08:12 +00001502
1503
Chris Lattnerf64b3522008-03-09 01:54:53 +00001504 // Disable __VA_ARGS__ again.
1505 Ident__VA_ARGS__->setIsPoisoned(true);
1506
1507 // Check that there is no paste (##) operator at the begining or end of the
1508 // replacement list.
1509 unsigned NumTokens = MI->getNumTokens();
1510 if (NumTokens != 0) {
1511 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1512 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001513 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001514 return;
1515 }
1516 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1517 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001518 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001519 return;
1520 }
1521 }
Mike Stump11289f42009-09-09 15:08:12 +00001522
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001523 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001524
Chris Lattnerf64b3522008-03-09 01:54:53 +00001525 // Finally, if this identifier already had a macro defined for it, verify that
1526 // the macro bodies are identical and free the old definition.
1527 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001528 // It is very common for system headers to have tons of macro redefinitions
1529 // and for warnings to be disabled in system headers. If this is the case,
1530 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001531 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001532 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001533 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001534 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001535
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001536 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001537 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001538 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001539 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001540 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1541 << MacroNameTok.getIdentifierInfo();
1542 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1543 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001544 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001545 if (OtherMI->isWarnIfUnused())
1546 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001547 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001548 }
Mike Stump11289f42009-09-09 15:08:12 +00001549
Chris Lattnerf64b3522008-03-09 01:54:53 +00001550 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001551
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001552 assert(!MI->isUsed());
1553 // If we need warning for not using the macro, add its location in the
1554 // warn-because-unused-macro set. If it gets used it will be removed from set.
1555 if (isInPrimaryFile() && // don't warn for include'd macros.
1556 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1557 MI->getDefinitionLoc()) != Diagnostic::Ignored) {
1558 MI->setIsWarnIfUnused(true);
1559 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1560 }
1561
Chris Lattner928e9092009-04-12 01:39:54 +00001562 // If the callbacks want to know, tell them about the macro definition.
1563 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001564 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001565}
1566
1567/// HandleUndefDirective - Implements #undef.
1568///
1569void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1570 ++NumUndefined;
1571
1572 Token MacroNameTok;
1573 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001574
Chris Lattnerf64b3522008-03-09 01:54:53 +00001575 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001576 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001577 return;
Mike Stump11289f42009-09-09 15:08:12 +00001578
Chris Lattnerf64b3522008-03-09 01:54:53 +00001579 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001580 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001581
Chris Lattnerf64b3522008-03-09 01:54:53 +00001582 // Okay, we finally have a valid identifier to undef.
1583 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001584
Chris Lattnerf64b3522008-03-09 01:54:53 +00001585 // If the macro is not defined, this is a noop undef, just return.
1586 if (MI == 0) return;
1587
1588 if (!MI->isUsed())
1589 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001590
1591 // If the callbacks want to know, tell them about the macro #undef.
1592 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001593 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001594
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001595 if (MI->isWarnIfUnused())
1596 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1597
Chris Lattnerf64b3522008-03-09 01:54:53 +00001598 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001599 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001600 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1601}
1602
1603
1604//===----------------------------------------------------------------------===//
1605// Preprocessor Conditional Directive Handling.
1606//===----------------------------------------------------------------------===//
1607
1608/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1609/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1610/// if any tokens have been returned or pp-directives activated before this
1611/// #ifndef has been lexed.
1612///
1613void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1614 bool ReadAnyTokensBeforeDirective) {
1615 ++NumIf;
1616 Token DirectiveTok = Result;
1617
1618 Token MacroNameTok;
1619 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001620
Chris Lattnerf64b3522008-03-09 01:54:53 +00001621 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001622 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001623 // Skip code until we get to #endif. This helps with recovery by not
1624 // emitting an error when the #endif is reached.
1625 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1626 /*Foundnonskip*/false, /*FoundElse*/false);
1627 return;
1628 }
Mike Stump11289f42009-09-09 15:08:12 +00001629
Chris Lattnerf64b3522008-03-09 01:54:53 +00001630 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001631 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001632
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001633 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1634 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001635
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001636 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001637 // If the start of a top-level #ifdef and if the macro is not defined,
1638 // inform MIOpt that this might be the start of a proper include guard.
1639 // Otherwise it is some other form of unknown conditional which we can't
1640 // handle.
1641 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001642 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001643 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001644 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001645 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001646 }
1647
Chris Lattnerf64b3522008-03-09 01:54:53 +00001648 // If there is a macro, process it.
1649 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001650 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001651
Chris Lattnerf64b3522008-03-09 01:54:53 +00001652 // Should we include the stuff contained by this directive?
1653 if (!MI == isIfndef) {
1654 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001655 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1656 /*wasskip*/false, /*foundnonskip*/true,
1657 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001658 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001659 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001660 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001661 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001662 /*FoundElse*/false);
1663 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001664
1665 if (Callbacks) {
1666 if (isIfndef)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001667 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001668 else
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001669 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001670 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001671}
1672
1673/// HandleIfDirective - Implements the #if directive.
1674///
1675void Preprocessor::HandleIfDirective(Token &IfToken,
1676 bool ReadAnyTokensBeforeDirective) {
1677 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001678
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001679 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001680 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001681 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1682 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1683 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001684
1685 // If this condition is equivalent to #ifndef X, and if this is the first
1686 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001687 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001688 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001689 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001690 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001691 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001692 }
1693
Chris Lattnerf64b3522008-03-09 01:54:53 +00001694 // Should we include the stuff contained by this directive?
1695 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001696 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001697 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001698 /*foundnonskip*/true, /*foundelse*/false);
1699 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001700 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00001701 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001702 /*FoundElse*/false);
1703 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001704
1705 if (Callbacks)
1706 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001707}
1708
1709/// HandleEndifDirective - Implements the #endif directive.
1710///
1711void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1712 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00001713
Chris Lattnerf64b3522008-03-09 01:54:53 +00001714 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001715 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00001716
Chris Lattnerf64b3522008-03-09 01:54:53 +00001717 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001718 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001719 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00001720 Diag(EndifToken, diag::err_pp_endif_without_if);
1721 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001722 }
Mike Stump11289f42009-09-09 15:08:12 +00001723
Chris Lattnerf64b3522008-03-09 01:54:53 +00001724 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001725 if (CurPPLexer->getConditionalStackDepth() == 0)
1726 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001727
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001728 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00001729 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001730
1731 if (Callbacks)
1732 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001733}
1734
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001735/// HandleElseDirective - Implements the #else directive.
1736///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001737void Preprocessor::HandleElseDirective(Token &Result) {
1738 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001739
Chris Lattnerf64b3522008-03-09 01:54:53 +00001740 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001741 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00001742
Chris Lattnerf64b3522008-03-09 01:54:53 +00001743 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001744 if (CurPPLexer->popConditionalLevel(CI)) {
1745 Diag(Result, diag::pp_err_else_without_if);
1746 return;
1747 }
Mike Stump11289f42009-09-09 15:08:12 +00001748
Chris Lattnerf64b3522008-03-09 01:54:53 +00001749 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001750 if (CurPPLexer->getConditionalStackDepth() == 0)
1751 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001752
1753 // If this is a #else with a #else before it, report the error.
1754 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00001755
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001756 // Finally, skip the rest of the contents of this block.
1757 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1758 /*FoundElse*/true);
1759
1760 if (Callbacks)
1761 Callbacks->Else();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001762}
1763
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001764/// HandleElifDirective - Implements the #elif directive.
1765///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001766void Preprocessor::HandleElifDirective(Token &ElifToken) {
1767 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001768
Chris Lattnerf64b3522008-03-09 01:54:53 +00001769 // #elif directive in a non-skipping conditional... start skipping.
1770 // We don't care what the condition is, because we will always skip it (since
1771 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001772 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001773 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001774 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001775
1776 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001777 if (CurPPLexer->popConditionalLevel(CI)) {
1778 Diag(ElifToken, diag::pp_err_elif_without_if);
1779 return;
1780 }
Mike Stump11289f42009-09-09 15:08:12 +00001781
Chris Lattnerf64b3522008-03-09 01:54:53 +00001782 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001783 if (CurPPLexer->getConditionalStackDepth() == 0)
1784 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001785
Chris Lattnerf64b3522008-03-09 01:54:53 +00001786 // If this is a #elif with a #else before it, report the error.
1787 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1788
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001789 // Finally, skip the rest of the contents of this block.
1790 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1791 /*FoundElse*/CI.FoundElse);
1792
1793 if (Callbacks)
1794 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001795}