blob: 300ec0bb7564a0532bffb58d96515eeaa6cabc3d [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.
Chris Lattner56b05c82008-11-18 08:02:48 +000062 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000063 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)) {
Chris Lattner56b05c82008-11-18 08:02:48 +0000101 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType;
Chris Lattner141e71f2008-03-09 01:54:53 +0000102 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
Ted Kremenek268ee702008-12-12 18:34:08 +0000125 if (CurPTHLexer) {
126 PTHSkipExcludedConditionalBlock();
127 return;
128 }
129
Chris Lattner141e71f2008-03-09 01:54:53 +0000130 // Enter raw mode to disable identifier lookup (and thus macro expansion),
131 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000132 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000133 Token Tok;
134 while (1) {
Ted Kremenekf6452c52008-11-18 01:04:47 +0000135 if (CurLexer)
136 CurLexer->Lex(Tok);
137 else
138 CurPTHLexer->Lex(Tok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000139
140 // If this is the end of the buffer, we have an error.
141 if (Tok.is(tok::eof)) {
142 // Emit errors for each unterminated conditional on the stack, including
143 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000144 while (!CurPPLexer->ConditionalStack.empty()) {
145 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000146 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000147 CurPPLexer->ConditionalStack.pop_back();
Chris Lattner141e71f2008-03-09 01:54:53 +0000148 }
149
150 // Just return and let the caller lex after this #include.
151 break;
152 }
153
154 // If this token is not a preprocessor directive, just skip it.
155 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
156 continue;
157
158 // We just parsed a # character at the start of a line, so we're in
159 // directive mode. Tell the lexer this so any newlines we see will be
160 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000161 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000162 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000163
164
165 // Read the next token, the directive flavor.
166 LexUnexpandedToken(Tok);
167
168 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
169 // something bogus), skip it.
170 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000171 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000172 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000173 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000174 continue;
175 }
176
177 // If the first letter isn't i or e, it isn't intesting to us. We know that
178 // this is safe in the face of spelling differences, because there is no way
179 // to spell an i/e in a strange way that is another letter. Skipping this
180 // allows us to avoid looking up the identifier info for #define/#undef and
181 // other common directives.
182 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
183 char FirstChar = RawCharData[0];
184 if (FirstChar >= 'a' && FirstChar <= 'z' &&
185 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000186 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000187 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000188 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000189 continue;
190 }
191
192 // Get the identifier name without trigraphs or embedded newlines. Note
193 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
194 // when skipping.
195 // TODO: could do this with zero copies in the no-clean case by using
196 // strncmp below.
197 char Directive[20];
198 unsigned IdLen;
199 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
200 IdLen = Tok.getLength();
201 memcpy(Directive, RawCharData, IdLen);
202 Directive[IdLen] = 0;
203 } else {
204 std::string DirectiveStr = getSpelling(Tok);
205 IdLen = DirectiveStr.size();
206 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000207 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000208 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000209 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000210 continue;
211 }
212 memcpy(Directive, &DirectiveStr[0], IdLen);
213 Directive[IdLen] = 0;
214 }
215
216 if (FirstChar == 'i' && Directive[1] == 'f') {
217 if ((IdLen == 2) || // "if"
218 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
219 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
220 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
221 // bother parsing the condition.
222 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000223 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000224 /*foundnonskip*/false,
225 /*fnddelse*/false);
226 }
227 } else if (FirstChar == 'e') {
228 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
229 CheckEndOfDirective("#endif");
230 PPConditionalInfo CondInfo;
231 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000232 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000233 InCond = InCond; // Silence warning in no-asserts mode.
234 assert(!InCond && "Can't be skipping if not in a conditional!");
235
236 // If we popped the outermost skipping block, we're done skipping!
237 if (!CondInfo.WasSkipping)
238 break;
239 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
240 // #else directive in a skipping conditional. If not in some other
241 // skipping conditional, and if #else hasn't already been seen, enter it
242 // as a non-skipping conditional.
243 CheckEndOfDirective("#else");
Ted Kremenek60e45d42008-11-18 00:34:22 +0000244 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000245
246 // If this is a #else with a #else before it, report the error.
247 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
248
249 // Note that we've seen a #else in this conditional.
250 CondInfo.FoundElse = true;
251
252 // If the conditional is at the top level, and the #if block wasn't
253 // entered, enter the #else block now.
254 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
255 CondInfo.FoundNonSkip = true;
256 break;
257 }
258 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000259 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000260
261 bool ShouldEnter;
262 // If this is in a skipping block or if we're already handled this #if
263 // block, don't bother parsing the condition.
264 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
265 DiscardUntilEndOfDirective();
266 ShouldEnter = false;
267 } else {
268 // Restore the value of LexingRawMode so that identifiers are
269 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000270 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
271 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000272 IdentifierInfo *IfNDefMacro = 0;
273 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000274 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000275 }
276
277 // If this is a #elif with a #else before it, report the error.
278 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
279
280 // If this condition is true, enter it!
281 if (ShouldEnter) {
282 CondInfo.FoundNonSkip = true;
283 break;
284 }
285 }
286 }
287
Ted Kremenek60e45d42008-11-18 00:34:22 +0000288 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000289 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000290 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000291 }
292
293 // Finally, if we are out of the conditional (saw an #endif or ran off the end
294 // of the file, just stop skipping and return to lexing whatever came after
295 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000296 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000297}
298
Ted Kremenek268ee702008-12-12 18:34:08 +0000299void Preprocessor::PTHSkipExcludedConditionalBlock() {
300
301 while(1) {
302 assert(CurPTHLexer);
303 assert(CurPTHLexer->LexingRawMode == false);
304
305 // Skip to the next '#else', '#elif', or #endif.
306 if (CurPTHLexer->SkipBlock()) {
307 // We have reached an #endif. Both the '#' and 'endif' tokens
308 // have been consumed by the PTHLexer. Just pop off the condition level.
309 PPConditionalInfo CondInfo;
310 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
311 InCond = InCond; // Silence warning in no-asserts mode.
312 assert(!InCond && "Can't be skipping if not in a conditional!");
313 break;
314 }
315
316 // We have reached a '#else' or '#elif'. Lex the next token to get
317 // the directive flavor.
318 Token Tok;
319 LexUnexpandedToken(Tok);
320
321 // We can actually look up the IdentifierInfo here since we aren't in
322 // raw mode.
323 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
324
325 if (K == tok::pp_else) {
326 // #else: Enter the else condition. We aren't in a nested condition
327 // since we skip those. We're always in the one matching the last
328 // blocked we skipped.
329 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
330 // Note that we've seen a #else in this conditional.
331 CondInfo.FoundElse = true;
332
333 // If the #if block wasn't entered then enter the #else block now.
334 if (!CondInfo.FoundNonSkip) {
335 CondInfo.FoundNonSkip = true;
336 break;
337 }
338
339 // Otherwise skip this block.
340 continue;
341 }
342
343 assert(K == tok::pp_elif);
344 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
345
346 // If this is a #elif with a #else before it, report the error.
347 if (CondInfo.FoundElse)
348 Diag(Tok, diag::pp_err_elif_after_else);
349
350 // If this is in a skipping block or if we're already handled this #if
351 // block, don't bother parsing the condition. We just skip this block.
352 if (CondInfo.FoundNonSkip)
353 continue;
354
355 // Evaluate the condition of the #elif.
356 IdentifierInfo *IfNDefMacro = 0;
357 CurPTHLexer->ParsingPreprocessorDirective = true;
358 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
359 CurPTHLexer->ParsingPreprocessorDirective = false;
360
361 // If this condition is true, enter it!
362 if (ShouldEnter) {
363 CondInfo.FoundNonSkip = true;
364 break;
365 }
366
367 // Otherwise, skip this block and go to the next one.
368 continue;
369 }
370}
371
Chris Lattner10725092008-03-09 04:17:44 +0000372/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
373/// return null on failure. isAngled indicates whether the file reference is
374/// for system #include's or not (i.e. using <> instead of "").
375const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
376 const char *FilenameEnd,
377 bool isAngled,
378 const DirectoryLookup *FromDir,
379 const DirectoryLookup *&CurDir) {
380 // If the header lookup mechanism may be relative to the current file, pass in
381 // info about where the current file is.
382 const FileEntry *CurFileEnt = 0;
383 if (!FromDir) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000384 unsigned FileID = getCurrentFileLexer()->getFileID();
385 CurFileEnt = SourceMgr.getFileEntryForID(FileID);
Chris Lattner10725092008-03-09 04:17:44 +0000386 }
387
388 // Do a standard file entry lookup.
389 CurDir = CurDirLookup;
390 const FileEntry *FE =
391 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
392 isAngled, FromDir, CurDir, CurFileEnt);
393 if (FE) return FE;
394
395 // Otherwise, see if this is a subframework header. If so, this is relative
396 // to one of the headers on the #include stack. Walk the list of the current
397 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000398 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000399 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000400 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
401 CurFileEnt)))
402 return FE;
403 }
404
405 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
406 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000407 if (IsFileLexer(ISEntry)) {
Chris Lattner10725092008-03-09 04:17:44 +0000408 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000409 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000410 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
411 FilenameEnd, CurFileEnt)))
412 return FE;
413 }
414 }
415
416 // Otherwise, we really couldn't find the file.
417 return 0;
418}
419
Chris Lattner141e71f2008-03-09 01:54:53 +0000420
421//===----------------------------------------------------------------------===//
422// Preprocessor Directive Handling.
423//===----------------------------------------------------------------------===//
424
425/// HandleDirective - This callback is invoked when the lexer sees a # token
426/// at the start of a line. This consumes the directive, modifies the
427/// lexer/preprocessor state, and advances the lexer(s) so that the next token
428/// read is the correct one.
429void Preprocessor::HandleDirective(Token &Result) {
430 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
431
432 // We just parsed a # character at the start of a line, so we're in directive
433 // mode. Tell the lexer this so any newlines we see will be converted into an
434 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000435 CurPPLexer->ParsingPreprocessorDirective = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000436
437 ++NumDirectives;
438
439 // We are about to read a token. For the multiple-include optimization FA to
440 // work, we have to remember if we had read any tokens *before* this
441 // pp-directive.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000442 bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Chris Lattner141e71f2008-03-09 01:54:53 +0000443
444 // Read the next token, the directive flavor. This isn't expanded due to
445 // C99 6.10.3p8.
446 LexUnexpandedToken(Result);
447
448 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
449 // #define A(x) #x
450 // A(abc
451 // #warning blah
452 // def)
453 // If so, the user is relying on non-portable behavior, emit a diagnostic.
454 if (InMacroArgs)
455 Diag(Result, diag::ext_embedded_directive);
456
457TryAgain:
458 switch (Result.getKind()) {
459 case tok::eom:
460 return; // null directive.
461 case tok::comment:
462 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
463 LexUnexpandedToken(Result);
464 goto TryAgain;
465
466 case tok::numeric_constant:
467 // FIXME: implement # 7 line numbers!
468 DiscardUntilEndOfDirective();
469 return;
470 default:
471 IdentifierInfo *II = Result.getIdentifierInfo();
472 if (II == 0) break; // Not an identifier.
473
474 // Ask what the preprocessor keyword ID is.
475 switch (II->getPPKeywordID()) {
476 default: break;
477 // C99 6.10.1 - Conditional Inclusion.
478 case tok::pp_if:
479 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
480 case tok::pp_ifdef:
481 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
482 case tok::pp_ifndef:
483 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
484 case tok::pp_elif:
485 return HandleElifDirective(Result);
486 case tok::pp_else:
487 return HandleElseDirective(Result);
488 case tok::pp_endif:
489 return HandleEndifDirective(Result);
490
491 // C99 6.10.2 - Source File Inclusion.
492 case tok::pp_include:
493 return HandleIncludeDirective(Result); // Handle #include.
494
495 // C99 6.10.3 - Macro Replacement.
496 case tok::pp_define:
497 return HandleDefineDirective(Result);
498 case tok::pp_undef:
499 return HandleUndefDirective(Result);
500
501 // C99 6.10.4 - Line Control.
502 case tok::pp_line:
503 // FIXME: implement #line
504 DiscardUntilEndOfDirective();
505 return;
506
507 // C99 6.10.5 - Error Directive.
508 case tok::pp_error:
509 return HandleUserDiagnosticDirective(Result, false);
510
511 // C99 6.10.6 - Pragma Directive.
512 case tok::pp_pragma:
513 return HandlePragmaDirective();
514
515 // GNU Extensions.
516 case tok::pp_import:
517 return HandleImportDirective(Result);
518 case tok::pp_include_next:
519 return HandleIncludeNextDirective(Result);
520
521 case tok::pp_warning:
522 Diag(Result, diag::ext_pp_warning_directive);
523 return HandleUserDiagnosticDirective(Result, true);
524 case tok::pp_ident:
525 return HandleIdentSCCSDirective(Result);
526 case tok::pp_sccs:
527 return HandleIdentSCCSDirective(Result);
528 case tok::pp_assert:
529 //isExtension = true; // FIXME: implement #assert
530 break;
531 case tok::pp_unassert:
532 //isExtension = true; // FIXME: implement #unassert
533 break;
534 }
535 break;
536 }
537
538 // If we reached here, the preprocessing token is not valid!
539 Diag(Result, diag::err_pp_invalid_directive);
540
541 // Read the rest of the PP line.
542 DiscardUntilEndOfDirective();
543
544 // Okay, we're done parsing the directive.
545}
546
547void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
548 bool isWarning) {
549 // Read the rest of the line raw. We do this because we don't want macros
550 // to be expanded and we don't require that the tokens be valid preprocessing
551 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
552 // collapse multiple consequtive white space between tokens, but this isn't
553 // specified by the standard.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000554
555 if (CurLexer) {
556 std::string Message = CurLexer->ReadToEndOfLine();
557 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
558 Diag(Tok, DiagID) << Message;
559 }
560 else {
561 CurPTHLexer->DiscardToEndOfLine();
562 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000563}
564
565/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
566///
567void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
568 // Yes, this directive is an extension.
569 Diag(Tok, diag::ext_pp_ident_directive);
570
571 // Read the string argument.
572 Token StrTok;
573 Lex(StrTok);
574
575 // If the token kind isn't a string, it's a malformed directive.
576 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000577 StrTok.isNot(tok::wide_string_literal)) {
578 Diag(StrTok, diag::err_pp_malformed_ident);
579 return;
580 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000581
582 // Verify that there is nothing after the string, other than EOM.
583 CheckEndOfDirective("#ident");
584
585 if (Callbacks)
586 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
587}
588
589//===----------------------------------------------------------------------===//
590// Preprocessor Include Directive Handling.
591//===----------------------------------------------------------------------===//
592
593/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
594/// checked and spelled filename, e.g. as an operand of #include. This returns
595/// true if the input filename was in <>'s or false if it were in ""'s. The
596/// caller is expected to provide a buffer that is large enough to hold the
597/// spelling of the filename, but is also expected to handle the case when
598/// this method decides to use a different buffer.
599bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
600 const char *&BufStart,
601 const char *&BufEnd) {
602 // Get the text form of the filename.
603 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
604
605 // Make sure the filename is <x> or "x".
606 bool isAngled;
607 if (BufStart[0] == '<') {
608 if (BufEnd[-1] != '>') {
609 Diag(Loc, diag::err_pp_expects_filename);
610 BufStart = 0;
611 return true;
612 }
613 isAngled = true;
614 } else if (BufStart[0] == '"') {
615 if (BufEnd[-1] != '"') {
616 Diag(Loc, diag::err_pp_expects_filename);
617 BufStart = 0;
618 return true;
619 }
620 isAngled = false;
621 } else {
622 Diag(Loc, diag::err_pp_expects_filename);
623 BufStart = 0;
624 return true;
625 }
626
627 // Diagnose #include "" as invalid.
628 if (BufEnd-BufStart <= 2) {
629 Diag(Loc, diag::err_pp_empty_filename);
630 BufStart = 0;
631 return "";
632 }
633
634 // Skip the brackets.
635 ++BufStart;
636 --BufEnd;
637 return isAngled;
638}
639
640/// ConcatenateIncludeName - Handle cases where the #include name is expanded
641/// from a macro as multiple tokens, which need to be glued together. This
642/// occurs for code like:
643/// #define FOO <a/b.h>
644/// #include FOO
645/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
646///
647/// This code concatenates and consumes tokens up to the '>' token. It returns
648/// false if the > was found, otherwise it returns true if it finds and consumes
649/// the EOM marker.
650static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
651 Preprocessor &PP) {
652 Token CurTok;
653
654 PP.Lex(CurTok);
655 while (CurTok.isNot(tok::eom)) {
656 // Append the spelling of this token to the buffer. If there was a space
657 // before it, add it now.
658 if (CurTok.hasLeadingSpace())
659 FilenameBuffer.push_back(' ');
660
661 // Get the spelling of the token, directly into FilenameBuffer if possible.
662 unsigned PreAppendSize = FilenameBuffer.size();
663 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
664
665 const char *BufPtr = &FilenameBuffer[PreAppendSize];
666 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
667
668 // If the token was spelled somewhere else, copy it into FilenameBuffer.
669 if (BufPtr != &FilenameBuffer[PreAppendSize])
670 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
671
672 // Resize FilenameBuffer to the correct size.
673 if (CurTok.getLength() != ActualLen)
674 FilenameBuffer.resize(PreAppendSize+ActualLen);
675
676 // If we found the '>' marker, return success.
677 if (CurTok.is(tok::greater))
678 return false;
679
680 PP.Lex(CurTok);
681 }
682
683 // If we hit the eom marker, emit an error and return true so that the caller
684 // knows the EOM has been read.
685 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
686 return true;
687}
688
689/// HandleIncludeDirective - The "#include" tokens have just been read, read the
690/// file to be included from the lexer, then include it! This is a common
691/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +0000692/// #import. LookupFrom is set when this is a #include_next directive, it
693/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +0000694void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
695 const DirectoryLookup *LookupFrom,
696 bool isImport) {
697
698 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +0000699 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000700
701 // Reserve a buffer to get the spelling.
702 llvm::SmallVector<char, 128> FilenameBuffer;
703 const char *FilenameStart, *FilenameEnd;
704
705 switch (FilenameTok.getKind()) {
706 case tok::eom:
707 // If the token kind is EOM, the error has already been diagnosed.
708 return;
709
710 case tok::angle_string_literal:
711 case tok::string_literal: {
712 FilenameBuffer.resize(FilenameTok.getLength());
713 FilenameStart = &FilenameBuffer[0];
714 unsigned Len = getSpelling(FilenameTok, FilenameStart);
715 FilenameEnd = FilenameStart+Len;
716 break;
717 }
718
719 case tok::less:
720 // This could be a <foo/bar.h> file coming from a macro expansion. In this
721 // case, glue the tokens together into FilenameBuffer and interpret those.
722 FilenameBuffer.push_back('<');
723 if (ConcatenateIncludeName(FilenameBuffer, *this))
724 return; // Found <eom> but no ">"? Diagnostic already emitted.
725 FilenameStart = &FilenameBuffer[0];
726 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
727 break;
728 default:
729 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
730 DiscardUntilEndOfDirective();
731 return;
732 }
733
734 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
735 FilenameStart, FilenameEnd);
736 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
737 // error.
738 if (FilenameStart == 0) {
739 DiscardUntilEndOfDirective();
740 return;
741 }
742
743 // Verify that there is nothing after the filename, other than EOM. Use the
744 // preprocessor to lex this in case lexing the filename entered a macro.
745 CheckEndOfDirective("#include");
746
747 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +0000748 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
749 Diag(FilenameTok, diag::err_pp_include_too_deep);
750 return;
751 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000752
753 // Search include directories.
754 const DirectoryLookup *CurDir;
755 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
756 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +0000757 if (File == 0) {
758 Diag(FilenameTok, diag::err_pp_file_not_found)
759 << std::string(FilenameStart, FilenameEnd);
760 return;
761 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000762
Chris Lattner72181832008-09-26 20:12:23 +0000763 // Ask HeaderInfo if we should enter this #include file. If not, #including
764 // this file will have no effect.
765 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +0000766 return;
Chris Lattner72181832008-09-26 20:12:23 +0000767
768 // The #included file will be considered to be a system header if either it is
769 // in a system include directory, or if the #includer is a system include
770 // header.
Chris Lattner9d728512008-10-27 01:19:25 +0000771 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000772 std::max(HeaderInfo.getFileDirFlavor(File),
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000773 SourceMgr.getFileCharacteristic(getCurrentFileLexer()->getFileID()));
Chris Lattner72181832008-09-26 20:12:23 +0000774
Chris Lattner141e71f2008-03-09 01:54:53 +0000775 // Look up the file, create a File ID for it.
Nico Weber7bfaaae2008-08-10 19:59:06 +0000776 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
Chris Lattner72181832008-09-26 20:12:23 +0000777 FileCharacter);
Chris Lattner56b05c82008-11-18 08:02:48 +0000778 if (FileID == 0) {
779 Diag(FilenameTok, diag::err_pp_file_not_found)
780 << std::string(FilenameStart, FilenameEnd);
781 return;
782 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000783
784 // Finally, if all is good, enter the new file!
785 EnterSourceFile(FileID, CurDir);
786}
787
788/// HandleIncludeNextDirective - Implements #include_next.
789///
790void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
791 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
792
793 // #include_next is like #include, except that we start searching after
794 // the current found directory. If we can't do this, issue a
795 // diagnostic.
796 const DirectoryLookup *Lookup = CurDirLookup;
797 if (isInPrimaryFile()) {
798 Lookup = 0;
799 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
800 } else if (Lookup == 0) {
801 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
802 } else {
803 // Start looking up in the next directory.
804 ++Lookup;
805 }
806
807 return HandleIncludeDirective(IncludeNextTok, Lookup);
808}
809
810/// HandleImportDirective - Implements #import.
811///
812void Preprocessor::HandleImportDirective(Token &ImportTok) {
813 Diag(ImportTok, diag::ext_pp_import_directive);
814
815 return HandleIncludeDirective(ImportTok, 0, true);
816}
817
818//===----------------------------------------------------------------------===//
819// Preprocessor Macro Directive Handling.
820//===----------------------------------------------------------------------===//
821
822/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
823/// definition has just been read. Lex the rest of the arguments and the
824/// closing ), updating MI with what we learn. Return true if an error occurs
825/// parsing the arg list.
826bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
827 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
828
829 Token Tok;
830 while (1) {
831 LexUnexpandedToken(Tok);
832 switch (Tok.getKind()) {
833 case tok::r_paren:
834 // Found the end of the argument list.
835 if (Arguments.empty()) { // #define FOO()
836 MI->setArgumentList(Arguments.begin(), Arguments.end());
837 return false;
838 }
839 // Otherwise we have #define FOO(A,)
840 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
841 return true;
842 case tok::ellipsis: // #define X(... -> C99 varargs
843 // Warn if use of C99 feature in non-C99 mode.
844 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
845
846 // Lex the token after the identifier.
847 LexUnexpandedToken(Tok);
848 if (Tok.isNot(tok::r_paren)) {
849 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
850 return true;
851 }
852 // Add the __VA_ARGS__ identifier as an argument.
853 Arguments.push_back(Ident__VA_ARGS__);
854 MI->setIsC99Varargs();
855 MI->setArgumentList(Arguments.begin(), Arguments.end());
856 return false;
857 case tok::eom: // #define X(
858 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
859 return true;
860 default:
861 // Handle keywords and identifiers here to accept things like
862 // #define Foo(for) for.
863 IdentifierInfo *II = Tok.getIdentifierInfo();
864 if (II == 0) {
865 // #define X(1
866 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
867 return true;
868 }
869
870 // If this is already used as an argument, it is used multiple times (e.g.
871 // #define X(A,A.
872 if (std::find(Arguments.begin(), Arguments.end(), II) !=
873 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +0000874 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +0000875 return true;
876 }
877
878 // Add the argument to the macro info.
879 Arguments.push_back(II);
880
881 // Lex the token after the identifier.
882 LexUnexpandedToken(Tok);
883
884 switch (Tok.getKind()) {
885 default: // #define X(A B
886 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
887 return true;
888 case tok::r_paren: // #define X(A)
889 MI->setArgumentList(Arguments.begin(), Arguments.end());
890 return false;
891 case tok::comma: // #define X(A,
892 break;
893 case tok::ellipsis: // #define X(A... -> GCC extension
894 // Diagnose extension.
895 Diag(Tok, diag::ext_named_variadic_macro);
896
897 // Lex the token after the identifier.
898 LexUnexpandedToken(Tok);
899 if (Tok.isNot(tok::r_paren)) {
900 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
901 return true;
902 }
903
904 MI->setIsGNUVarargs();
905 MI->setArgumentList(Arguments.begin(), Arguments.end());
906 return false;
907 }
908 }
909 }
910}
911
912/// HandleDefineDirective - Implements #define. This consumes the entire macro
913/// line then lets the caller lex the next real token.
914void Preprocessor::HandleDefineDirective(Token &DefineTok) {
915 ++NumDefined;
916
917 Token MacroNameTok;
918 ReadMacroName(MacroNameTok, 1);
919
920 // Error reading macro name? If so, diagnostic already issued.
921 if (MacroNameTok.is(tok::eom))
922 return;
923
924 // If we are supposed to keep comments in #defines, reenable comment saving
925 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000926 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000927
928 // Create the new macro.
929 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
930
931 Token Tok;
932 LexUnexpandedToken(Tok);
933
934 // If this is a function-like macro definition, parse the argument list,
935 // marking each of the identifiers as being used as macro arguments. Also,
936 // check other constraints on the first token of the macro body.
937 if (Tok.is(tok::eom)) {
938 // If there is no body to this macro, we have no special handling here.
939 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
940 // This is a function-like macro definition. Read the argument list.
941 MI->setIsFunctionLike();
942 if (ReadMacroDefinitionArgList(MI)) {
943 // Forget about MI.
944 delete MI;
945 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000946 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +0000947 DiscardUntilEndOfDirective();
948 return;
949 }
950
951 // Read the first token after the arg list for down below.
952 LexUnexpandedToken(Tok);
953 } else if (!Tok.hasLeadingSpace()) {
954 // C99 requires whitespace between the macro definition and the body. Emit
955 // a diagnostic for something like "#define X+".
956 if (Features.C99) {
957 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
958 } else {
959 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
960 // one in some cases!
961 }
962 } else {
963 // This is a normal token with leading space. Clear the leading space
964 // marker on the first token to get proper expansion.
965 Tok.clearFlag(Token::LeadingSpace);
966 }
967
968 // If this is a definition of a variadic C99 function-like macro, not using
969 // the GNU named varargs extension, enabled __VA_ARGS__.
970
971 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
972 // This gets unpoisoned where it is allowed.
973 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
974 if (MI->isC99Varargs())
975 Ident__VA_ARGS__->setIsPoisoned(false);
976
977 // Read the rest of the macro body.
978 if (MI->isObjectLike()) {
979 // Object-like macros are very simple, just read their body.
980 while (Tok.isNot(tok::eom)) {
981 MI->AddTokenToBody(Tok);
982 // Get the next token of the macro.
983 LexUnexpandedToken(Tok);
984 }
985
986 } else {
987 // Otherwise, read the body of a function-like macro. This has to validate
988 // the # (stringize) operator.
989 while (Tok.isNot(tok::eom)) {
990 MI->AddTokenToBody(Tok);
991
992 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
993 // parameters in function-like macro expansions.
994 if (Tok.isNot(tok::hash)) {
995 // Get the next token of the macro.
996 LexUnexpandedToken(Tok);
997 continue;
998 }
999
1000 // Get the next token of the macro.
1001 LexUnexpandedToken(Tok);
1002
1003 // Not a macro arg identifier?
1004 if (!Tok.getIdentifierInfo() ||
1005 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1006 Diag(Tok, diag::err_pp_stringize_not_parameter);
1007 delete MI;
1008
1009 // Disable __VA_ARGS__ again.
1010 Ident__VA_ARGS__->setIsPoisoned(true);
1011 return;
1012 }
1013
1014 // Things look ok, add the param name token to the macro.
1015 MI->AddTokenToBody(Tok);
1016
1017 // Get the next token of the macro.
1018 LexUnexpandedToken(Tok);
1019 }
1020 }
1021
1022
1023 // Disable __VA_ARGS__ again.
1024 Ident__VA_ARGS__->setIsPoisoned(true);
1025
1026 // Check that there is no paste (##) operator at the begining or end of the
1027 // replacement list.
1028 unsigned NumTokens = MI->getNumTokens();
1029 if (NumTokens != 0) {
1030 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1031 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
1032 delete MI;
1033 return;
1034 }
1035 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1036 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
1037 delete MI;
1038 return;
1039 }
1040 }
1041
1042 // If this is the primary source file, remember that this macro hasn't been
1043 // used yet.
1044 if (isInPrimaryFile())
1045 MI->setIsUsed(false);
1046
1047 // Finally, if this identifier already had a macro defined for it, verify that
1048 // the macro bodies are identical and free the old definition.
1049 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
1050 if (!OtherMI->isUsed())
1051 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1052
1053 // Macros must be identical. This means all tokes and whitespace separation
1054 // must be the same. C99 6.10.3.2.
1055 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner204b2fe2008-11-18 21:48:13 +00001056 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001057 << MacroNameTok.getIdentifierInfo();
Chris Lattner08631c52008-11-23 21:45:46 +00001058 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
Chris Lattner141e71f2008-03-09 01:54:53 +00001059 }
1060 delete OtherMI;
1061 }
1062
1063 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
1064}
1065
1066/// HandleUndefDirective - Implements #undef.
1067///
1068void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1069 ++NumUndefined;
1070
1071 Token MacroNameTok;
1072 ReadMacroName(MacroNameTok, 2);
1073
1074 // Error reading macro name? If so, diagnostic already issued.
1075 if (MacroNameTok.is(tok::eom))
1076 return;
1077
1078 // Check to see if this is the last token on the #undef line.
1079 CheckEndOfDirective("#undef");
1080
1081 // Okay, we finally have a valid identifier to undef.
1082 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1083
1084 // If the macro is not defined, this is a noop undef, just return.
1085 if (MI == 0) return;
1086
1087 if (!MI->isUsed())
1088 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1089
1090 // Free macro definition.
1091 delete MI;
1092 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1093}
1094
1095
1096//===----------------------------------------------------------------------===//
1097// Preprocessor Conditional Directive Handling.
1098//===----------------------------------------------------------------------===//
1099
1100/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1101/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1102/// if any tokens have been returned or pp-directives activated before this
1103/// #ifndef has been lexed.
1104///
1105void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1106 bool ReadAnyTokensBeforeDirective) {
1107 ++NumIf;
1108 Token DirectiveTok = Result;
1109
1110 Token MacroNameTok;
1111 ReadMacroName(MacroNameTok);
1112
1113 // Error reading macro name? If so, diagnostic already issued.
1114 if (MacroNameTok.is(tok::eom)) {
1115 // Skip code until we get to #endif. This helps with recovery by not
1116 // emitting an error when the #endif is reached.
1117 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1118 /*Foundnonskip*/false, /*FoundElse*/false);
1119 return;
1120 }
1121
1122 // Check to see if this is the last token on the #if[n]def line.
1123 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1124
Ted Kremenek60e45d42008-11-18 00:34:22 +00001125 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001126 // If the start of a top-level #ifdef, inform MIOpt.
1127 if (!ReadAnyTokensBeforeDirective) {
1128 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001129 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001130 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001131 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001132 }
1133
1134 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1135 MacroInfo *MI = getMacroInfo(MII);
1136
1137 // If there is a macro, process it.
1138 if (MI) // Mark it used.
1139 MI->setIsUsed(true);
1140
1141 // Should we include the stuff contained by this directive?
1142 if (!MI == isIfndef) {
1143 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001144 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001145 /*foundnonskip*/true, /*foundelse*/false);
1146 } else {
1147 // No, skip the contents of this block and return the first token after it.
1148 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1149 /*Foundnonskip*/false,
1150 /*FoundElse*/false);
1151 }
1152}
1153
1154/// HandleIfDirective - Implements the #if directive.
1155///
1156void Preprocessor::HandleIfDirective(Token &IfToken,
1157 bool ReadAnyTokensBeforeDirective) {
1158 ++NumIf;
1159
1160 // Parse and evaluation the conditional expression.
1161 IdentifierInfo *IfNDefMacro = 0;
1162 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1163
Nuno Lopes0049db62008-06-01 18:31:24 +00001164
1165 // If this condition is equivalent to #ifndef X, and if this is the first
1166 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001167 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001168 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001169 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001170 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001171 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001172 }
1173
Chris Lattner141e71f2008-03-09 01:54:53 +00001174 // Should we include the stuff contained by this directive?
1175 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001176 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001177 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001178 /*foundnonskip*/true, /*foundelse*/false);
1179 } else {
1180 // No, skip the contents of this block and return the first token after it.
1181 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1182 /*FoundElse*/false);
1183 }
1184}
1185
1186/// HandleEndifDirective - Implements the #endif directive.
1187///
1188void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1189 ++NumEndif;
1190
1191 // Check that this is the whole directive.
1192 CheckEndOfDirective("#endif");
1193
1194 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001195 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001196 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001197 Diag(EndifToken, diag::err_pp_endif_without_if);
1198 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001199 }
1200
1201 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001202 if (CurPPLexer->getConditionalStackDepth() == 0)
1203 CurPPLexer->MIOpt.ExitTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001204
Ted Kremenek60e45d42008-11-18 00:34:22 +00001205 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001206 "This code should only be reachable in the non-skipping case!");
1207}
1208
1209
1210void Preprocessor::HandleElseDirective(Token &Result) {
1211 ++NumElse;
1212
1213 // #else directive in a non-skipping conditional... start skipping.
1214 CheckEndOfDirective("#else");
1215
1216 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001217 if (CurPPLexer->popConditionalLevel(CI)) {
1218 Diag(Result, diag::pp_err_else_without_if);
1219 return;
1220 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001221
1222 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001223 if (CurPPLexer->getConditionalStackDepth() == 0)
1224 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001225
1226 // If this is a #else with a #else before it, report the error.
1227 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1228
1229 // Finally, skip the rest of the contents of this block and return the first
1230 // token after it.
1231 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1232 /*FoundElse*/true);
1233}
1234
1235void Preprocessor::HandleElifDirective(Token &ElifToken) {
1236 ++NumElse;
1237
1238 // #elif directive in a non-skipping conditional... start skipping.
1239 // We don't care what the condition is, because we will always skip it (since
1240 // the block immediately before it was included).
1241 DiscardUntilEndOfDirective();
1242
1243 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001244 if (CurPPLexer->popConditionalLevel(CI)) {
1245 Diag(ElifToken, diag::pp_err_elif_without_if);
1246 return;
1247 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001248
1249 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001250 if (CurPPLexer->getConditionalStackDepth() == 0)
1251 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001252
1253 // If this is a #elif with a #else before it, report the error.
1254 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1255
1256 // Finally, skip the rest of the contents of this block and return the first
1257 // token after it.
1258 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1259 /*FoundElse*/CI.FoundElse);
1260}
1261