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