blob: 59df8255e322172f3ef3f6533344a5a764177466 [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
Ted Kremenek0ea76722008-12-15 19:56:42 +000025MacroInfo* Preprocessor::AllocateMacroInfo(SourceLocation L) {
26 MacroInfo *MI;
27
28 if (!MICache.empty()) {
29 MI = MICache.back();
30 MICache.pop_back();
31 }
32 else MI = (MacroInfo*) BP.Allocate<MacroInfo>();
33 new (MI) MacroInfo(L);
34 return MI;
35}
36
Chris Lattner141e71f2008-03-09 01:54:53 +000037/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
38/// current line until the tok::eom token is found.
39void Preprocessor::DiscardUntilEndOfDirective() {
40 Token Tmp;
41 do {
42 LexUnexpandedToken(Tmp);
43 } while (Tmp.isNot(tok::eom));
44}
45
Chris Lattner141e71f2008-03-09 01:54:53 +000046/// ReadMacroName - Lex and validate a macro name, which occurs after a
47/// #define or #undef. This sets the token kind to eom and discards the rest
48/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
49/// this is due to a a #define, 2 if #undef directive, 0 if it is something
50/// else (e.g. #ifdef).
51void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
52 // Read the token, don't allow macro expansion on it.
53 LexUnexpandedToken(MacroNameTok);
54
55 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000056 if (MacroNameTok.is(tok::eom)) {
57 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
58 return;
59 }
Chris Lattner141e71f2008-03-09 01:54:53 +000060
61 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
62 if (II == 0) {
63 std::string Spelling = getSpelling(MacroNameTok);
Chris Lattner9485d232008-12-13 20:12:40 +000064 const IdentifierInfo &Info = Identifiers.get(Spelling);
65 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +000066 // C++ 2.5p2: Alternative tokens behave the same as its primary token
67 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +000068 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000069 else
70 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
71 // Fall through on error.
72 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
73 // Error if defining "defined": C99 6.10.8.4.
74 Diag(MacroNameTok, diag::err_defined_macro_name);
75 } else if (isDefineUndef && II->hasMacroDefinition() &&
76 getMacroInfo(II)->isBuiltinMacro()) {
77 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
78 if (isDefineUndef == 1)
79 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
80 else
81 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
82 } else {
83 // Okay, we got a good identifier node. Return it.
84 return;
85 }
86
87 // Invalid macro name, read and discard the rest of the line. Then set the
88 // token kind to tok::eom.
89 MacroNameTok.setKind(tok::eom);
90 return DiscardUntilEndOfDirective();
91}
92
93/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
94/// not, emit a diagnostic and consume up until the eom.
95void Preprocessor::CheckEndOfDirective(const char *DirType) {
96 Token Tmp;
97 // Lex unexpanded tokens: macros might expand to zero tokens, causing us to
98 // miss diagnosing invalid lines.
99 LexUnexpandedToken(Tmp);
100
101 // There should be no tokens after the directive, but we allow them as an
102 // extension.
103 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
104 LexUnexpandedToken(Tmp);
105
106 if (Tmp.isNot(tok::eom)) {
Chris Lattner56b05c82008-11-18 08:02:48 +0000107 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType;
Chris Lattner141e71f2008-03-09 01:54:53 +0000108 DiscardUntilEndOfDirective();
109 }
110}
111
112
113
114/// SkipExcludedConditionalBlock - We just read a #if or related directive and
115/// decided that the subsequent tokens are in the #if'd out portion of the
116/// file. Lex the rest of the file, until we see an #endif. If
117/// FoundNonSkipPortion is true, then we have already emitted code for part of
118/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
119/// is true, then #else directives are ok, if not, then we have already seen one
120/// so a #else directive is a duplicate. When this returns, the caller can lex
121/// the first valid token.
122void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
123 bool FoundNonSkipPortion,
124 bool FoundElse) {
125 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000126 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000127
Ted Kremenek60e45d42008-11-18 00:34:22 +0000128 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000129 FoundNonSkipPortion, FoundElse);
130
Ted Kremenek268ee702008-12-12 18:34:08 +0000131 if (CurPTHLexer) {
132 PTHSkipExcludedConditionalBlock();
133 return;
134 }
135
Chris Lattner141e71f2008-03-09 01:54:53 +0000136 // Enter raw mode to disable identifier lookup (and thus macro expansion),
137 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000138 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000139 Token Tok;
140 while (1) {
Ted Kremenekf6452c52008-11-18 01:04:47 +0000141 if (CurLexer)
142 CurLexer->Lex(Tok);
143 else
144 CurPTHLexer->Lex(Tok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000145
146 // If this is the end of the buffer, we have an error.
147 if (Tok.is(tok::eof)) {
148 // Emit errors for each unterminated conditional on the stack, including
149 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000150 while (!CurPPLexer->ConditionalStack.empty()) {
151 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000152 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000153 CurPPLexer->ConditionalStack.pop_back();
Chris Lattner141e71f2008-03-09 01:54:53 +0000154 }
155
156 // Just return and let the caller lex after this #include.
157 break;
158 }
159
160 // If this token is not a preprocessor directive, just skip it.
161 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
162 continue;
163
164 // We just parsed a # character at the start of a line, so we're in
165 // directive mode. Tell the lexer this so any newlines we see will be
166 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000167 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000168 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000169
170
171 // Read the next token, the directive flavor.
172 LexUnexpandedToken(Tok);
173
174 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
175 // something bogus), skip it.
176 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000177 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000178 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000179 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000180 continue;
181 }
182
183 // If the first letter isn't i or e, it isn't intesting to us. We know that
184 // this is safe in the face of spelling differences, because there is no way
185 // to spell an i/e in a strange way that is another letter. Skipping this
186 // allows us to avoid looking up the identifier info for #define/#undef and
187 // other common directives.
188 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
189 char FirstChar = RawCharData[0];
190 if (FirstChar >= 'a' && FirstChar <= 'z' &&
191 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000192 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000193 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000194 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000195 continue;
196 }
197
198 // Get the identifier name without trigraphs or embedded newlines. Note
199 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
200 // when skipping.
201 // TODO: could do this with zero copies in the no-clean case by using
202 // strncmp below.
203 char Directive[20];
204 unsigned IdLen;
205 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
206 IdLen = Tok.getLength();
207 memcpy(Directive, RawCharData, IdLen);
208 Directive[IdLen] = 0;
209 } else {
210 std::string DirectiveStr = getSpelling(Tok);
211 IdLen = DirectiveStr.size();
212 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000213 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000214 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000215 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000216 continue;
217 }
218 memcpy(Directive, &DirectiveStr[0], IdLen);
219 Directive[IdLen] = 0;
220 }
221
222 if (FirstChar == 'i' && Directive[1] == 'f') {
223 if ((IdLen == 2) || // "if"
224 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
225 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
226 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
227 // bother parsing the condition.
228 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000229 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000230 /*foundnonskip*/false,
231 /*fnddelse*/false);
232 }
233 } else if (FirstChar == 'e') {
234 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
235 CheckEndOfDirective("#endif");
236 PPConditionalInfo CondInfo;
237 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000238 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000239 InCond = InCond; // Silence warning in no-asserts mode.
240 assert(!InCond && "Can't be skipping if not in a conditional!");
241
242 // If we popped the outermost skipping block, we're done skipping!
243 if (!CondInfo.WasSkipping)
244 break;
245 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
246 // #else directive in a skipping conditional. If not in some other
247 // skipping conditional, and if #else hasn't already been seen, enter it
248 // as a non-skipping conditional.
249 CheckEndOfDirective("#else");
Ted Kremenek60e45d42008-11-18 00:34:22 +0000250 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000251
252 // If this is a #else with a #else before it, report the error.
253 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
254
255 // Note that we've seen a #else in this conditional.
256 CondInfo.FoundElse = true;
257
258 // If the conditional is at the top level, and the #if block wasn't
259 // entered, enter the #else block now.
260 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
261 CondInfo.FoundNonSkip = true;
262 break;
263 }
264 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000265 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000266
267 bool ShouldEnter;
268 // If this is in a skipping block or if we're already handled this #if
269 // block, don't bother parsing the condition.
270 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
271 DiscardUntilEndOfDirective();
272 ShouldEnter = false;
273 } else {
274 // Restore the value of LexingRawMode so that identifiers are
275 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000276 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
277 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000278 IdentifierInfo *IfNDefMacro = 0;
279 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000280 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000281 }
282
283 // If this is a #elif with a #else before it, report the error.
284 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
285
286 // If this condition is true, enter it!
287 if (ShouldEnter) {
288 CondInfo.FoundNonSkip = true;
289 break;
290 }
291 }
292 }
293
Ted Kremenek60e45d42008-11-18 00:34:22 +0000294 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000295 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000296 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000297 }
298
299 // Finally, if we are out of the conditional (saw an #endif or ran off the end
300 // of the file, just stop skipping and return to lexing whatever came after
301 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000302 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000303}
304
Ted Kremenek268ee702008-12-12 18:34:08 +0000305void Preprocessor::PTHSkipExcludedConditionalBlock() {
306
307 while(1) {
308 assert(CurPTHLexer);
309 assert(CurPTHLexer->LexingRawMode == false);
310
311 // Skip to the next '#else', '#elif', or #endif.
312 if (CurPTHLexer->SkipBlock()) {
313 // We have reached an #endif. Both the '#' and 'endif' tokens
314 // have been consumed by the PTHLexer. Just pop off the condition level.
315 PPConditionalInfo CondInfo;
316 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
317 InCond = InCond; // Silence warning in no-asserts mode.
318 assert(!InCond && "Can't be skipping if not in a conditional!");
319 break;
320 }
321
322 // We have reached a '#else' or '#elif'. Lex the next token to get
323 // the directive flavor.
324 Token Tok;
325 LexUnexpandedToken(Tok);
326
327 // We can actually look up the IdentifierInfo here since we aren't in
328 // raw mode.
329 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
330
331 if (K == tok::pp_else) {
332 // #else: Enter the else condition. We aren't in a nested condition
333 // since we skip those. We're always in the one matching the last
334 // blocked we skipped.
335 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
336 // Note that we've seen a #else in this conditional.
337 CondInfo.FoundElse = true;
338
339 // If the #if block wasn't entered then enter the #else block now.
340 if (!CondInfo.FoundNonSkip) {
341 CondInfo.FoundNonSkip = true;
342 break;
343 }
344
345 // Otherwise skip this block.
346 continue;
347 }
348
349 assert(K == tok::pp_elif);
350 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
351
352 // If this is a #elif with a #else before it, report the error.
353 if (CondInfo.FoundElse)
354 Diag(Tok, diag::pp_err_elif_after_else);
355
356 // If this is in a skipping block or if we're already handled this #if
357 // block, don't bother parsing the condition. We just skip this block.
358 if (CondInfo.FoundNonSkip)
359 continue;
360
361 // Evaluate the condition of the #elif.
362 IdentifierInfo *IfNDefMacro = 0;
363 CurPTHLexer->ParsingPreprocessorDirective = true;
364 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
365 CurPTHLexer->ParsingPreprocessorDirective = false;
366
367 // If this condition is true, enter it!
368 if (ShouldEnter) {
369 CondInfo.FoundNonSkip = true;
370 break;
371 }
372
373 // Otherwise, skip this block and go to the next one.
374 continue;
375 }
376}
377
Chris Lattner10725092008-03-09 04:17:44 +0000378/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
379/// return null on failure. isAngled indicates whether the file reference is
380/// for system #include's or not (i.e. using <> instead of "").
381const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
382 const char *FilenameEnd,
383 bool isAngled,
384 const DirectoryLookup *FromDir,
385 const DirectoryLookup *&CurDir) {
386 // If the header lookup mechanism may be relative to the current file, pass in
387 // info about where the current file is.
388 const FileEntry *CurFileEnt = 0;
389 if (!FromDir) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000390 unsigned FileID = getCurrentFileLexer()->getFileID();
391 CurFileEnt = SourceMgr.getFileEntryForID(FileID);
Chris Lattner10725092008-03-09 04:17:44 +0000392 }
393
394 // Do a standard file entry lookup.
395 CurDir = CurDirLookup;
396 const FileEntry *FE =
397 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
398 isAngled, FromDir, CurDir, CurFileEnt);
399 if (FE) return FE;
400
401 // Otherwise, see if this is a subframework header. If so, this is relative
402 // to one of the headers on the #include stack. Walk the list of the current
403 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000404 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000405 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000406 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
407 CurFileEnt)))
408 return FE;
409 }
410
411 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
412 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000413 if (IsFileLexer(ISEntry)) {
Chris Lattner10725092008-03-09 04:17:44 +0000414 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000415 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000416 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
417 FilenameEnd, CurFileEnt)))
418 return FE;
419 }
420 }
421
422 // Otherwise, we really couldn't find the file.
423 return 0;
424}
425
Chris Lattner141e71f2008-03-09 01:54:53 +0000426
427//===----------------------------------------------------------------------===//
428// Preprocessor Directive Handling.
429//===----------------------------------------------------------------------===//
430
431/// HandleDirective - This callback is invoked when the lexer sees a # token
432/// at the start of a line. This consumes the directive, modifies the
433/// lexer/preprocessor state, and advances the lexer(s) so that the next token
434/// read is the correct one.
435void Preprocessor::HandleDirective(Token &Result) {
436 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
437
438 // We just parsed a # character at the start of a line, so we're in directive
439 // mode. Tell the lexer this so any newlines we see will be converted into an
440 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000441 CurPPLexer->ParsingPreprocessorDirective = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000442
443 ++NumDirectives;
444
445 // We are about to read a token. For the multiple-include optimization FA to
446 // work, we have to remember if we had read any tokens *before* this
447 // pp-directive.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000448 bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Chris Lattner141e71f2008-03-09 01:54:53 +0000449
450 // Read the next token, the directive flavor. This isn't expanded due to
451 // C99 6.10.3p8.
452 LexUnexpandedToken(Result);
453
454 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
455 // #define A(x) #x
456 // A(abc
457 // #warning blah
458 // def)
459 // If so, the user is relying on non-portable behavior, emit a diagnostic.
460 if (InMacroArgs)
461 Diag(Result, diag::ext_embedded_directive);
462
463TryAgain:
464 switch (Result.getKind()) {
465 case tok::eom:
466 return; // null directive.
467 case tok::comment:
468 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
469 LexUnexpandedToken(Result);
470 goto TryAgain;
471
472 case tok::numeric_constant:
473 // FIXME: implement # 7 line numbers!
474 DiscardUntilEndOfDirective();
475 return;
476 default:
477 IdentifierInfo *II = Result.getIdentifierInfo();
478 if (II == 0) break; // Not an identifier.
479
480 // Ask what the preprocessor keyword ID is.
481 switch (II->getPPKeywordID()) {
482 default: break;
483 // C99 6.10.1 - Conditional Inclusion.
484 case tok::pp_if:
485 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
486 case tok::pp_ifdef:
487 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
488 case tok::pp_ifndef:
489 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
490 case tok::pp_elif:
491 return HandleElifDirective(Result);
492 case tok::pp_else:
493 return HandleElseDirective(Result);
494 case tok::pp_endif:
495 return HandleEndifDirective(Result);
496
497 // C99 6.10.2 - Source File Inclusion.
498 case tok::pp_include:
499 return HandleIncludeDirective(Result); // Handle #include.
500
501 // C99 6.10.3 - Macro Replacement.
502 case tok::pp_define:
503 return HandleDefineDirective(Result);
504 case tok::pp_undef:
505 return HandleUndefDirective(Result);
506
507 // C99 6.10.4 - Line Control.
508 case tok::pp_line:
509 // FIXME: implement #line
510 DiscardUntilEndOfDirective();
511 return;
512
513 // C99 6.10.5 - Error Directive.
514 case tok::pp_error:
515 return HandleUserDiagnosticDirective(Result, false);
516
517 // C99 6.10.6 - Pragma Directive.
518 case tok::pp_pragma:
519 return HandlePragmaDirective();
520
521 // GNU Extensions.
522 case tok::pp_import:
523 return HandleImportDirective(Result);
524 case tok::pp_include_next:
525 return HandleIncludeNextDirective(Result);
526
527 case tok::pp_warning:
528 Diag(Result, diag::ext_pp_warning_directive);
529 return HandleUserDiagnosticDirective(Result, true);
530 case tok::pp_ident:
531 return HandleIdentSCCSDirective(Result);
532 case tok::pp_sccs:
533 return HandleIdentSCCSDirective(Result);
534 case tok::pp_assert:
535 //isExtension = true; // FIXME: implement #assert
536 break;
537 case tok::pp_unassert:
538 //isExtension = true; // FIXME: implement #unassert
539 break;
540 }
541 break;
542 }
543
544 // If we reached here, the preprocessing token is not valid!
545 Diag(Result, diag::err_pp_invalid_directive);
546
547 // Read the rest of the PP line.
548 DiscardUntilEndOfDirective();
549
550 // Okay, we're done parsing the directive.
551}
552
553void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
554 bool isWarning) {
555 // Read the rest of the line raw. We do this because we don't want macros
556 // to be expanded and we don't require that the tokens be valid preprocessing
557 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
558 // collapse multiple consequtive white space between tokens, but this isn't
559 // specified by the standard.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000560
561 if (CurLexer) {
562 std::string Message = CurLexer->ReadToEndOfLine();
563 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
564 Diag(Tok, DiagID) << Message;
565 }
566 else {
567 CurPTHLexer->DiscardToEndOfLine();
568 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000569}
570
571/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
572///
573void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
574 // Yes, this directive is an extension.
575 Diag(Tok, diag::ext_pp_ident_directive);
576
577 // Read the string argument.
578 Token StrTok;
579 Lex(StrTok);
580
581 // If the token kind isn't a string, it's a malformed directive.
582 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000583 StrTok.isNot(tok::wide_string_literal)) {
584 Diag(StrTok, diag::err_pp_malformed_ident);
585 return;
586 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000587
588 // Verify that there is nothing after the string, other than EOM.
589 CheckEndOfDirective("#ident");
590
591 if (Callbacks)
592 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
593}
594
595//===----------------------------------------------------------------------===//
596// Preprocessor Include Directive Handling.
597//===----------------------------------------------------------------------===//
598
599/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
600/// checked and spelled filename, e.g. as an operand of #include. This returns
601/// true if the input filename was in <>'s or false if it were in ""'s. The
602/// caller is expected to provide a buffer that is large enough to hold the
603/// spelling of the filename, but is also expected to handle the case when
604/// this method decides to use a different buffer.
605bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
606 const char *&BufStart,
607 const char *&BufEnd) {
608 // Get the text form of the filename.
609 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
610
611 // Make sure the filename is <x> or "x".
612 bool isAngled;
613 if (BufStart[0] == '<') {
614 if (BufEnd[-1] != '>') {
615 Diag(Loc, diag::err_pp_expects_filename);
616 BufStart = 0;
617 return true;
618 }
619 isAngled = true;
620 } else if (BufStart[0] == '"') {
621 if (BufEnd[-1] != '"') {
622 Diag(Loc, diag::err_pp_expects_filename);
623 BufStart = 0;
624 return true;
625 }
626 isAngled = false;
627 } else {
628 Diag(Loc, diag::err_pp_expects_filename);
629 BufStart = 0;
630 return true;
631 }
632
633 // Diagnose #include "" as invalid.
634 if (BufEnd-BufStart <= 2) {
635 Diag(Loc, diag::err_pp_empty_filename);
636 BufStart = 0;
637 return "";
638 }
639
640 // Skip the brackets.
641 ++BufStart;
642 --BufEnd;
643 return isAngled;
644}
645
646/// ConcatenateIncludeName - Handle cases where the #include name is expanded
647/// from a macro as multiple tokens, which need to be glued together. This
648/// occurs for code like:
649/// #define FOO <a/b.h>
650/// #include FOO
651/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
652///
653/// This code concatenates and consumes tokens up to the '>' token. It returns
654/// false if the > was found, otherwise it returns true if it finds and consumes
655/// the EOM marker.
656static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
657 Preprocessor &PP) {
658 Token CurTok;
659
660 PP.Lex(CurTok);
661 while (CurTok.isNot(tok::eom)) {
662 // Append the spelling of this token to the buffer. If there was a space
663 // before it, add it now.
664 if (CurTok.hasLeadingSpace())
665 FilenameBuffer.push_back(' ');
666
667 // Get the spelling of the token, directly into FilenameBuffer if possible.
668 unsigned PreAppendSize = FilenameBuffer.size();
669 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
670
671 const char *BufPtr = &FilenameBuffer[PreAppendSize];
672 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
673
674 // If the token was spelled somewhere else, copy it into FilenameBuffer.
675 if (BufPtr != &FilenameBuffer[PreAppendSize])
676 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
677
678 // Resize FilenameBuffer to the correct size.
679 if (CurTok.getLength() != ActualLen)
680 FilenameBuffer.resize(PreAppendSize+ActualLen);
681
682 // If we found the '>' marker, return success.
683 if (CurTok.is(tok::greater))
684 return false;
685
686 PP.Lex(CurTok);
687 }
688
689 // If we hit the eom marker, emit an error and return true so that the caller
690 // knows the EOM has been read.
691 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
692 return true;
693}
694
695/// HandleIncludeDirective - The "#include" tokens have just been read, read the
696/// file to be included from the lexer, then include it! This is a common
697/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +0000698/// #import. LookupFrom is set when this is a #include_next directive, it
699/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +0000700void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
701 const DirectoryLookup *LookupFrom,
702 bool isImport) {
703
704 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +0000705 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000706
707 // Reserve a buffer to get the spelling.
708 llvm::SmallVector<char, 128> FilenameBuffer;
709 const char *FilenameStart, *FilenameEnd;
710
711 switch (FilenameTok.getKind()) {
712 case tok::eom:
713 // If the token kind is EOM, the error has already been diagnosed.
714 return;
715
716 case tok::angle_string_literal:
717 case tok::string_literal: {
718 FilenameBuffer.resize(FilenameTok.getLength());
719 FilenameStart = &FilenameBuffer[0];
720 unsigned Len = getSpelling(FilenameTok, FilenameStart);
721 FilenameEnd = FilenameStart+Len;
722 break;
723 }
724
725 case tok::less:
726 // This could be a <foo/bar.h> file coming from a macro expansion. In this
727 // case, glue the tokens together into FilenameBuffer and interpret those.
728 FilenameBuffer.push_back('<');
729 if (ConcatenateIncludeName(FilenameBuffer, *this))
730 return; // Found <eom> but no ">"? Diagnostic already emitted.
731 FilenameStart = &FilenameBuffer[0];
732 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
733 break;
734 default:
735 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
736 DiscardUntilEndOfDirective();
737 return;
738 }
739
740 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
741 FilenameStart, FilenameEnd);
742 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
743 // error.
744 if (FilenameStart == 0) {
745 DiscardUntilEndOfDirective();
746 return;
747 }
748
749 // Verify that there is nothing after the filename, other than EOM. Use the
750 // preprocessor to lex this in case lexing the filename entered a macro.
751 CheckEndOfDirective("#include");
752
753 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +0000754 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
755 Diag(FilenameTok, diag::err_pp_include_too_deep);
756 return;
757 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000758
759 // Search include directories.
760 const DirectoryLookup *CurDir;
761 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
762 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +0000763 if (File == 0) {
764 Diag(FilenameTok, diag::err_pp_file_not_found)
765 << std::string(FilenameStart, FilenameEnd);
766 return;
767 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000768
Chris Lattner72181832008-09-26 20:12:23 +0000769 // Ask HeaderInfo if we should enter this #include file. If not, #including
770 // this file will have no effect.
771 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +0000772 return;
Chris Lattner72181832008-09-26 20:12:23 +0000773
774 // The #included file will be considered to be a system header if either it is
775 // in a system include directory, or if the #includer is a system include
776 // header.
Chris Lattner9d728512008-10-27 01:19:25 +0000777 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000778 std::max(HeaderInfo.getFileDirFlavor(File),
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000779 SourceMgr.getFileCharacteristic(getCurrentFileLexer()->getFileID()));
Chris Lattner72181832008-09-26 20:12:23 +0000780
Chris Lattner141e71f2008-03-09 01:54:53 +0000781 // Look up the file, create a File ID for it.
Nico Weber7bfaaae2008-08-10 19:59:06 +0000782 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
Chris Lattner72181832008-09-26 20:12:23 +0000783 FileCharacter);
Chris Lattner56b05c82008-11-18 08:02:48 +0000784 if (FileID == 0) {
785 Diag(FilenameTok, diag::err_pp_file_not_found)
786 << std::string(FilenameStart, FilenameEnd);
787 return;
788 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000789
790 // Finally, if all is good, enter the new file!
791 EnterSourceFile(FileID, CurDir);
792}
793
794/// HandleIncludeNextDirective - Implements #include_next.
795///
796void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
797 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
798
799 // #include_next is like #include, except that we start searching after
800 // the current found directory. If we can't do this, issue a
801 // diagnostic.
802 const DirectoryLookup *Lookup = CurDirLookup;
803 if (isInPrimaryFile()) {
804 Lookup = 0;
805 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
806 } else if (Lookup == 0) {
807 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
808 } else {
809 // Start looking up in the next directory.
810 ++Lookup;
811 }
812
813 return HandleIncludeDirective(IncludeNextTok, Lookup);
814}
815
816/// HandleImportDirective - Implements #import.
817///
818void Preprocessor::HandleImportDirective(Token &ImportTok) {
819 Diag(ImportTok, diag::ext_pp_import_directive);
820
821 return HandleIncludeDirective(ImportTok, 0, true);
822}
823
824//===----------------------------------------------------------------------===//
825// Preprocessor Macro Directive Handling.
826//===----------------------------------------------------------------------===//
827
828/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
829/// definition has just been read. Lex the rest of the arguments and the
830/// closing ), updating MI with what we learn. Return true if an error occurs
831/// parsing the arg list.
832bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
833 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
834
835 Token Tok;
836 while (1) {
837 LexUnexpandedToken(Tok);
838 switch (Tok.getKind()) {
839 case tok::r_paren:
840 // Found the end of the argument list.
841 if (Arguments.empty()) { // #define FOO()
842 MI->setArgumentList(Arguments.begin(), Arguments.end());
843 return false;
844 }
845 // Otherwise we have #define FOO(A,)
846 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
847 return true;
848 case tok::ellipsis: // #define X(... -> C99 varargs
849 // Warn if use of C99 feature in non-C99 mode.
850 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
851
852 // Lex the token after the identifier.
853 LexUnexpandedToken(Tok);
854 if (Tok.isNot(tok::r_paren)) {
855 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
856 return true;
857 }
858 // Add the __VA_ARGS__ identifier as an argument.
859 Arguments.push_back(Ident__VA_ARGS__);
860 MI->setIsC99Varargs();
861 MI->setArgumentList(Arguments.begin(), Arguments.end());
862 return false;
863 case tok::eom: // #define X(
864 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
865 return true;
866 default:
867 // Handle keywords and identifiers here to accept things like
868 // #define Foo(for) for.
869 IdentifierInfo *II = Tok.getIdentifierInfo();
870 if (II == 0) {
871 // #define X(1
872 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
873 return true;
874 }
875
876 // If this is already used as an argument, it is used multiple times (e.g.
877 // #define X(A,A.
878 if (std::find(Arguments.begin(), Arguments.end(), II) !=
879 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +0000880 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +0000881 return true;
882 }
883
884 // Add the argument to the macro info.
885 Arguments.push_back(II);
886
887 // Lex the token after the identifier.
888 LexUnexpandedToken(Tok);
889
890 switch (Tok.getKind()) {
891 default: // #define X(A B
892 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
893 return true;
894 case tok::r_paren: // #define X(A)
895 MI->setArgumentList(Arguments.begin(), Arguments.end());
896 return false;
897 case tok::comma: // #define X(A,
898 break;
899 case tok::ellipsis: // #define X(A... -> GCC extension
900 // Diagnose extension.
901 Diag(Tok, diag::ext_named_variadic_macro);
902
903 // Lex the token after the identifier.
904 LexUnexpandedToken(Tok);
905 if (Tok.isNot(tok::r_paren)) {
906 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
907 return true;
908 }
909
910 MI->setIsGNUVarargs();
911 MI->setArgumentList(Arguments.begin(), Arguments.end());
912 return false;
913 }
914 }
915 }
916}
917
918/// HandleDefineDirective - Implements #define. This consumes the entire macro
919/// line then lets the caller lex the next real token.
920void Preprocessor::HandleDefineDirective(Token &DefineTok) {
921 ++NumDefined;
922
923 Token MacroNameTok;
924 ReadMacroName(MacroNameTok, 1);
925
926 // Error reading macro name? If so, diagnostic already issued.
927 if (MacroNameTok.is(tok::eom))
928 return;
929
930 // If we are supposed to keep comments in #defines, reenable comment saving
931 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000932 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000933
934 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +0000935 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +0000936
937 Token Tok;
938 LexUnexpandedToken(Tok);
939
940 // If this is a function-like macro definition, parse the argument list,
941 // marking each of the identifiers as being used as macro arguments. Also,
942 // check other constraints on the first token of the macro body.
943 if (Tok.is(tok::eom)) {
944 // If there is no body to this macro, we have no special handling here.
945 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
946 // This is a function-like macro definition. Read the argument list.
947 MI->setIsFunctionLike();
948 if (ReadMacroDefinitionArgList(MI)) {
949 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +0000950 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +0000951 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000952 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +0000953 DiscardUntilEndOfDirective();
954 return;
955 }
956
957 // Read the first token after the arg list for down below.
958 LexUnexpandedToken(Tok);
959 } else if (!Tok.hasLeadingSpace()) {
960 // C99 requires whitespace between the macro definition and the body. Emit
961 // a diagnostic for something like "#define X+".
962 if (Features.C99) {
963 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
964 } else {
965 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
966 // one in some cases!
967 }
968 } else {
969 // This is a normal token with leading space. Clear the leading space
970 // marker on the first token to get proper expansion.
971 Tok.clearFlag(Token::LeadingSpace);
972 }
973
974 // If this is a definition of a variadic C99 function-like macro, not using
975 // the GNU named varargs extension, enabled __VA_ARGS__.
976
977 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
978 // This gets unpoisoned where it is allowed.
979 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
980 if (MI->isC99Varargs())
981 Ident__VA_ARGS__->setIsPoisoned(false);
982
983 // Read the rest of the macro body.
984 if (MI->isObjectLike()) {
985 // Object-like macros are very simple, just read their body.
986 while (Tok.isNot(tok::eom)) {
987 MI->AddTokenToBody(Tok);
988 // Get the next token of the macro.
989 LexUnexpandedToken(Tok);
990 }
991
992 } else {
993 // Otherwise, read the body of a function-like macro. This has to validate
994 // the # (stringize) operator.
995 while (Tok.isNot(tok::eom)) {
996 MI->AddTokenToBody(Tok);
997
998 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
999 // parameters in function-like macro expansions.
1000 if (Tok.isNot(tok::hash)) {
1001 // Get the next token of the macro.
1002 LexUnexpandedToken(Tok);
1003 continue;
1004 }
1005
1006 // Get the next token of the macro.
1007 LexUnexpandedToken(Tok);
1008
1009 // Not a macro arg identifier?
1010 if (!Tok.getIdentifierInfo() ||
1011 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1012 Diag(Tok, diag::err_pp_stringize_not_parameter);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001013 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001014
1015 // Disable __VA_ARGS__ again.
1016 Ident__VA_ARGS__->setIsPoisoned(true);
1017 return;
1018 }
1019
1020 // Things look ok, add the param name token to the macro.
1021 MI->AddTokenToBody(Tok);
1022
1023 // Get the next token of the macro.
1024 LexUnexpandedToken(Tok);
1025 }
1026 }
1027
1028
1029 // Disable __VA_ARGS__ again.
1030 Ident__VA_ARGS__->setIsPoisoned(true);
1031
1032 // Check that there is no paste (##) operator at the begining or end of the
1033 // replacement list.
1034 unsigned NumTokens = MI->getNumTokens();
1035 if (NumTokens != 0) {
1036 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1037 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001038 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001039 return;
1040 }
1041 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1042 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001043 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001044 return;
1045 }
1046 }
1047
1048 // If this is the primary source file, remember that this macro hasn't been
1049 // used yet.
1050 if (isInPrimaryFile())
1051 MI->setIsUsed(false);
1052
1053 // Finally, if this identifier already had a macro defined for it, verify that
1054 // the macro bodies are identical and free the old definition.
1055 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
1056 if (!OtherMI->isUsed())
1057 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1058
1059 // Macros must be identical. This means all tokes and whitespace separation
1060 // must be the same. C99 6.10.3.2.
1061 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner204b2fe2008-11-18 21:48:13 +00001062 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001063 << MacroNameTok.getIdentifierInfo();
Chris Lattner08631c52008-11-23 21:45:46 +00001064 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
Chris Lattner141e71f2008-03-09 01:54:53 +00001065 }
Ted Kremenek0ea76722008-12-15 19:56:42 +00001066 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001067 }
1068
1069 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
1070}
1071
1072/// HandleUndefDirective - Implements #undef.
1073///
1074void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1075 ++NumUndefined;
1076
1077 Token MacroNameTok;
1078 ReadMacroName(MacroNameTok, 2);
1079
1080 // Error reading macro name? If so, diagnostic already issued.
1081 if (MacroNameTok.is(tok::eom))
1082 return;
1083
1084 // Check to see if this is the last token on the #undef line.
1085 CheckEndOfDirective("#undef");
1086
1087 // Okay, we finally have a valid identifier to undef.
1088 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1089
1090 // If the macro is not defined, this is a noop undef, just return.
1091 if (MI == 0) return;
1092
1093 if (!MI->isUsed())
1094 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1095
1096 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001097 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001098 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1099}
1100
1101
1102//===----------------------------------------------------------------------===//
1103// Preprocessor Conditional Directive Handling.
1104//===----------------------------------------------------------------------===//
1105
1106/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1107/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1108/// if any tokens have been returned or pp-directives activated before this
1109/// #ifndef has been lexed.
1110///
1111void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1112 bool ReadAnyTokensBeforeDirective) {
1113 ++NumIf;
1114 Token DirectiveTok = Result;
1115
1116 Token MacroNameTok;
1117 ReadMacroName(MacroNameTok);
1118
1119 // Error reading macro name? If so, diagnostic already issued.
1120 if (MacroNameTok.is(tok::eom)) {
1121 // Skip code until we get to #endif. This helps with recovery by not
1122 // emitting an error when the #endif is reached.
1123 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1124 /*Foundnonskip*/false, /*FoundElse*/false);
1125 return;
1126 }
1127
1128 // Check to see if this is the last token on the #if[n]def line.
1129 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1130
Ted Kremenek60e45d42008-11-18 00:34:22 +00001131 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001132 // If the start of a top-level #ifdef, inform MIOpt.
1133 if (!ReadAnyTokensBeforeDirective) {
1134 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001135 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001136 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001137 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001138 }
1139
1140 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1141 MacroInfo *MI = getMacroInfo(MII);
1142
1143 // If there is a macro, process it.
1144 if (MI) // Mark it used.
1145 MI->setIsUsed(true);
1146
1147 // Should we include the stuff contained by this directive?
1148 if (!MI == isIfndef) {
1149 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001150 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001151 /*foundnonskip*/true, /*foundelse*/false);
1152 } else {
1153 // No, skip the contents of this block and return the first token after it.
1154 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1155 /*Foundnonskip*/false,
1156 /*FoundElse*/false);
1157 }
1158}
1159
1160/// HandleIfDirective - Implements the #if directive.
1161///
1162void Preprocessor::HandleIfDirective(Token &IfToken,
1163 bool ReadAnyTokensBeforeDirective) {
1164 ++NumIf;
1165
1166 // Parse and evaluation the conditional expression.
1167 IdentifierInfo *IfNDefMacro = 0;
1168 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1169
Nuno Lopes0049db62008-06-01 18:31:24 +00001170
1171 // If this condition is equivalent to #ifndef X, and if this is the first
1172 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001173 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001174 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001175 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001176 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001177 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001178 }
1179
Chris Lattner141e71f2008-03-09 01:54:53 +00001180 // Should we include the stuff contained by this directive?
1181 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001182 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001183 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001184 /*foundnonskip*/true, /*foundelse*/false);
1185 } else {
1186 // No, skip the contents of this block and return the first token after it.
1187 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1188 /*FoundElse*/false);
1189 }
1190}
1191
1192/// HandleEndifDirective - Implements the #endif directive.
1193///
1194void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1195 ++NumEndif;
1196
1197 // Check that this is the whole directive.
1198 CheckEndOfDirective("#endif");
1199
1200 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001201 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001202 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001203 Diag(EndifToken, diag::err_pp_endif_without_if);
1204 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001205 }
1206
1207 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001208 if (CurPPLexer->getConditionalStackDepth() == 0)
1209 CurPPLexer->MIOpt.ExitTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001210
Ted Kremenek60e45d42008-11-18 00:34:22 +00001211 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001212 "This code should only be reachable in the non-skipping case!");
1213}
1214
1215
1216void Preprocessor::HandleElseDirective(Token &Result) {
1217 ++NumElse;
1218
1219 // #else directive in a non-skipping conditional... start skipping.
1220 CheckEndOfDirective("#else");
1221
1222 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001223 if (CurPPLexer->popConditionalLevel(CI)) {
1224 Diag(Result, diag::pp_err_else_without_if);
1225 return;
1226 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001227
1228 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001229 if (CurPPLexer->getConditionalStackDepth() == 0)
1230 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001231
1232 // If this is a #else with a #else before it, report the error.
1233 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1234
1235 // Finally, skip the rest of the contents of this block and return the first
1236 // token after it.
1237 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1238 /*FoundElse*/true);
1239}
1240
1241void Preprocessor::HandleElifDirective(Token &ElifToken) {
1242 ++NumElse;
1243
1244 // #elif directive in a non-skipping conditional... start skipping.
1245 // We don't care what the condition is, because we will always skip it (since
1246 // the block immediately before it was included).
1247 DiscardUntilEndOfDirective();
1248
1249 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001250 if (CurPPLexer->popConditionalLevel(CI)) {
1251 Diag(ElifToken, diag::pp_err_elif_without_if);
1252 return;
1253 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001254
1255 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001256 if (CurPPLexer->getConditionalStackDepth() == 0)
1257 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001258
1259 // If this is a #elif with a #else before it, report the error.
1260 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1261
1262 // Finally, skip the rest of the contents of this block and return the first
1263 // token after it.
1264 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1265 /*FoundElse*/CI.FoundElse);
1266}
1267