blob: 69a3efe287c7f797c17deb769352ab380698330d [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"
15#include "clang/Lex/HeaderSearch.h"
16#include "clang/Lex/MacroInfo.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000017#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/SourceManager.h"
19using namespace clang;
20
21//===----------------------------------------------------------------------===//
22// Utility Methods for Preprocessor Directive Handling.
23//===----------------------------------------------------------------------===//
24
25/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
26/// current line until the tok::eom token is found.
27void Preprocessor::DiscardUntilEndOfDirective() {
28 Token Tmp;
29 do {
30 LexUnexpandedToken(Tmp);
31 } while (Tmp.isNot(tok::eom));
32}
33
34/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
35static bool isCXXNamedOperator(const std::string &Spelling) {
36 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
37 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
38 Spelling == "or" || Spelling == "xor";
39}
40
41/// ReadMacroName - Lex and validate a macro name, which occurs after a
42/// #define or #undef. This sets the token kind to eom and discards the rest
43/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
44/// this is due to a a #define, 2 if #undef directive, 0 if it is something
45/// else (e.g. #ifdef).
46void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
47 // Read the token, don't allow macro expansion on it.
48 LexUnexpandedToken(MacroNameTok);
49
50 // Missing macro name?
51 if (MacroNameTok.is(tok::eom))
52 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
53
54 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
55 if (II == 0) {
56 std::string Spelling = getSpelling(MacroNameTok);
57 if (isCXXNamedOperator(Spelling))
58 // C++ 2.5p2: Alternative tokens behave the same as its primary token
59 // except for their spellings.
60 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
61 else
62 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
63 // Fall through on error.
64 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
65 // Error if defining "defined": C99 6.10.8.4.
66 Diag(MacroNameTok, diag::err_defined_macro_name);
67 } else if (isDefineUndef && II->hasMacroDefinition() &&
68 getMacroInfo(II)->isBuiltinMacro()) {
69 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
70 if (isDefineUndef == 1)
71 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
72 else
73 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
74 } else {
75 // Okay, we got a good identifier node. Return it.
76 return;
77 }
78
79 // Invalid macro name, read and discard the rest of the line. Then set the
80 // token kind to tok::eom.
81 MacroNameTok.setKind(tok::eom);
82 return DiscardUntilEndOfDirective();
83}
84
85/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
86/// not, emit a diagnostic and consume up until the eom.
87void Preprocessor::CheckEndOfDirective(const char *DirType) {
88 Token Tmp;
89 // Lex unexpanded tokens: macros might expand to zero tokens, causing us to
90 // miss diagnosing invalid lines.
91 LexUnexpandedToken(Tmp);
92
93 // There should be no tokens after the directive, but we allow them as an
94 // extension.
95 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
96 LexUnexpandedToken(Tmp);
97
98 if (Tmp.isNot(tok::eom)) {
99 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
100 DiscardUntilEndOfDirective();
101 }
102}
103
104
105
106/// SkipExcludedConditionalBlock - We just read a #if or related directive and
107/// decided that the subsequent tokens are in the #if'd out portion of the
108/// file. Lex the rest of the file, until we see an #endif. If
109/// FoundNonSkipPortion is true, then we have already emitted code for part of
110/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
111/// is true, then #else directives are ok, if not, then we have already seen one
112/// so a #else directive is a duplicate. When this returns, the caller can lex
113/// the first valid token.
114void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
115 bool FoundNonSkipPortion,
116 bool FoundElse) {
117 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000118 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000119
Ted Kremenek60e45d42008-11-18 00:34:22 +0000120 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000121 FoundNonSkipPortion, FoundElse);
122
123 // Enter raw mode to disable identifier lookup (and thus macro expansion),
124 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000125 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000126 Token Tok;
127 while (1) {
Ted Kremenekf6452c52008-11-18 01:04:47 +0000128 if (CurLexer)
129 CurLexer->Lex(Tok);
130 else
131 CurPTHLexer->Lex(Tok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000132
133 // If this is the end of the buffer, we have an error.
134 if (Tok.is(tok::eof)) {
135 // Emit errors for each unterminated conditional on the stack, including
136 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000137 while (!CurPPLexer->ConditionalStack.empty()) {
138 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000139 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000140 CurPPLexer->ConditionalStack.pop_back();
Chris Lattner141e71f2008-03-09 01:54:53 +0000141 }
142
143 // Just return and let the caller lex after this #include.
144 break;
145 }
146
147 // If this token is not a preprocessor directive, just skip it.
148 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
149 continue;
150
151 // We just parsed a # character at the start of a line, so we're in
152 // directive mode. Tell the lexer this so any newlines we see will be
153 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000154 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000155 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000156
157
158 // Read the next token, the directive flavor.
159 LexUnexpandedToken(Tok);
160
161 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
162 // something bogus), skip it.
163 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000164 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000165 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000166 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000167 continue;
168 }
169
170 // If the first letter isn't i or e, it isn't intesting to us. We know that
171 // this is safe in the face of spelling differences, because there is no way
172 // to spell an i/e in a strange way that is another letter. Skipping this
173 // allows us to avoid looking up the identifier info for #define/#undef and
174 // other common directives.
175 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
176 char FirstChar = RawCharData[0];
177 if (FirstChar >= 'a' && FirstChar <= 'z' &&
178 FirstChar != 'i' && FirstChar != 'e') {
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 // Get the identifier name without trigraphs or embedded newlines. Note
186 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
187 // when skipping.
188 // TODO: could do this with zero copies in the no-clean case by using
189 // strncmp below.
190 char Directive[20];
191 unsigned IdLen;
192 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
193 IdLen = Tok.getLength();
194 memcpy(Directive, RawCharData, IdLen);
195 Directive[IdLen] = 0;
196 } else {
197 std::string DirectiveStr = getSpelling(Tok);
198 IdLen = DirectiveStr.size();
199 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000200 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000201 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000202 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000203 continue;
204 }
205 memcpy(Directive, &DirectiveStr[0], IdLen);
206 Directive[IdLen] = 0;
207 }
208
209 if (FirstChar == 'i' && Directive[1] == 'f') {
210 if ((IdLen == 2) || // "if"
211 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
212 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
213 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
214 // bother parsing the condition.
215 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000216 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000217 /*foundnonskip*/false,
218 /*fnddelse*/false);
219 }
220 } else if (FirstChar == 'e') {
221 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
222 CheckEndOfDirective("#endif");
223 PPConditionalInfo CondInfo;
224 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000225 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000226 InCond = InCond; // Silence warning in no-asserts mode.
227 assert(!InCond && "Can't be skipping if not in a conditional!");
228
229 // If we popped the outermost skipping block, we're done skipping!
230 if (!CondInfo.WasSkipping)
231 break;
232 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
233 // #else directive in a skipping conditional. If not in some other
234 // skipping conditional, and if #else hasn't already been seen, enter it
235 // as a non-skipping conditional.
236 CheckEndOfDirective("#else");
Ted Kremenek60e45d42008-11-18 00:34:22 +0000237 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000238
239 // If this is a #else with a #else before it, report the error.
240 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
241
242 // Note that we've seen a #else in this conditional.
243 CondInfo.FoundElse = true;
244
245 // If the conditional is at the top level, and the #if block wasn't
246 // entered, enter the #else block now.
247 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
248 CondInfo.FoundNonSkip = true;
249 break;
250 }
251 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000252 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000253
254 bool ShouldEnter;
255 // If this is in a skipping block or if we're already handled this #if
256 // block, don't bother parsing the condition.
257 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
258 DiscardUntilEndOfDirective();
259 ShouldEnter = false;
260 } else {
261 // Restore the value of LexingRawMode so that identifiers are
262 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000263 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
264 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000265 IdentifierInfo *IfNDefMacro = 0;
266 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000267 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000268 }
269
270 // If this is a #elif with a #else before it, report the error.
271 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
272
273 // If this condition is true, enter it!
274 if (ShouldEnter) {
275 CondInfo.FoundNonSkip = true;
276 break;
277 }
278 }
279 }
280
Ted Kremenek60e45d42008-11-18 00:34:22 +0000281 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000282 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000283 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000284 }
285
286 // Finally, if we are out of the conditional (saw an #endif or ran off the end
287 // of the file, just stop skipping and return to lexing whatever came after
288 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000289 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000290}
291
Chris Lattner10725092008-03-09 04:17:44 +0000292/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
293/// return null on failure. isAngled indicates whether the file reference is
294/// for system #include's or not (i.e. using <> instead of "").
295const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
296 const char *FilenameEnd,
297 bool isAngled,
298 const DirectoryLookup *FromDir,
299 const DirectoryLookup *&CurDir) {
300 // If the header lookup mechanism may be relative to the current file, pass in
301 // info about where the current file is.
302 const FileEntry *CurFileEnt = 0;
303 if (!FromDir) {
304 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
305 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
306 }
307
308 // Do a standard file entry lookup.
309 CurDir = CurDirLookup;
310 const FileEntry *FE =
311 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
312 isAngled, FromDir, CurDir, CurFileEnt);
313 if (FE) return FE;
314
315 // Otherwise, see if this is a subframework header. If so, this is relative
316 // to one of the headers on the #include stack. Walk the list of the current
317 // headers on the #include stack and pass them to HeaderInfo.
318 if (CurLexer && !CurLexer->Is_PragmaLexer) {
319 if ((CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc())))
320 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
321 CurFileEnt)))
322 return FE;
323 }
324
325 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
326 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
327 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
328 if ((CurFileEnt =
329 SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc())))
330 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
331 FilenameEnd, CurFileEnt)))
332 return FE;
333 }
334 }
335
336 // Otherwise, we really couldn't find the file.
337 return 0;
338}
339
Chris Lattner141e71f2008-03-09 01:54:53 +0000340
341//===----------------------------------------------------------------------===//
342// Preprocessor Directive Handling.
343//===----------------------------------------------------------------------===//
344
345/// HandleDirective - This callback is invoked when the lexer sees a # token
346/// at the start of a line. This consumes the directive, modifies the
347/// lexer/preprocessor state, and advances the lexer(s) so that the next token
348/// read is the correct one.
349void Preprocessor::HandleDirective(Token &Result) {
350 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
351
352 // We just parsed a # character at the start of a line, so we're in directive
353 // mode. Tell the lexer this so any newlines we see will be converted into an
354 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000355 CurPPLexer->ParsingPreprocessorDirective = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000356
357 ++NumDirectives;
358
359 // We are about to read a token. For the multiple-include optimization FA to
360 // work, we have to remember if we had read any tokens *before* this
361 // pp-directive.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000362 bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Chris Lattner141e71f2008-03-09 01:54:53 +0000363
364 // Read the next token, the directive flavor. This isn't expanded due to
365 // C99 6.10.3p8.
366 LexUnexpandedToken(Result);
367
368 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
369 // #define A(x) #x
370 // A(abc
371 // #warning blah
372 // def)
373 // If so, the user is relying on non-portable behavior, emit a diagnostic.
374 if (InMacroArgs)
375 Diag(Result, diag::ext_embedded_directive);
376
377TryAgain:
378 switch (Result.getKind()) {
379 case tok::eom:
380 return; // null directive.
381 case tok::comment:
382 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
383 LexUnexpandedToken(Result);
384 goto TryAgain;
385
386 case tok::numeric_constant:
387 // FIXME: implement # 7 line numbers!
388 DiscardUntilEndOfDirective();
389 return;
390 default:
391 IdentifierInfo *II = Result.getIdentifierInfo();
392 if (II == 0) break; // Not an identifier.
393
394 // Ask what the preprocessor keyword ID is.
395 switch (II->getPPKeywordID()) {
396 default: break;
397 // C99 6.10.1 - Conditional Inclusion.
398 case tok::pp_if:
399 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
400 case tok::pp_ifdef:
401 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
402 case tok::pp_ifndef:
403 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
404 case tok::pp_elif:
405 return HandleElifDirective(Result);
406 case tok::pp_else:
407 return HandleElseDirective(Result);
408 case tok::pp_endif:
409 return HandleEndifDirective(Result);
410
411 // C99 6.10.2 - Source File Inclusion.
412 case tok::pp_include:
413 return HandleIncludeDirective(Result); // Handle #include.
414
415 // C99 6.10.3 - Macro Replacement.
416 case tok::pp_define:
417 return HandleDefineDirective(Result);
418 case tok::pp_undef:
419 return HandleUndefDirective(Result);
420
421 // C99 6.10.4 - Line Control.
422 case tok::pp_line:
423 // FIXME: implement #line
424 DiscardUntilEndOfDirective();
425 return;
426
427 // C99 6.10.5 - Error Directive.
428 case tok::pp_error:
429 return HandleUserDiagnosticDirective(Result, false);
430
431 // C99 6.10.6 - Pragma Directive.
432 case tok::pp_pragma:
433 return HandlePragmaDirective();
434
435 // GNU Extensions.
436 case tok::pp_import:
437 return HandleImportDirective(Result);
438 case tok::pp_include_next:
439 return HandleIncludeNextDirective(Result);
440
441 case tok::pp_warning:
442 Diag(Result, diag::ext_pp_warning_directive);
443 return HandleUserDiagnosticDirective(Result, true);
444 case tok::pp_ident:
445 return HandleIdentSCCSDirective(Result);
446 case tok::pp_sccs:
447 return HandleIdentSCCSDirective(Result);
448 case tok::pp_assert:
449 //isExtension = true; // FIXME: implement #assert
450 break;
451 case tok::pp_unassert:
452 //isExtension = true; // FIXME: implement #unassert
453 break;
454 }
455 break;
456 }
457
458 // If we reached here, the preprocessing token is not valid!
459 Diag(Result, diag::err_pp_invalid_directive);
460
461 // Read the rest of the PP line.
462 DiscardUntilEndOfDirective();
463
464 // Okay, we're done parsing the directive.
465}
466
467void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
468 bool isWarning) {
469 // Read the rest of the line raw. We do this because we don't want macros
470 // to be expanded and we don't require that the tokens be valid preprocessing
471 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
472 // collapse multiple consequtive white space between tokens, but this isn't
473 // specified by the standard.
474 std::string Message = CurLexer->ReadToEndOfLine();
475
476 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
477 return Diag(Tok, DiagID, Message);
478}
479
480/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
481///
482void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
483 // Yes, this directive is an extension.
484 Diag(Tok, diag::ext_pp_ident_directive);
485
486 // Read the string argument.
487 Token StrTok;
488 Lex(StrTok);
489
490 // If the token kind isn't a string, it's a malformed directive.
491 if (StrTok.isNot(tok::string_literal) &&
492 StrTok.isNot(tok::wide_string_literal))
493 return Diag(StrTok, diag::err_pp_malformed_ident);
494
495 // Verify that there is nothing after the string, other than EOM.
496 CheckEndOfDirective("#ident");
497
498 if (Callbacks)
499 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
500}
501
502//===----------------------------------------------------------------------===//
503// Preprocessor Include Directive Handling.
504//===----------------------------------------------------------------------===//
505
506/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
507/// checked and spelled filename, e.g. as an operand of #include. This returns
508/// true if the input filename was in <>'s or false if it were in ""'s. The
509/// caller is expected to provide a buffer that is large enough to hold the
510/// spelling of the filename, but is also expected to handle the case when
511/// this method decides to use a different buffer.
512bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
513 const char *&BufStart,
514 const char *&BufEnd) {
515 // Get the text form of the filename.
516 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
517
518 // Make sure the filename is <x> or "x".
519 bool isAngled;
520 if (BufStart[0] == '<') {
521 if (BufEnd[-1] != '>') {
522 Diag(Loc, diag::err_pp_expects_filename);
523 BufStart = 0;
524 return true;
525 }
526 isAngled = true;
527 } else if (BufStart[0] == '"') {
528 if (BufEnd[-1] != '"') {
529 Diag(Loc, diag::err_pp_expects_filename);
530 BufStart = 0;
531 return true;
532 }
533 isAngled = false;
534 } else {
535 Diag(Loc, diag::err_pp_expects_filename);
536 BufStart = 0;
537 return true;
538 }
539
540 // Diagnose #include "" as invalid.
541 if (BufEnd-BufStart <= 2) {
542 Diag(Loc, diag::err_pp_empty_filename);
543 BufStart = 0;
544 return "";
545 }
546
547 // Skip the brackets.
548 ++BufStart;
549 --BufEnd;
550 return isAngled;
551}
552
553/// ConcatenateIncludeName - Handle cases where the #include name is expanded
554/// from a macro as multiple tokens, which need to be glued together. This
555/// occurs for code like:
556/// #define FOO <a/b.h>
557/// #include FOO
558/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
559///
560/// This code concatenates and consumes tokens up to the '>' token. It returns
561/// false if the > was found, otherwise it returns true if it finds and consumes
562/// the EOM marker.
563static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
564 Preprocessor &PP) {
565 Token CurTok;
566
567 PP.Lex(CurTok);
568 while (CurTok.isNot(tok::eom)) {
569 // Append the spelling of this token to the buffer. If there was a space
570 // before it, add it now.
571 if (CurTok.hasLeadingSpace())
572 FilenameBuffer.push_back(' ');
573
574 // Get the spelling of the token, directly into FilenameBuffer if possible.
575 unsigned PreAppendSize = FilenameBuffer.size();
576 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
577
578 const char *BufPtr = &FilenameBuffer[PreAppendSize];
579 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
580
581 // If the token was spelled somewhere else, copy it into FilenameBuffer.
582 if (BufPtr != &FilenameBuffer[PreAppendSize])
583 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
584
585 // Resize FilenameBuffer to the correct size.
586 if (CurTok.getLength() != ActualLen)
587 FilenameBuffer.resize(PreAppendSize+ActualLen);
588
589 // If we found the '>' marker, return success.
590 if (CurTok.is(tok::greater))
591 return false;
592
593 PP.Lex(CurTok);
594 }
595
596 // If we hit the eom marker, emit an error and return true so that the caller
597 // knows the EOM has been read.
598 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
599 return true;
600}
601
602/// HandleIncludeDirective - The "#include" tokens have just been read, read the
603/// file to be included from the lexer, then include it! This is a common
604/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +0000605/// #import. LookupFrom is set when this is a #include_next directive, it
606/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +0000607void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
608 const DirectoryLookup *LookupFrom,
609 bool isImport) {
610
611 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +0000612 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000613
614 // Reserve a buffer to get the spelling.
615 llvm::SmallVector<char, 128> FilenameBuffer;
616 const char *FilenameStart, *FilenameEnd;
617
618 switch (FilenameTok.getKind()) {
619 case tok::eom:
620 // If the token kind is EOM, the error has already been diagnosed.
621 return;
622
623 case tok::angle_string_literal:
624 case tok::string_literal: {
625 FilenameBuffer.resize(FilenameTok.getLength());
626 FilenameStart = &FilenameBuffer[0];
627 unsigned Len = getSpelling(FilenameTok, FilenameStart);
628 FilenameEnd = FilenameStart+Len;
629 break;
630 }
631
632 case tok::less:
633 // This could be a <foo/bar.h> file coming from a macro expansion. In this
634 // case, glue the tokens together into FilenameBuffer and interpret those.
635 FilenameBuffer.push_back('<');
636 if (ConcatenateIncludeName(FilenameBuffer, *this))
637 return; // Found <eom> but no ">"? Diagnostic already emitted.
638 FilenameStart = &FilenameBuffer[0];
639 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
640 break;
641 default:
642 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
643 DiscardUntilEndOfDirective();
644 return;
645 }
646
647 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
648 FilenameStart, FilenameEnd);
649 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
650 // error.
651 if (FilenameStart == 0) {
652 DiscardUntilEndOfDirective();
653 return;
654 }
655
656 // Verify that there is nothing after the filename, other than EOM. Use the
657 // preprocessor to lex this in case lexing the filename entered a macro.
658 CheckEndOfDirective("#include");
659
660 // Check that we don't have infinite #include recursion.
661 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
662 return Diag(FilenameTok, diag::err_pp_include_too_deep);
663
664 // Search include directories.
665 const DirectoryLookup *CurDir;
666 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
667 isAngled, LookupFrom, CurDir);
668 if (File == 0)
669 return Diag(FilenameTok, diag::err_pp_file_not_found,
670 std::string(FilenameStart, FilenameEnd));
671
Chris Lattner72181832008-09-26 20:12:23 +0000672 // Ask HeaderInfo if we should enter this #include file. If not, #including
673 // this file will have no effect.
674 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +0000675 return;
Chris Lattner72181832008-09-26 20:12:23 +0000676
677 // The #included file will be considered to be a system header if either it is
678 // in a system include directory, or if the #includer is a system include
679 // header.
Chris Lattner9d728512008-10-27 01:19:25 +0000680 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000681 std::max(HeaderInfo.getFileDirFlavor(File),
682 SourceMgr.getFileCharacteristic(getCurrentFileLexer()->getFileLoc()));
Chris Lattner72181832008-09-26 20:12:23 +0000683
Chris Lattner141e71f2008-03-09 01:54:53 +0000684 // Look up the file, create a File ID for it.
Nico Weber7bfaaae2008-08-10 19:59:06 +0000685 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
Chris Lattner72181832008-09-26 20:12:23 +0000686 FileCharacter);
Chris Lattner141e71f2008-03-09 01:54:53 +0000687 if (FileID == 0)
688 return Diag(FilenameTok, diag::err_pp_file_not_found,
689 std::string(FilenameStart, FilenameEnd));
690
691 // Finally, if all is good, enter the new file!
692 EnterSourceFile(FileID, CurDir);
693}
694
695/// HandleIncludeNextDirective - Implements #include_next.
696///
697void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
698 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
699
700 // #include_next is like #include, except that we start searching after
701 // the current found directory. If we can't do this, issue a
702 // diagnostic.
703 const DirectoryLookup *Lookup = CurDirLookup;
704 if (isInPrimaryFile()) {
705 Lookup = 0;
706 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
707 } else if (Lookup == 0) {
708 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
709 } else {
710 // Start looking up in the next directory.
711 ++Lookup;
712 }
713
714 return HandleIncludeDirective(IncludeNextTok, Lookup);
715}
716
717/// HandleImportDirective - Implements #import.
718///
719void Preprocessor::HandleImportDirective(Token &ImportTok) {
720 Diag(ImportTok, diag::ext_pp_import_directive);
721
722 return HandleIncludeDirective(ImportTok, 0, true);
723}
724
725//===----------------------------------------------------------------------===//
726// Preprocessor Macro Directive Handling.
727//===----------------------------------------------------------------------===//
728
729/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
730/// definition has just been read. Lex the rest of the arguments and the
731/// closing ), updating MI with what we learn. Return true if an error occurs
732/// parsing the arg list.
733bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
734 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
735
736 Token Tok;
737 while (1) {
738 LexUnexpandedToken(Tok);
739 switch (Tok.getKind()) {
740 case tok::r_paren:
741 // Found the end of the argument list.
742 if (Arguments.empty()) { // #define FOO()
743 MI->setArgumentList(Arguments.begin(), Arguments.end());
744 return false;
745 }
746 // Otherwise we have #define FOO(A,)
747 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
748 return true;
749 case tok::ellipsis: // #define X(... -> C99 varargs
750 // Warn if use of C99 feature in non-C99 mode.
751 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
752
753 // Lex the token after the identifier.
754 LexUnexpandedToken(Tok);
755 if (Tok.isNot(tok::r_paren)) {
756 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
757 return true;
758 }
759 // Add the __VA_ARGS__ identifier as an argument.
760 Arguments.push_back(Ident__VA_ARGS__);
761 MI->setIsC99Varargs();
762 MI->setArgumentList(Arguments.begin(), Arguments.end());
763 return false;
764 case tok::eom: // #define X(
765 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
766 return true;
767 default:
768 // Handle keywords and identifiers here to accept things like
769 // #define Foo(for) for.
770 IdentifierInfo *II = Tok.getIdentifierInfo();
771 if (II == 0) {
772 // #define X(1
773 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
774 return true;
775 }
776
777 // If this is already used as an argument, it is used multiple times (e.g.
778 // #define X(A,A.
779 if (std::find(Arguments.begin(), Arguments.end(), II) !=
780 Arguments.end()) { // C99 6.10.3p6
781 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
782 return true;
783 }
784
785 // Add the argument to the macro info.
786 Arguments.push_back(II);
787
788 // Lex the token after the identifier.
789 LexUnexpandedToken(Tok);
790
791 switch (Tok.getKind()) {
792 default: // #define X(A B
793 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
794 return true;
795 case tok::r_paren: // #define X(A)
796 MI->setArgumentList(Arguments.begin(), Arguments.end());
797 return false;
798 case tok::comma: // #define X(A,
799 break;
800 case tok::ellipsis: // #define X(A... -> GCC extension
801 // Diagnose extension.
802 Diag(Tok, diag::ext_named_variadic_macro);
803
804 // Lex the token after the identifier.
805 LexUnexpandedToken(Tok);
806 if (Tok.isNot(tok::r_paren)) {
807 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
808 return true;
809 }
810
811 MI->setIsGNUVarargs();
812 MI->setArgumentList(Arguments.begin(), Arguments.end());
813 return false;
814 }
815 }
816 }
817}
818
819/// HandleDefineDirective - Implements #define. This consumes the entire macro
820/// line then lets the caller lex the next real token.
821void Preprocessor::HandleDefineDirective(Token &DefineTok) {
822 ++NumDefined;
823
824 Token MacroNameTok;
825 ReadMacroName(MacroNameTok, 1);
826
827 // Error reading macro name? If so, diagnostic already issued.
828 if (MacroNameTok.is(tok::eom))
829 return;
830
831 // If we are supposed to keep comments in #defines, reenable comment saving
832 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000833 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000834
835 // Create the new macro.
836 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
837
838 Token Tok;
839 LexUnexpandedToken(Tok);
840
841 // If this is a function-like macro definition, parse the argument list,
842 // marking each of the identifiers as being used as macro arguments. Also,
843 // check other constraints on the first token of the macro body.
844 if (Tok.is(tok::eom)) {
845 // If there is no body to this macro, we have no special handling here.
846 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
847 // This is a function-like macro definition. Read the argument list.
848 MI->setIsFunctionLike();
849 if (ReadMacroDefinitionArgList(MI)) {
850 // Forget about MI.
851 delete MI;
852 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000853 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +0000854 DiscardUntilEndOfDirective();
855 return;
856 }
857
858 // Read the first token after the arg list for down below.
859 LexUnexpandedToken(Tok);
860 } else if (!Tok.hasLeadingSpace()) {
861 // C99 requires whitespace between the macro definition and the body. Emit
862 // a diagnostic for something like "#define X+".
863 if (Features.C99) {
864 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
865 } else {
866 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
867 // one in some cases!
868 }
869 } else {
870 // This is a normal token with leading space. Clear the leading space
871 // marker on the first token to get proper expansion.
872 Tok.clearFlag(Token::LeadingSpace);
873 }
874
875 // If this is a definition of a variadic C99 function-like macro, not using
876 // the GNU named varargs extension, enabled __VA_ARGS__.
877
878 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
879 // This gets unpoisoned where it is allowed.
880 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
881 if (MI->isC99Varargs())
882 Ident__VA_ARGS__->setIsPoisoned(false);
883
884 // Read the rest of the macro body.
885 if (MI->isObjectLike()) {
886 // Object-like macros are very simple, just read their body.
887 while (Tok.isNot(tok::eom)) {
888 MI->AddTokenToBody(Tok);
889 // Get the next token of the macro.
890 LexUnexpandedToken(Tok);
891 }
892
893 } else {
894 // Otherwise, read the body of a function-like macro. This has to validate
895 // the # (stringize) operator.
896 while (Tok.isNot(tok::eom)) {
897 MI->AddTokenToBody(Tok);
898
899 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
900 // parameters in function-like macro expansions.
901 if (Tok.isNot(tok::hash)) {
902 // Get the next token of the macro.
903 LexUnexpandedToken(Tok);
904 continue;
905 }
906
907 // Get the next token of the macro.
908 LexUnexpandedToken(Tok);
909
910 // Not a macro arg identifier?
911 if (!Tok.getIdentifierInfo() ||
912 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
913 Diag(Tok, diag::err_pp_stringize_not_parameter);
914 delete MI;
915
916 // Disable __VA_ARGS__ again.
917 Ident__VA_ARGS__->setIsPoisoned(true);
918 return;
919 }
920
921 // Things look ok, add the param name token to the macro.
922 MI->AddTokenToBody(Tok);
923
924 // Get the next token of the macro.
925 LexUnexpandedToken(Tok);
926 }
927 }
928
929
930 // Disable __VA_ARGS__ again.
931 Ident__VA_ARGS__->setIsPoisoned(true);
932
933 // Check that there is no paste (##) operator at the begining or end of the
934 // replacement list.
935 unsigned NumTokens = MI->getNumTokens();
936 if (NumTokens != 0) {
937 if (MI->getReplacementToken(0).is(tok::hashhash)) {
938 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
939 delete MI;
940 return;
941 }
942 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
943 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
944 delete MI;
945 return;
946 }
947 }
948
949 // If this is the primary source file, remember that this macro hasn't been
950 // used yet.
951 if (isInPrimaryFile())
952 MI->setIsUsed(false);
953
954 // Finally, if this identifier already had a macro defined for it, verify that
955 // the macro bodies are identical and free the old definition.
956 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
957 if (!OtherMI->isUsed())
958 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
959
960 // Macros must be identical. This means all tokes and whitespace separation
961 // must be the same. C99 6.10.3.2.
962 if (!MI->isIdenticalTo(*OtherMI, *this)) {
963 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
964 MacroNameTok.getIdentifierInfo()->getName());
965 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
966 }
967 delete OtherMI;
968 }
969
970 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
971}
972
973/// HandleUndefDirective - Implements #undef.
974///
975void Preprocessor::HandleUndefDirective(Token &UndefTok) {
976 ++NumUndefined;
977
978 Token MacroNameTok;
979 ReadMacroName(MacroNameTok, 2);
980
981 // Error reading macro name? If so, diagnostic already issued.
982 if (MacroNameTok.is(tok::eom))
983 return;
984
985 // Check to see if this is the last token on the #undef line.
986 CheckEndOfDirective("#undef");
987
988 // Okay, we finally have a valid identifier to undef.
989 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
990
991 // If the macro is not defined, this is a noop undef, just return.
992 if (MI == 0) return;
993
994 if (!MI->isUsed())
995 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
996
997 // Free macro definition.
998 delete MI;
999 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1000}
1001
1002
1003//===----------------------------------------------------------------------===//
1004// Preprocessor Conditional Directive Handling.
1005//===----------------------------------------------------------------------===//
1006
1007/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1008/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1009/// if any tokens have been returned or pp-directives activated before this
1010/// #ifndef has been lexed.
1011///
1012void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1013 bool ReadAnyTokensBeforeDirective) {
1014 ++NumIf;
1015 Token DirectiveTok = Result;
1016
1017 Token MacroNameTok;
1018 ReadMacroName(MacroNameTok);
1019
1020 // Error reading macro name? If so, diagnostic already issued.
1021 if (MacroNameTok.is(tok::eom)) {
1022 // Skip code until we get to #endif. This helps with recovery by not
1023 // emitting an error when the #endif is reached.
1024 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1025 /*Foundnonskip*/false, /*FoundElse*/false);
1026 return;
1027 }
1028
1029 // Check to see if this is the last token on the #if[n]def line.
1030 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1031
Ted Kremenek60e45d42008-11-18 00:34:22 +00001032 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001033 // If the start of a top-level #ifdef, inform MIOpt.
1034 if (!ReadAnyTokensBeforeDirective) {
1035 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001036 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001037 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001038 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001039 }
1040
1041 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1042 MacroInfo *MI = getMacroInfo(MII);
1043
1044 // If there is a macro, process it.
1045 if (MI) // Mark it used.
1046 MI->setIsUsed(true);
1047
1048 // Should we include the stuff contained by this directive?
1049 if (!MI == isIfndef) {
1050 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001051 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001052 /*foundnonskip*/true, /*foundelse*/false);
1053 } else {
1054 // No, skip the contents of this block and return the first token after it.
1055 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1056 /*Foundnonskip*/false,
1057 /*FoundElse*/false);
1058 }
1059}
1060
1061/// HandleIfDirective - Implements the #if directive.
1062///
1063void Preprocessor::HandleIfDirective(Token &IfToken,
1064 bool ReadAnyTokensBeforeDirective) {
1065 ++NumIf;
1066
1067 // Parse and evaluation the conditional expression.
1068 IdentifierInfo *IfNDefMacro = 0;
1069 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1070
Nuno Lopes0049db62008-06-01 18:31:24 +00001071
1072 // If this condition is equivalent to #ifndef X, and if this is the first
1073 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001074 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001075 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001076 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001077 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001078 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001079 }
1080
Chris Lattner141e71f2008-03-09 01:54:53 +00001081 // Should we include the stuff contained by this directive?
1082 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001083 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001084 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001085 /*foundnonskip*/true, /*foundelse*/false);
1086 } else {
1087 // No, skip the contents of this block and return the first token after it.
1088 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1089 /*FoundElse*/false);
1090 }
1091}
1092
1093/// HandleEndifDirective - Implements the #endif directive.
1094///
1095void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1096 ++NumEndif;
1097
1098 // Check that this is the whole directive.
1099 CheckEndOfDirective("#endif");
1100
1101 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001102 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001103 // No conditionals on the stack: this is an #endif without an #if.
1104 return Diag(EndifToken, diag::err_pp_endif_without_if);
1105 }
1106
1107 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001108 if (CurPPLexer->getConditionalStackDepth() == 0)
1109 CurPPLexer->MIOpt.ExitTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001110
Ted Kremenek60e45d42008-11-18 00:34:22 +00001111 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001112 "This code should only be reachable in the non-skipping case!");
1113}
1114
1115
1116void Preprocessor::HandleElseDirective(Token &Result) {
1117 ++NumElse;
1118
1119 // #else directive in a non-skipping conditional... start skipping.
1120 CheckEndOfDirective("#else");
1121
1122 PPConditionalInfo CI;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001123 if (CurPPLexer->popConditionalLevel(CI))
Chris Lattner141e71f2008-03-09 01:54:53 +00001124 return Diag(Result, diag::pp_err_else_without_if);
1125
1126 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001127 if (CurPPLexer->getConditionalStackDepth() == 0)
1128 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001129
1130 // If this is a #else with a #else before it, report the error.
1131 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1132
1133 // Finally, skip the rest of the contents of this block and return the first
1134 // token after it.
1135 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1136 /*FoundElse*/true);
1137}
1138
1139void Preprocessor::HandleElifDirective(Token &ElifToken) {
1140 ++NumElse;
1141
1142 // #elif directive in a non-skipping conditional... start skipping.
1143 // We don't care what the condition is, because we will always skip it (since
1144 // the block immediately before it was included).
1145 DiscardUntilEndOfDirective();
1146
1147 PPConditionalInfo CI;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001148 if (CurPPLexer->popConditionalLevel(CI))
Chris Lattner141e71f2008-03-09 01:54:53 +00001149 return Diag(ElifToken, diag::pp_err_elif_without_if);
1150
1151 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001152 if (CurPPLexer->getConditionalStackDepth() == 0)
1153 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001154
1155 // If this is a #elif with a #else before it, report the error.
1156 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1157
1158 // Finally, skip the rest of the contents of this block and return the first
1159 // token after it.
1160 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1161 /*FoundElse*/CI.FoundElse);
1162}
1163