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