blob: 00cb62384e3502f559e96c024c84deab740f0c5f [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-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 Lattner359cc442009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000019#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000020#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000021using namespace clang;
22
23//===----------------------------------------------------------------------===//
24// Utility Methods for Preprocessor Directive Handling.
25//===----------------------------------------------------------------------===//
26
Ted Kremenek0ea76722008-12-15 19:56:42 +000027MacroInfo* Preprocessor::AllocateMacroInfo(SourceLocation L) {
28 MacroInfo *MI;
29
30 if (!MICache.empty()) {
31 MI = MICache.back();
32 MICache.pop_back();
33 }
34 else MI = (MacroInfo*) BP.Allocate<MacroInfo>();
35 new (MI) MacroInfo(L);
36 return MI;
37}
38
Chris Lattner141e71f2008-03-09 01:54:53 +000039/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
40/// current line until the tok::eom token is found.
41void Preprocessor::DiscardUntilEndOfDirective() {
42 Token Tmp;
43 do {
44 LexUnexpandedToken(Tmp);
45 } while (Tmp.isNot(tok::eom));
46}
47
Chris Lattner141e71f2008-03-09 01:54:53 +000048/// ReadMacroName - Lex and validate a macro name, which occurs after a
49/// #define or #undef. This sets the token kind to eom and discards the rest
50/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
51/// this is due to a a #define, 2 if #undef directive, 0 if it is something
52/// else (e.g. #ifdef).
53void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
54 // Read the token, don't allow macro expansion on it.
55 LexUnexpandedToken(MacroNameTok);
56
57 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000058 if (MacroNameTok.is(tok::eom)) {
59 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
60 return;
61 }
Chris Lattner141e71f2008-03-09 01:54:53 +000062
63 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
64 if (II == 0) {
65 std::string Spelling = getSpelling(MacroNameTok);
Chris Lattner9485d232008-12-13 20:12:40 +000066 const IdentifierInfo &Info = Identifiers.get(Spelling);
67 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +000068 // C++ 2.5p2: Alternative tokens behave the same as its primary token
69 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +000070 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000071 else
72 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
73 // Fall through on error.
74 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
75 // Error if defining "defined": C99 6.10.8.4.
76 Diag(MacroNameTok, diag::err_defined_macro_name);
77 } else if (isDefineUndef && II->hasMacroDefinition() &&
78 getMacroInfo(II)->isBuiltinMacro()) {
79 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
80 if (isDefineUndef == 1)
81 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
82 else
83 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
84 } else {
85 // Okay, we got a good identifier node. Return it.
86 return;
87 }
88
89 // Invalid macro name, read and discard the rest of the line. Then set the
90 // token kind to tok::eom.
91 MacroNameTok.setKind(tok::eom);
92 return DiscardUntilEndOfDirective();
93}
94
95/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
96/// not, emit a diagnostic and consume up until the eom.
97void Preprocessor::CheckEndOfDirective(const char *DirType) {
98 Token Tmp;
99 // Lex unexpanded tokens: macros might expand to zero tokens, causing us to
100 // miss diagnosing invalid lines.
101 LexUnexpandedToken(Tmp);
102
103 // There should be no tokens after the directive, but we allow them as an
104 // extension.
105 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
106 LexUnexpandedToken(Tmp);
107
108 if (Tmp.isNot(tok::eom)) {
Chris Lattner56b05c82008-11-18 08:02:48 +0000109 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType;
Chris Lattner141e71f2008-03-09 01:54:53 +0000110 DiscardUntilEndOfDirective();
111 }
112}
113
114
115
116/// SkipExcludedConditionalBlock - We just read a #if or related directive and
117/// decided that the subsequent tokens are in the #if'd out portion of the
118/// file. Lex the rest of the file, until we see an #endif. If
119/// FoundNonSkipPortion is true, then we have already emitted code for part of
120/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
121/// is true, then #else directives are ok, if not, then we have already seen one
122/// so a #else directive is a duplicate. When this returns, the caller can lex
123/// the first valid token.
124void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
125 bool FoundNonSkipPortion,
126 bool FoundElse) {
127 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000128 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000129
Ted Kremenek60e45d42008-11-18 00:34:22 +0000130 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000131 FoundNonSkipPortion, FoundElse);
132
Ted Kremenek268ee702008-12-12 18:34:08 +0000133 if (CurPTHLexer) {
134 PTHSkipExcludedConditionalBlock();
135 return;
136 }
137
Chris Lattner141e71f2008-03-09 01:54:53 +0000138 // Enter raw mode to disable identifier lookup (and thus macro expansion),
139 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000140 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000141 Token Tok;
142 while (1) {
Ted Kremenekf6452c52008-11-18 01:04:47 +0000143 if (CurLexer)
144 CurLexer->Lex(Tok);
145 else
146 CurPTHLexer->Lex(Tok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000147
148 // If this is the end of the buffer, we have an error.
149 if (Tok.is(tok::eof)) {
150 // Emit errors for each unterminated conditional on the stack, including
151 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000152 while (!CurPPLexer->ConditionalStack.empty()) {
153 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000154 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000155 CurPPLexer->ConditionalStack.pop_back();
Chris Lattner141e71f2008-03-09 01:54:53 +0000156 }
157
158 // Just return and let the caller lex after this #include.
159 break;
160 }
161
162 // If this token is not a preprocessor directive, just skip it.
163 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
164 continue;
165
166 // We just parsed a # character at the start of a line, so we're in
167 // directive mode. Tell the lexer this so any newlines we see will be
168 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000169 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000170 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000171
172
173 // Read the next token, the directive flavor.
174 LexUnexpandedToken(Tok);
175
176 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
177 // something bogus), skip it.
178 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000179 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000180 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000181 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000182 continue;
183 }
184
185 // If the first letter isn't i or e, it isn't intesting to us. We know that
186 // this is safe in the face of spelling differences, because there is no way
187 // to spell an i/e in a strange way that is another letter. Skipping this
188 // allows us to avoid looking up the identifier info for #define/#undef and
189 // other common directives.
190 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
191 char FirstChar = RawCharData[0];
192 if (FirstChar >= 'a' && FirstChar <= 'z' &&
193 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000194 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000195 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000196 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000197 continue;
198 }
199
200 // Get the identifier name without trigraphs or embedded newlines. Note
201 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
202 // when skipping.
203 // TODO: could do this with zero copies in the no-clean case by using
204 // strncmp below.
205 char Directive[20];
206 unsigned IdLen;
207 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
208 IdLen = Tok.getLength();
209 memcpy(Directive, RawCharData, IdLen);
210 Directive[IdLen] = 0;
211 } else {
212 std::string DirectiveStr = getSpelling(Tok);
213 IdLen = DirectiveStr.size();
214 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000215 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000216 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000217 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000218 continue;
219 }
220 memcpy(Directive, &DirectiveStr[0], IdLen);
221 Directive[IdLen] = 0;
Chris Lattner202fd2c2009-01-27 05:34:03 +0000222 FirstChar = Directive[0];
Chris Lattner141e71f2008-03-09 01:54:53 +0000223 }
224
225 if (FirstChar == 'i' && Directive[1] == 'f') {
226 if ((IdLen == 2) || // "if"
227 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
228 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
229 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
230 // bother parsing the condition.
231 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000232 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000233 /*foundnonskip*/false,
234 /*fnddelse*/false);
235 }
236 } else if (FirstChar == 'e') {
237 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
238 CheckEndOfDirective("#endif");
239 PPConditionalInfo CondInfo;
240 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000241 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000242 InCond = InCond; // Silence warning in no-asserts mode.
243 assert(!InCond && "Can't be skipping if not in a conditional!");
244
245 // If we popped the outermost skipping block, we're done skipping!
246 if (!CondInfo.WasSkipping)
247 break;
248 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
249 // #else directive in a skipping conditional. If not in some other
250 // skipping conditional, and if #else hasn't already been seen, enter it
251 // as a non-skipping conditional.
252 CheckEndOfDirective("#else");
Ted Kremenek60e45d42008-11-18 00:34:22 +0000253 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000254
255 // If this is a #else with a #else before it, report the error.
256 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
257
258 // Note that we've seen a #else in this conditional.
259 CondInfo.FoundElse = true;
260
261 // If the conditional is at the top level, and the #if block wasn't
262 // entered, enter the #else block now.
263 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
264 CondInfo.FoundNonSkip = true;
265 break;
266 }
267 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000268 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000269
270 bool ShouldEnter;
271 // If this is in a skipping block or if we're already handled this #if
272 // block, don't bother parsing the condition.
273 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
274 DiscardUntilEndOfDirective();
275 ShouldEnter = false;
276 } else {
277 // Restore the value of LexingRawMode so that identifiers are
278 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000279 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
280 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000281 IdentifierInfo *IfNDefMacro = 0;
282 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000283 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000284 }
285
286 // If this is a #elif with a #else before it, report the error.
287 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
288
289 // If this condition is true, enter it!
290 if (ShouldEnter) {
291 CondInfo.FoundNonSkip = true;
292 break;
293 }
294 }
295 }
296
Ted Kremenek60e45d42008-11-18 00:34:22 +0000297 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000298 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000299 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000300 }
301
302 // Finally, if we are out of the conditional (saw an #endif or ran off the end
303 // of the file, just stop skipping and return to lexing whatever came after
304 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000305 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000306}
307
Ted Kremenek268ee702008-12-12 18:34:08 +0000308void Preprocessor::PTHSkipExcludedConditionalBlock() {
309
310 while(1) {
311 assert(CurPTHLexer);
312 assert(CurPTHLexer->LexingRawMode == false);
313
314 // Skip to the next '#else', '#elif', or #endif.
315 if (CurPTHLexer->SkipBlock()) {
316 // We have reached an #endif. Both the '#' and 'endif' tokens
317 // have been consumed by the PTHLexer. Just pop off the condition level.
318 PPConditionalInfo CondInfo;
319 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
320 InCond = InCond; // Silence warning in no-asserts mode.
321 assert(!InCond && "Can't be skipping if not in a conditional!");
322 break;
323 }
324
325 // We have reached a '#else' or '#elif'. Lex the next token to get
326 // the directive flavor.
327 Token Tok;
328 LexUnexpandedToken(Tok);
329
330 // We can actually look up the IdentifierInfo here since we aren't in
331 // raw mode.
332 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
333
334 if (K == tok::pp_else) {
335 // #else: Enter the else condition. We aren't in a nested condition
336 // since we skip those. We're always in the one matching the last
337 // blocked we skipped.
338 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
339 // Note that we've seen a #else in this conditional.
340 CondInfo.FoundElse = true;
341
342 // If the #if block wasn't entered then enter the #else block now.
343 if (!CondInfo.FoundNonSkip) {
344 CondInfo.FoundNonSkip = true;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000345
346 // Consume the eom token.
347 CurPTHLexer->ParsingPreprocessorDirective = true;
348 LexUnexpandedToken(Tok);
349 assert(Tok.is(tok::eom));
350 CurPTHLexer->ParsingPreprocessorDirective = false;
351
Ted Kremenek268ee702008-12-12 18:34:08 +0000352 break;
353 }
354
355 // Otherwise skip this block.
356 continue;
357 }
358
359 assert(K == tok::pp_elif);
360 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
361
362 // If this is a #elif with a #else before it, report the error.
363 if (CondInfo.FoundElse)
364 Diag(Tok, diag::pp_err_elif_after_else);
365
366 // If this is in a skipping block or if we're already handled this #if
367 // block, don't bother parsing the condition. We just skip this block.
368 if (CondInfo.FoundNonSkip)
369 continue;
370
371 // Evaluate the condition of the #elif.
372 IdentifierInfo *IfNDefMacro = 0;
373 CurPTHLexer->ParsingPreprocessorDirective = true;
374 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
375 CurPTHLexer->ParsingPreprocessorDirective = false;
376
377 // If this condition is true, enter it!
378 if (ShouldEnter) {
379 CondInfo.FoundNonSkip = true;
380 break;
381 }
382
383 // Otherwise, skip this block and go to the next one.
384 continue;
385 }
386}
387
Chris Lattner10725092008-03-09 04:17:44 +0000388/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
389/// return null on failure. isAngled indicates whether the file reference is
390/// for system #include's or not (i.e. using <> instead of "").
391const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
392 const char *FilenameEnd,
393 bool isAngled,
394 const DirectoryLookup *FromDir,
395 const DirectoryLookup *&CurDir) {
396 // If the header lookup mechanism may be relative to the current file, pass in
397 // info about where the current file is.
398 const FileEntry *CurFileEnt = 0;
399 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000400 FileID FID = getCurrentFileLexer()->getFileID();
401 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Chris Lattner10725092008-03-09 04:17:44 +0000402 }
403
404 // Do a standard file entry lookup.
405 CurDir = CurDirLookup;
406 const FileEntry *FE =
407 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
408 isAngled, FromDir, CurDir, CurFileEnt);
409 if (FE) return FE;
410
411 // Otherwise, see if this is a subframework header. If so, this is relative
412 // to one of the headers on the #include stack. Walk the list of the current
413 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000414 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000415 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000416 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
417 CurFileEnt)))
418 return FE;
419 }
420
421 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
422 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000423 if (IsFileLexer(ISEntry)) {
Chris Lattner10725092008-03-09 04:17:44 +0000424 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000425 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000426 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
427 FilenameEnd, CurFileEnt)))
428 return FE;
429 }
430 }
431
432 // Otherwise, we really couldn't find the file.
433 return 0;
434}
435
Chris Lattner141e71f2008-03-09 01:54:53 +0000436
437//===----------------------------------------------------------------------===//
438// Preprocessor Directive Handling.
439//===----------------------------------------------------------------------===//
440
441/// HandleDirective - This callback is invoked when the lexer sees a # token
442/// at the start of a line. This consumes the directive, modifies the
443/// lexer/preprocessor state, and advances the lexer(s) so that the next token
444/// read is the correct one.
445void Preprocessor::HandleDirective(Token &Result) {
446 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
447
448 // We just parsed a # character at the start of a line, so we're in directive
449 // mode. Tell the lexer this so any newlines we see will be converted into an
450 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000451 CurPPLexer->ParsingPreprocessorDirective = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000452
453 ++NumDirectives;
454
455 // We are about to read a token. For the multiple-include optimization FA to
456 // work, we have to remember if we had read any tokens *before* this
457 // pp-directive.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000458 bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Chris Lattner141e71f2008-03-09 01:54:53 +0000459
460 // Read the next token, the directive flavor. This isn't expanded due to
461 // C99 6.10.3p8.
462 LexUnexpandedToken(Result);
463
464 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
465 // #define A(x) #x
466 // A(abc
467 // #warning blah
468 // def)
469 // If so, the user is relying on non-portable behavior, emit a diagnostic.
470 if (InMacroArgs)
471 Diag(Result, diag::ext_embedded_directive);
472
473TryAgain:
474 switch (Result.getKind()) {
475 case tok::eom:
476 return; // null directive.
477 case tok::comment:
478 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
479 LexUnexpandedToken(Result);
480 goto TryAgain;
481
Chris Lattner478a18e2009-01-26 06:19:46 +0000482 case tok::numeric_constant: // # 7 GNU line marker directive.
483 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000484 default:
485 IdentifierInfo *II = Result.getIdentifierInfo();
486 if (II == 0) break; // Not an identifier.
487
488 // Ask what the preprocessor keyword ID is.
489 switch (II->getPPKeywordID()) {
490 default: break;
491 // C99 6.10.1 - Conditional Inclusion.
492 case tok::pp_if:
493 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
494 case tok::pp_ifdef:
495 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
496 case tok::pp_ifndef:
497 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
498 case tok::pp_elif:
499 return HandleElifDirective(Result);
500 case tok::pp_else:
501 return HandleElseDirective(Result);
502 case tok::pp_endif:
503 return HandleEndifDirective(Result);
504
505 // C99 6.10.2 - Source File Inclusion.
506 case tok::pp_include:
507 return HandleIncludeDirective(Result); // Handle #include.
508
509 // C99 6.10.3 - Macro Replacement.
510 case tok::pp_define:
511 return HandleDefineDirective(Result);
512 case tok::pp_undef:
513 return HandleUndefDirective(Result);
514
515 // C99 6.10.4 - Line Control.
516 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000517 return HandleLineDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000518
519 // C99 6.10.5 - Error Directive.
520 case tok::pp_error:
521 return HandleUserDiagnosticDirective(Result, false);
522
523 // C99 6.10.6 - Pragma Directive.
524 case tok::pp_pragma:
525 return HandlePragmaDirective();
526
527 // GNU Extensions.
528 case tok::pp_import:
529 return HandleImportDirective(Result);
530 case tok::pp_include_next:
531 return HandleIncludeNextDirective(Result);
532
533 case tok::pp_warning:
534 Diag(Result, diag::ext_pp_warning_directive);
535 return HandleUserDiagnosticDirective(Result, true);
536 case tok::pp_ident:
537 return HandleIdentSCCSDirective(Result);
538 case tok::pp_sccs:
539 return HandleIdentSCCSDirective(Result);
540 case tok::pp_assert:
541 //isExtension = true; // FIXME: implement #assert
542 break;
543 case tok::pp_unassert:
544 //isExtension = true; // FIXME: implement #unassert
545 break;
546 }
547 break;
548 }
549
550 // If we reached here, the preprocessing token is not valid!
551 Diag(Result, diag::err_pp_invalid_directive);
552
553 // Read the rest of the PP line.
554 DiscardUntilEndOfDirective();
555
556 // Okay, we're done parsing the directive.
557}
558
Chris Lattner478a18e2009-01-26 06:19:46 +0000559/// GetLineValue - Convert a numeric token into an unsigned value, emitting
560/// Diagnostic DiagID if it is invalid, and returning the value in Val.
561static bool GetLineValue(Token &DigitTok, unsigned &Val,
562 unsigned DiagID, Preprocessor &PP) {
563 if (DigitTok.isNot(tok::numeric_constant)) {
564 PP.Diag(DigitTok, DiagID);
565
566 if (DigitTok.isNot(tok::eom))
567 PP.DiscardUntilEndOfDirective();
568 return true;
569 }
570
571 llvm::SmallString<64> IntegerBuffer;
572 IntegerBuffer.resize(DigitTok.getLength());
573 const char *DigitTokBegin = &IntegerBuffer[0];
574 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
575 NumericLiteralParser Literal(DigitTokBegin, DigitTokBegin+ActualLength,
576 DigitTok.getLocation(), PP);
577 if (Literal.hadError)
578 return true; // Error already emitted.
579
580 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
581 PP.Diag(DigitTok, DiagID);
582 return true;
583 }
584
585 // Parse the integer literal into Result.
586 llvm::APInt APVal(32, 0);
587 if (Literal.GetIntegerValue(APVal)) {
588 // Overflow parsing integer literal.
589 PP.Diag(DigitTok, DiagID);
590 return true;
591 }
592 Val = APVal.getZExtValue();
593
594 // Reject 0, this is needed both by #line numbers and flags.
595 if (Val == 0) {
596 PP.Diag(DigitTok, DiagID);
597 PP.DiscardUntilEndOfDirective();
598 return true;
599 }
600
601 return false;
602}
603
Chris Lattner359cc442009-01-26 05:29:08 +0000604/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
605/// acceptable forms are:
606/// # line digit-sequence
607/// # line digit-sequence "s-char-sequence"
608void Preprocessor::HandleLineDirective(Token &Tok) {
609 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
610 // expanded.
611 Token DigitTok;
612 Lex(DigitTok);
613
Chris Lattner359cc442009-01-26 05:29:08 +0000614 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000615 unsigned LineNo;
616 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer, *this))
Chris Lattner359cc442009-01-26 05:29:08 +0000617 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000618
Chris Lattner478a18e2009-01-26 06:19:46 +0000619 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
620 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000621 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
622 if (LineNo >= LineLimit)
623 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
624
Chris Lattner5b9a5042009-01-26 07:57:50 +0000625 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000626 Token StrTok;
627 Lex(StrTok);
628
629 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
630 // string followed by eom.
631 if (StrTok.is(tok::eom))
632 ; // ok
633 else if (StrTok.isNot(tok::string_literal)) {
634 Diag(StrTok, diag::err_pp_line_invalid_filename);
635 DiscardUntilEndOfDirective();
636 return;
637 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000638 // Parse and validate the string, converting it into a unique ID.
639 StringLiteralParser Literal(&StrTok, 1, *this);
640 assert(!Literal.AnyWide && "Didn't allow wide strings in");
641 if (Literal.hadError)
642 return DiscardUntilEndOfDirective();
643 if (Literal.Pascal) {
644 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
645 return DiscardUntilEndOfDirective();
646 }
647 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
648 Literal.GetStringLength());
649
Chris Lattner359cc442009-01-26 05:29:08 +0000650 // Verify that there is nothing after the string, other than EOM.
651 CheckEndOfDirective("#line");
652 }
653
Chris Lattner4c4ea172009-02-03 21:52:55 +0000654 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Chris Lattner359cc442009-01-26 05:29:08 +0000655}
656
Chris Lattner478a18e2009-01-26 06:19:46 +0000657/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
658/// marker directive.
659static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
660 bool &IsSystemHeader, bool &IsExternCHeader,
661 Preprocessor &PP) {
662 unsigned FlagVal;
663 Token FlagTok;
664 PP.Lex(FlagTok);
665 if (FlagTok.is(tok::eom)) return false;
666 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
667 return true;
668
669 if (FlagVal == 1) {
670 IsFileEntry = true;
671
672 PP.Lex(FlagTok);
673 if (FlagTok.is(tok::eom)) return false;
674 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
675 return true;
676 } else if (FlagVal == 2) {
677 IsFileExit = true;
678
Chris Lattner137b6a62009-02-04 06:25:26 +0000679 SourceManager &SM = PP.getSourceManager();
680 // If we are leaving the current presumed file, check to make sure the
681 // presumed include stack isn't empty!
682 FileID CurFileID =
683 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
684 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
685
686 // If there is no include loc (main file) or if the include loc is in a
687 // different physical file, then we aren't in a "1" line marker flag region.
688 SourceLocation IncLoc = PLoc.getIncludeLoc();
689 if (IncLoc.isInvalid() ||
690 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
691 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
692 PP.DiscardUntilEndOfDirective();
693 return true;
694 }
695
Chris Lattner478a18e2009-01-26 06:19:46 +0000696 PP.Lex(FlagTok);
697 if (FlagTok.is(tok::eom)) return false;
698 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
699 return true;
700 }
701
702 // We must have 3 if there are still flags.
703 if (FlagVal != 3) {
704 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000705 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000706 return true;
707 }
708
709 IsSystemHeader = true;
710
711 PP.Lex(FlagTok);
712 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000713 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000714 return true;
715
716 // We must have 4 if there is yet another flag.
717 if (FlagVal != 4) {
718 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000719 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000720 return true;
721 }
722
723 IsExternCHeader = true;
724
725 PP.Lex(FlagTok);
726 if (FlagTok.is(tok::eom)) return false;
727
728 // There are no more valid flags here.
729 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000730 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000731 return true;
732}
733
734/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
735/// one of the following forms:
736///
737/// # 42
738/// # 42 "file" ('1' | '2')?
739/// # 42 "file" ('1' | '2')? '3' '4'?
740///
741void Preprocessor::HandleDigitDirective(Token &DigitTok) {
742 // Validate the number and convert it to an unsigned. GNU does not have a
743 // line # limit other than it fit in 32-bits.
744 unsigned LineNo;
745 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
746 *this))
747 return;
748
749 Token StrTok;
750 Lex(StrTok);
751
752 bool IsFileEntry = false, IsFileExit = false;
753 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000754 int FilenameID = -1;
755
Chris Lattner478a18e2009-01-26 06:19:46 +0000756 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
757 // string followed by eom.
758 if (StrTok.is(tok::eom))
759 ; // ok
760 else if (StrTok.isNot(tok::string_literal)) {
761 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000762 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000763 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000764 // Parse and validate the string, converting it into a unique ID.
765 StringLiteralParser Literal(&StrTok, 1, *this);
766 assert(!Literal.AnyWide && "Didn't allow wide strings in");
767 if (Literal.hadError)
768 return DiscardUntilEndOfDirective();
769 if (Literal.Pascal) {
770 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
771 return DiscardUntilEndOfDirective();
772 }
773 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
774 Literal.GetStringLength());
775
Chris Lattner478a18e2009-01-26 06:19:46 +0000776 // If a filename was present, read any flags that are present.
777 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000778 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000779 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000780 }
Chris Lattner137b6a62009-02-04 06:25:26 +0000781
Chris Lattner9d79eba2009-02-04 05:21:58 +0000782 // Create a line note with this information.
783 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
784 IsFileEntry, IsFileExit,
785 IsSystemHeader, IsExternCHeader);
Chris Lattner478a18e2009-01-26 06:19:46 +0000786}
787
788
Chris Lattner099dd052009-01-26 05:30:54 +0000789/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
790///
Chris Lattner141e71f2008-03-09 01:54:53 +0000791void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
792 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000793 // PTH doesn't emit #warning or #error directives.
794 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000795 return CurPTHLexer->DiscardToEndOfLine();
796
Chris Lattner141e71f2008-03-09 01:54:53 +0000797 // Read the rest of the line raw. We do this because we don't want macros
798 // to be expanded and we don't require that the tokens be valid preprocessing
799 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
800 // collapse multiple consequtive white space between tokens, but this isn't
801 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000802 std::string Message = CurLexer->ReadToEndOfLine();
803 if (isWarning)
804 Diag(Tok, diag::pp_hash_warning) << Message;
805 else
806 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000807}
808
809/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
810///
811void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
812 // Yes, this directive is an extension.
813 Diag(Tok, diag::ext_pp_ident_directive);
814
815 // Read the string argument.
816 Token StrTok;
817 Lex(StrTok);
818
819 // If the token kind isn't a string, it's a malformed directive.
820 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000821 StrTok.isNot(tok::wide_string_literal)) {
822 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000823 if (StrTok.isNot(tok::eom))
824 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000825 return;
826 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000827
828 // Verify that there is nothing after the string, other than EOM.
829 CheckEndOfDirective("#ident");
830
831 if (Callbacks)
832 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
833}
834
835//===----------------------------------------------------------------------===//
836// Preprocessor Include Directive Handling.
837//===----------------------------------------------------------------------===//
838
839/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
840/// checked and spelled filename, e.g. as an operand of #include. This returns
841/// true if the input filename was in <>'s or false if it were in ""'s. The
842/// caller is expected to provide a buffer that is large enough to hold the
843/// spelling of the filename, but is also expected to handle the case when
844/// this method decides to use a different buffer.
845bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
846 const char *&BufStart,
847 const char *&BufEnd) {
848 // Get the text form of the filename.
849 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
850
851 // Make sure the filename is <x> or "x".
852 bool isAngled;
853 if (BufStart[0] == '<') {
854 if (BufEnd[-1] != '>') {
855 Diag(Loc, diag::err_pp_expects_filename);
856 BufStart = 0;
857 return true;
858 }
859 isAngled = true;
860 } else if (BufStart[0] == '"') {
861 if (BufEnd[-1] != '"') {
862 Diag(Loc, diag::err_pp_expects_filename);
863 BufStart = 0;
864 return true;
865 }
866 isAngled = false;
867 } else {
868 Diag(Loc, diag::err_pp_expects_filename);
869 BufStart = 0;
870 return true;
871 }
872
873 // Diagnose #include "" as invalid.
874 if (BufEnd-BufStart <= 2) {
875 Diag(Loc, diag::err_pp_empty_filename);
876 BufStart = 0;
877 return "";
878 }
879
880 // Skip the brackets.
881 ++BufStart;
882 --BufEnd;
883 return isAngled;
884}
885
886/// ConcatenateIncludeName - Handle cases where the #include name is expanded
887/// from a macro as multiple tokens, which need to be glued together. This
888/// occurs for code like:
889/// #define FOO <a/b.h>
890/// #include FOO
891/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
892///
893/// This code concatenates and consumes tokens up to the '>' token. It returns
894/// false if the > was found, otherwise it returns true if it finds and consumes
895/// the EOM marker.
896static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
897 Preprocessor &PP) {
898 Token CurTok;
899
900 PP.Lex(CurTok);
901 while (CurTok.isNot(tok::eom)) {
902 // Append the spelling of this token to the buffer. If there was a space
903 // before it, add it now.
904 if (CurTok.hasLeadingSpace())
905 FilenameBuffer.push_back(' ');
906
907 // Get the spelling of the token, directly into FilenameBuffer if possible.
908 unsigned PreAppendSize = FilenameBuffer.size();
909 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
910
911 const char *BufPtr = &FilenameBuffer[PreAppendSize];
912 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
913
914 // If the token was spelled somewhere else, copy it into FilenameBuffer.
915 if (BufPtr != &FilenameBuffer[PreAppendSize])
916 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
917
918 // Resize FilenameBuffer to the correct size.
919 if (CurTok.getLength() != ActualLen)
920 FilenameBuffer.resize(PreAppendSize+ActualLen);
921
922 // If we found the '>' marker, return success.
923 if (CurTok.is(tok::greater))
924 return false;
925
926 PP.Lex(CurTok);
927 }
928
929 // If we hit the eom marker, emit an error and return true so that the caller
930 // knows the EOM has been read.
931 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
932 return true;
933}
934
935/// HandleIncludeDirective - The "#include" tokens have just been read, read the
936/// file to be included from the lexer, then include it! This is a common
937/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +0000938/// #import. LookupFrom is set when this is a #include_next directive, it
939/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +0000940void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
941 const DirectoryLookup *LookupFrom,
942 bool isImport) {
943
944 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +0000945 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000946
947 // Reserve a buffer to get the spelling.
948 llvm::SmallVector<char, 128> FilenameBuffer;
949 const char *FilenameStart, *FilenameEnd;
950
951 switch (FilenameTok.getKind()) {
952 case tok::eom:
953 // If the token kind is EOM, the error has already been diagnosed.
954 return;
955
956 case tok::angle_string_literal:
957 case tok::string_literal: {
958 FilenameBuffer.resize(FilenameTok.getLength());
959 FilenameStart = &FilenameBuffer[0];
960 unsigned Len = getSpelling(FilenameTok, FilenameStart);
961 FilenameEnd = FilenameStart+Len;
962 break;
963 }
964
965 case tok::less:
966 // This could be a <foo/bar.h> file coming from a macro expansion. In this
967 // case, glue the tokens together into FilenameBuffer and interpret those.
968 FilenameBuffer.push_back('<');
969 if (ConcatenateIncludeName(FilenameBuffer, *this))
970 return; // Found <eom> but no ">"? Diagnostic already emitted.
971 FilenameStart = &FilenameBuffer[0];
972 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
973 break;
974 default:
975 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
976 DiscardUntilEndOfDirective();
977 return;
978 }
979
980 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
981 FilenameStart, FilenameEnd);
982 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
983 // error.
984 if (FilenameStart == 0) {
985 DiscardUntilEndOfDirective();
986 return;
987 }
988
989 // Verify that there is nothing after the filename, other than EOM. Use the
990 // preprocessor to lex this in case lexing the filename entered a macro.
991 CheckEndOfDirective("#include");
992
993 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +0000994 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
995 Diag(FilenameTok, diag::err_pp_include_too_deep);
996 return;
997 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000998
999 // Search include directories.
1000 const DirectoryLookup *CurDir;
1001 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1002 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001003 if (File == 0) {
1004 Diag(FilenameTok, diag::err_pp_file_not_found)
1005 << std::string(FilenameStart, FilenameEnd);
1006 return;
1007 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001008
Chris Lattner72181832008-09-26 20:12:23 +00001009 // Ask HeaderInfo if we should enter this #include file. If not, #including
1010 // this file will have no effect.
1011 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001012 return;
Chris Lattner72181832008-09-26 20:12:23 +00001013
1014 // The #included file will be considered to be a system header if either it is
1015 // in a system include directory, or if the #includer is a system include
1016 // header.
Chris Lattner9d728512008-10-27 01:19:25 +00001017 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001018 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001019 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Chris Lattner72181832008-09-26 20:12:23 +00001020
Chris Lattner141e71f2008-03-09 01:54:53 +00001021 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001022 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1023 FileCharacter);
1024 if (FID.isInvalid()) {
Chris Lattner56b05c82008-11-18 08:02:48 +00001025 Diag(FilenameTok, diag::err_pp_file_not_found)
1026 << std::string(FilenameStart, FilenameEnd);
1027 return;
1028 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001029
1030 // Finally, if all is good, enter the new file!
Chris Lattner2b2453a2009-01-17 06:22:33 +00001031 EnterSourceFile(FID, CurDir);
Chris Lattner141e71f2008-03-09 01:54:53 +00001032}
1033
1034/// HandleIncludeNextDirective - Implements #include_next.
1035///
1036void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1037 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1038
1039 // #include_next is like #include, except that we start searching after
1040 // the current found directory. If we can't do this, issue a
1041 // diagnostic.
1042 const DirectoryLookup *Lookup = CurDirLookup;
1043 if (isInPrimaryFile()) {
1044 Lookup = 0;
1045 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1046 } else if (Lookup == 0) {
1047 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1048 } else {
1049 // Start looking up in the next directory.
1050 ++Lookup;
1051 }
1052
1053 return HandleIncludeDirective(IncludeNextTok, Lookup);
1054}
1055
1056/// HandleImportDirective - Implements #import.
1057///
1058void Preprocessor::HandleImportDirective(Token &ImportTok) {
1059 Diag(ImportTok, diag::ext_pp_import_directive);
1060
1061 return HandleIncludeDirective(ImportTok, 0, true);
1062}
1063
1064//===----------------------------------------------------------------------===//
1065// Preprocessor Macro Directive Handling.
1066//===----------------------------------------------------------------------===//
1067
1068/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1069/// definition has just been read. Lex the rest of the arguments and the
1070/// closing ), updating MI with what we learn. Return true if an error occurs
1071/// parsing the arg list.
1072bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1073 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1074
1075 Token Tok;
1076 while (1) {
1077 LexUnexpandedToken(Tok);
1078 switch (Tok.getKind()) {
1079 case tok::r_paren:
1080 // Found the end of the argument list.
1081 if (Arguments.empty()) { // #define FOO()
1082 MI->setArgumentList(Arguments.begin(), Arguments.end());
1083 return false;
1084 }
1085 // Otherwise we have #define FOO(A,)
1086 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1087 return true;
1088 case tok::ellipsis: // #define X(... -> C99 varargs
1089 // Warn if use of C99 feature in non-C99 mode.
1090 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1091
1092 // Lex the token after the identifier.
1093 LexUnexpandedToken(Tok);
1094 if (Tok.isNot(tok::r_paren)) {
1095 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1096 return true;
1097 }
1098 // Add the __VA_ARGS__ identifier as an argument.
1099 Arguments.push_back(Ident__VA_ARGS__);
1100 MI->setIsC99Varargs();
1101 MI->setArgumentList(Arguments.begin(), Arguments.end());
1102 return false;
1103 case tok::eom: // #define X(
1104 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1105 return true;
1106 default:
1107 // Handle keywords and identifiers here to accept things like
1108 // #define Foo(for) for.
1109 IdentifierInfo *II = Tok.getIdentifierInfo();
1110 if (II == 0) {
1111 // #define X(1
1112 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1113 return true;
1114 }
1115
1116 // If this is already used as an argument, it is used multiple times (e.g.
1117 // #define X(A,A.
1118 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1119 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001120 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001121 return true;
1122 }
1123
1124 // Add the argument to the macro info.
1125 Arguments.push_back(II);
1126
1127 // Lex the token after the identifier.
1128 LexUnexpandedToken(Tok);
1129
1130 switch (Tok.getKind()) {
1131 default: // #define X(A B
1132 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1133 return true;
1134 case tok::r_paren: // #define X(A)
1135 MI->setArgumentList(Arguments.begin(), Arguments.end());
1136 return false;
1137 case tok::comma: // #define X(A,
1138 break;
1139 case tok::ellipsis: // #define X(A... -> GCC extension
1140 // Diagnose extension.
1141 Diag(Tok, diag::ext_named_variadic_macro);
1142
1143 // Lex the token after the identifier.
1144 LexUnexpandedToken(Tok);
1145 if (Tok.isNot(tok::r_paren)) {
1146 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1147 return true;
1148 }
1149
1150 MI->setIsGNUVarargs();
1151 MI->setArgumentList(Arguments.begin(), Arguments.end());
1152 return false;
1153 }
1154 }
1155 }
1156}
1157
1158/// HandleDefineDirective - Implements #define. This consumes the entire macro
1159/// line then lets the caller lex the next real token.
1160void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1161 ++NumDefined;
1162
1163 Token MacroNameTok;
1164 ReadMacroName(MacroNameTok, 1);
1165
1166 // Error reading macro name? If so, diagnostic already issued.
1167 if (MacroNameTok.is(tok::eom))
1168 return;
1169
1170 // If we are supposed to keep comments in #defines, reenable comment saving
1171 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001172 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Chris Lattner141e71f2008-03-09 01:54:53 +00001173
1174 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001175 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001176
1177 Token Tok;
1178 LexUnexpandedToken(Tok);
1179
1180 // If this is a function-like macro definition, parse the argument list,
1181 // marking each of the identifiers as being used as macro arguments. Also,
1182 // check other constraints on the first token of the macro body.
1183 if (Tok.is(tok::eom)) {
1184 // If there is no body to this macro, we have no special handling here.
1185 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
1186 // This is a function-like macro definition. Read the argument list.
1187 MI->setIsFunctionLike();
1188 if (ReadMacroDefinitionArgList(MI)) {
1189 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001190 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001191 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001192 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001193 DiscardUntilEndOfDirective();
1194 return;
1195 }
1196
1197 // Read the first token after the arg list for down below.
1198 LexUnexpandedToken(Tok);
1199 } else if (!Tok.hasLeadingSpace()) {
1200 // C99 requires whitespace between the macro definition and the body. Emit
1201 // a diagnostic for something like "#define X+".
1202 if (Features.C99) {
1203 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1204 } else {
1205 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1206 // one in some cases!
1207 }
1208 } else {
1209 // This is a normal token with leading space. Clear the leading space
1210 // marker on the first token to get proper expansion.
1211 Tok.clearFlag(Token::LeadingSpace);
1212 }
1213
1214 // If this is a definition of a variadic C99 function-like macro, not using
1215 // the GNU named varargs extension, enabled __VA_ARGS__.
1216
1217 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1218 // This gets unpoisoned where it is allowed.
1219 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1220 if (MI->isC99Varargs())
1221 Ident__VA_ARGS__->setIsPoisoned(false);
1222
1223 // Read the rest of the macro body.
1224 if (MI->isObjectLike()) {
1225 // Object-like macros are very simple, just read their body.
1226 while (Tok.isNot(tok::eom)) {
1227 MI->AddTokenToBody(Tok);
1228 // Get the next token of the macro.
1229 LexUnexpandedToken(Tok);
1230 }
1231
1232 } else {
1233 // Otherwise, read the body of a function-like macro. This has to validate
1234 // the # (stringize) operator.
1235 while (Tok.isNot(tok::eom)) {
1236 MI->AddTokenToBody(Tok);
1237
1238 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1239 // parameters in function-like macro expansions.
1240 if (Tok.isNot(tok::hash)) {
1241 // Get the next token of the macro.
1242 LexUnexpandedToken(Tok);
1243 continue;
1244 }
1245
1246 // Get the next token of the macro.
1247 LexUnexpandedToken(Tok);
1248
1249 // Not a macro arg identifier?
1250 if (!Tok.getIdentifierInfo() ||
1251 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1252 Diag(Tok, diag::err_pp_stringize_not_parameter);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001253 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001254
1255 // Disable __VA_ARGS__ again.
1256 Ident__VA_ARGS__->setIsPoisoned(true);
1257 return;
1258 }
1259
1260 // Things look ok, add the param name token to the macro.
1261 MI->AddTokenToBody(Tok);
1262
1263 // Get the next token of the macro.
1264 LexUnexpandedToken(Tok);
1265 }
1266 }
1267
1268
1269 // Disable __VA_ARGS__ again.
1270 Ident__VA_ARGS__->setIsPoisoned(true);
1271
1272 // Check that there is no paste (##) operator at the begining or end of the
1273 // replacement list.
1274 unsigned NumTokens = MI->getNumTokens();
1275 if (NumTokens != 0) {
1276 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1277 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001278 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001279 return;
1280 }
1281 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1282 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001283 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001284 return;
1285 }
1286 }
1287
1288 // If this is the primary source file, remember that this macro hasn't been
1289 // used yet.
1290 if (isInPrimaryFile())
1291 MI->setIsUsed(false);
1292
1293 // Finally, if this identifier already had a macro defined for it, verify that
1294 // the macro bodies are identical and free the old definition.
1295 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001296 // It is very common for system headers to have tons of macro redefinitions
1297 // and for warnings to be disabled in system headers. If this is the case,
1298 // then don't bother calling MacroInfo::isIdenticalTo.
1299 if (!Diags.getSuppressSystemWarnings() ||
1300 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1301 if (!OtherMI->isUsed())
1302 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001303
Chris Lattner41c3ae12009-01-16 19:50:11 +00001304 // Macros must be identical. This means all tokes and whitespace
1305 // separation must be the same. C99 6.10.3.2.
1306 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1307 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1308 << MacroNameTok.getIdentifierInfo();
1309 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1310 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001311 }
Chris Lattner41c3ae12009-01-16 19:50:11 +00001312
Ted Kremenek0ea76722008-12-15 19:56:42 +00001313 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001314 }
1315
1316 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
1317}
1318
1319/// HandleUndefDirective - Implements #undef.
1320///
1321void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1322 ++NumUndefined;
1323
1324 Token MacroNameTok;
1325 ReadMacroName(MacroNameTok, 2);
1326
1327 // Error reading macro name? If so, diagnostic already issued.
1328 if (MacroNameTok.is(tok::eom))
1329 return;
1330
1331 // Check to see if this is the last token on the #undef line.
1332 CheckEndOfDirective("#undef");
1333
1334 // Okay, we finally have a valid identifier to undef.
1335 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1336
1337 // If the macro is not defined, this is a noop undef, just return.
1338 if (MI == 0) return;
1339
1340 if (!MI->isUsed())
1341 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1342
1343 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001344 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001345 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1346}
1347
1348
1349//===----------------------------------------------------------------------===//
1350// Preprocessor Conditional Directive Handling.
1351//===----------------------------------------------------------------------===//
1352
1353/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1354/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1355/// if any tokens have been returned or pp-directives activated before this
1356/// #ifndef has been lexed.
1357///
1358void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1359 bool ReadAnyTokensBeforeDirective) {
1360 ++NumIf;
1361 Token DirectiveTok = Result;
1362
1363 Token MacroNameTok;
1364 ReadMacroName(MacroNameTok);
1365
1366 // Error reading macro name? If so, diagnostic already issued.
1367 if (MacroNameTok.is(tok::eom)) {
1368 // Skip code until we get to #endif. This helps with recovery by not
1369 // emitting an error when the #endif is reached.
1370 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1371 /*Foundnonskip*/false, /*FoundElse*/false);
1372 return;
1373 }
1374
1375 // Check to see if this is the last token on the #if[n]def line.
1376 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1377
Ted Kremenek60e45d42008-11-18 00:34:22 +00001378 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001379 // If the start of a top-level #ifdef, inform MIOpt.
1380 if (!ReadAnyTokensBeforeDirective) {
1381 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001382 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001383 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001384 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001385 }
1386
1387 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1388 MacroInfo *MI = getMacroInfo(MII);
1389
1390 // If there is a macro, process it.
1391 if (MI) // Mark it used.
1392 MI->setIsUsed(true);
1393
1394 // Should we include the stuff contained by this directive?
1395 if (!MI == isIfndef) {
1396 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001397 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001398 /*foundnonskip*/true, /*foundelse*/false);
1399 } else {
1400 // No, skip the contents of this block and return the first token after it.
1401 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1402 /*Foundnonskip*/false,
1403 /*FoundElse*/false);
1404 }
1405}
1406
1407/// HandleIfDirective - Implements the #if directive.
1408///
1409void Preprocessor::HandleIfDirective(Token &IfToken,
1410 bool ReadAnyTokensBeforeDirective) {
1411 ++NumIf;
1412
1413 // Parse and evaluation the conditional expression.
1414 IdentifierInfo *IfNDefMacro = 0;
1415 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1416
Nuno Lopes0049db62008-06-01 18:31:24 +00001417
1418 // If this condition is equivalent to #ifndef X, and if this is the first
1419 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001420 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001421 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001422 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001423 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001424 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001425 }
1426
Chris Lattner141e71f2008-03-09 01:54:53 +00001427 // Should we include the stuff contained by this directive?
1428 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001429 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001430 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001431 /*foundnonskip*/true, /*foundelse*/false);
1432 } else {
1433 // No, skip the contents of this block and return the first token after it.
1434 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1435 /*FoundElse*/false);
1436 }
1437}
1438
1439/// HandleEndifDirective - Implements the #endif directive.
1440///
1441void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1442 ++NumEndif;
1443
1444 // Check that this is the whole directive.
1445 CheckEndOfDirective("#endif");
1446
1447 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001448 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001449 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001450 Diag(EndifToken, diag::err_pp_endif_without_if);
1451 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001452 }
1453
1454 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001455 if (CurPPLexer->getConditionalStackDepth() == 0)
1456 CurPPLexer->MIOpt.ExitTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001457
Ted Kremenek60e45d42008-11-18 00:34:22 +00001458 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001459 "This code should only be reachable in the non-skipping case!");
1460}
1461
1462
1463void Preprocessor::HandleElseDirective(Token &Result) {
1464 ++NumElse;
1465
1466 // #else directive in a non-skipping conditional... start skipping.
1467 CheckEndOfDirective("#else");
1468
1469 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001470 if (CurPPLexer->popConditionalLevel(CI)) {
1471 Diag(Result, diag::pp_err_else_without_if);
1472 return;
1473 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001474
1475 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001476 if (CurPPLexer->getConditionalStackDepth() == 0)
1477 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001478
1479 // If this is a #else with a #else before it, report the error.
1480 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1481
1482 // Finally, skip the rest of the contents of this block and return the first
1483 // token after it.
1484 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1485 /*FoundElse*/true);
1486}
1487
1488void Preprocessor::HandleElifDirective(Token &ElifToken) {
1489 ++NumElse;
1490
1491 // #elif directive in a non-skipping conditional... start skipping.
1492 // We don't care what the condition is, because we will always skip it (since
1493 // the block immediately before it was included).
1494 DiscardUntilEndOfDirective();
1495
1496 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001497 if (CurPPLexer->popConditionalLevel(CI)) {
1498 Diag(ElifToken, diag::pp_err_elif_without_if);
1499 return;
1500 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001501
1502 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001503 if (CurPPLexer->getConditionalStackDepth() == 0)
1504 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001505
1506 // If this is a #elif with a #else before it, report the error.
1507 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1508
1509 // Finally, skip the rest of the contents of this block and return the first
1510 // token after it.
1511 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1512 /*FoundElse*/CI.FoundElse);
1513}
1514