blob: 5797b12ebc81216f95ab4a01edc9f0ca85af2fc5 [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"
Chris Lattner359cc442009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000019#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000020#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000021using namespace clang;
22
23//===----------------------------------------------------------------------===//
24// Utility Methods for Preprocessor Directive Handling.
25//===----------------------------------------------------------------------===//
26
Chris Lattner0301b3f2009-02-20 22:19:20 +000027MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
Ted Kremenek0ea76722008-12-15 19:56:42 +000028 MacroInfo *MI;
29
30 if (!MICache.empty()) {
31 MI = MICache.back();
32 MICache.pop_back();
Chris Lattner0301b3f2009-02-20 22:19:20 +000033 } else
34 MI = (MacroInfo*) BP.Allocate<MacroInfo>();
Ted Kremenek0ea76722008-12-15 19:56:42 +000035 new (MI) MacroInfo(L);
36 return MI;
37}
38
Chris Lattner0301b3f2009-02-20 22:19:20 +000039/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
40/// be reused for allocating new MacroInfo objects.
41void Preprocessor::ReleaseMacroInfo(MacroInfo* MI) {
42 MICache.push_back(MI);
Chris Lattner685befe2009-02-20 22:46:43 +000043 MI->FreeArgumentList(BP);
Chris Lattner0301b3f2009-02-20 22:19:20 +000044}
45
46
Chris Lattner141e71f2008-03-09 01:54:53 +000047/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
48/// current line until the tok::eom token is found.
49void Preprocessor::DiscardUntilEndOfDirective() {
50 Token Tmp;
51 do {
52 LexUnexpandedToken(Tmp);
53 } while (Tmp.isNot(tok::eom));
54}
55
Chris Lattner141e71f2008-03-09 01:54:53 +000056/// ReadMacroName - Lex and validate a macro name, which occurs after a
57/// #define or #undef. This sets the token kind to eom and discards the rest
58/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
59/// this is due to a a #define, 2 if #undef directive, 0 if it is something
60/// else (e.g. #ifdef).
61void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
62 // Read the token, don't allow macro expansion on it.
63 LexUnexpandedToken(MacroNameTok);
64
65 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000066 if (MacroNameTok.is(tok::eom)) {
67 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
68 return;
69 }
Chris Lattner141e71f2008-03-09 01:54:53 +000070
71 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
72 if (II == 0) {
73 std::string Spelling = getSpelling(MacroNameTok);
Chris Lattner9485d232008-12-13 20:12:40 +000074 const IdentifierInfo &Info = Identifiers.get(Spelling);
75 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +000076 // C++ 2.5p2: Alternative tokens behave the same as its primary token
77 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +000078 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000079 else
80 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
81 // Fall through on error.
82 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
83 // Error if defining "defined": C99 6.10.8.4.
84 Diag(MacroNameTok, diag::err_defined_macro_name);
85 } else if (isDefineUndef && II->hasMacroDefinition() &&
86 getMacroInfo(II)->isBuiltinMacro()) {
87 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
88 if (isDefineUndef == 1)
89 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
90 else
91 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
92 } else {
93 // Okay, we got a good identifier node. Return it.
94 return;
95 }
96
97 // Invalid macro name, read and discard the rest of the line. Then set the
98 // token kind to tok::eom.
99 MacroNameTok.setKind(tok::eom);
100 return DiscardUntilEndOfDirective();
101}
102
103/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
104/// not, emit a diagnostic and consume up until the eom.
105void Preprocessor::CheckEndOfDirective(const char *DirType) {
106 Token Tmp;
107 // Lex unexpanded tokens: macros might expand to zero tokens, causing us to
108 // miss diagnosing invalid lines.
109 LexUnexpandedToken(Tmp);
110
111 // There should be no tokens after the directive, but we allow them as an
112 // extension.
113 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
114 LexUnexpandedToken(Tmp);
115
116 if (Tmp.isNot(tok::eom)) {
Chris Lattner56b05c82008-11-18 08:02:48 +0000117 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType;
Chris Lattner141e71f2008-03-09 01:54:53 +0000118 DiscardUntilEndOfDirective();
119 }
120}
121
122
123
124/// SkipExcludedConditionalBlock - We just read a #if or related directive and
125/// decided that the subsequent tokens are in the #if'd out portion of the
126/// file. Lex the rest of the file, until we see an #endif. If
127/// FoundNonSkipPortion is true, then we have already emitted code for part of
128/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
129/// is true, then #else directives are ok, if not, then we have already seen one
130/// so a #else directive is a duplicate. When this returns, the caller can lex
131/// the first valid token.
132void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
133 bool FoundNonSkipPortion,
134 bool FoundElse) {
135 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000136 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000137
Ted Kremenek60e45d42008-11-18 00:34:22 +0000138 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000139 FoundNonSkipPortion, FoundElse);
140
Ted Kremenek268ee702008-12-12 18:34:08 +0000141 if (CurPTHLexer) {
142 PTHSkipExcludedConditionalBlock();
143 return;
144 }
145
Chris Lattner141e71f2008-03-09 01:54:53 +0000146 // Enter raw mode to disable identifier lookup (and thus macro expansion),
147 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000148 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000149 Token Tok;
150 while (1) {
Ted Kremenekf6452c52008-11-18 01:04:47 +0000151 if (CurLexer)
152 CurLexer->Lex(Tok);
153 else
154 CurPTHLexer->Lex(Tok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000155
156 // If this is the end of the buffer, we have an error.
157 if (Tok.is(tok::eof)) {
158 // Emit errors for each unterminated conditional on the stack, including
159 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000160 while (!CurPPLexer->ConditionalStack.empty()) {
161 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000162 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000163 CurPPLexer->ConditionalStack.pop_back();
Chris Lattner141e71f2008-03-09 01:54:53 +0000164 }
165
166 // Just return and let the caller lex after this #include.
167 break;
168 }
169
170 // If this token is not a preprocessor directive, just skip it.
171 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
172 continue;
173
174 // We just parsed a # character at the start of a line, so we're in
175 // directive mode. Tell the lexer this so any newlines we see will be
176 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000177 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000178 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000179
180
181 // Read the next token, the directive flavor.
182 LexUnexpandedToken(Tok);
183
184 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
185 // something bogus), skip it.
186 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000187 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000188 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000189 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000190 continue;
191 }
192
193 // If the first letter isn't i or e, it isn't intesting to us. We know that
194 // this is safe in the face of spelling differences, because there is no way
195 // to spell an i/e in a strange way that is another letter. Skipping this
196 // allows us to avoid looking up the identifier info for #define/#undef and
197 // other common directives.
198 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
199 char FirstChar = RawCharData[0];
200 if (FirstChar >= 'a' && FirstChar <= 'z' &&
201 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000202 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000203 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000204 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000205 continue;
206 }
207
208 // Get the identifier name without trigraphs or embedded newlines. Note
209 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
210 // when skipping.
211 // TODO: could do this with zero copies in the no-clean case by using
212 // strncmp below.
213 char Directive[20];
214 unsigned IdLen;
215 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
216 IdLen = Tok.getLength();
217 memcpy(Directive, RawCharData, IdLen);
218 Directive[IdLen] = 0;
219 } else {
220 std::string DirectiveStr = getSpelling(Tok);
221 IdLen = DirectiveStr.size();
222 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000223 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000224 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000225 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000226 continue;
227 }
228 memcpy(Directive, &DirectiveStr[0], IdLen);
229 Directive[IdLen] = 0;
Chris Lattner202fd2c2009-01-27 05:34:03 +0000230 FirstChar = Directive[0];
Chris Lattner141e71f2008-03-09 01:54:53 +0000231 }
232
233 if (FirstChar == 'i' && Directive[1] == 'f') {
234 if ((IdLen == 2) || // "if"
235 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
236 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
237 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
238 // bother parsing the condition.
239 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000240 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000241 /*foundnonskip*/false,
242 /*fnddelse*/false);
243 }
244 } else if (FirstChar == 'e') {
245 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
246 CheckEndOfDirective("#endif");
247 PPConditionalInfo CondInfo;
248 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000249 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000250 InCond = InCond; // Silence warning in no-asserts mode.
251 assert(!InCond && "Can't be skipping if not in a conditional!");
252
253 // If we popped the outermost skipping block, we're done skipping!
254 if (!CondInfo.WasSkipping)
255 break;
256 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
257 // #else directive in a skipping conditional. If not in some other
258 // skipping conditional, and if #else hasn't already been seen, enter it
259 // as a non-skipping conditional.
260 CheckEndOfDirective("#else");
Ted Kremenek60e45d42008-11-18 00:34:22 +0000261 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000262
263 // If this is a #else with a #else before it, report the error.
264 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
265
266 // Note that we've seen a #else in this conditional.
267 CondInfo.FoundElse = true;
268
269 // If the conditional is at the top level, and the #if block wasn't
270 // entered, enter the #else block now.
271 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
272 CondInfo.FoundNonSkip = true;
273 break;
274 }
275 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000276 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000277
278 bool ShouldEnter;
279 // If this is in a skipping block or if we're already handled this #if
280 // block, don't bother parsing the condition.
281 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
282 DiscardUntilEndOfDirective();
283 ShouldEnter = false;
284 } else {
285 // Restore the value of LexingRawMode so that identifiers are
286 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000287 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
288 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000289 IdentifierInfo *IfNDefMacro = 0;
290 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000291 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000292 }
293
294 // If this is a #elif with a #else before it, report the error.
295 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
296
297 // If this condition is true, enter it!
298 if (ShouldEnter) {
299 CondInfo.FoundNonSkip = true;
300 break;
301 }
302 }
303 }
304
Ted Kremenek60e45d42008-11-18 00:34:22 +0000305 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000306 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000307 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000308 }
309
310 // Finally, if we are out of the conditional (saw an #endif or ran off the end
311 // of the file, just stop skipping and return to lexing whatever came after
312 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000313 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000314}
315
Ted Kremenek268ee702008-12-12 18:34:08 +0000316void Preprocessor::PTHSkipExcludedConditionalBlock() {
317
318 while(1) {
319 assert(CurPTHLexer);
320 assert(CurPTHLexer->LexingRawMode == false);
321
322 // Skip to the next '#else', '#elif', or #endif.
323 if (CurPTHLexer->SkipBlock()) {
324 // We have reached an #endif. Both the '#' and 'endif' tokens
325 // have been consumed by the PTHLexer. Just pop off the condition level.
326 PPConditionalInfo CondInfo;
327 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
328 InCond = InCond; // Silence warning in no-asserts mode.
329 assert(!InCond && "Can't be skipping if not in a conditional!");
330 break;
331 }
332
333 // We have reached a '#else' or '#elif'. Lex the next token to get
334 // the directive flavor.
335 Token Tok;
336 LexUnexpandedToken(Tok);
337
338 // We can actually look up the IdentifierInfo here since we aren't in
339 // raw mode.
340 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
341
342 if (K == tok::pp_else) {
343 // #else: Enter the else condition. We aren't in a nested condition
344 // since we skip those. We're always in the one matching the last
345 // blocked we skipped.
346 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
347 // Note that we've seen a #else in this conditional.
348 CondInfo.FoundElse = true;
349
350 // If the #if block wasn't entered then enter the #else block now.
351 if (!CondInfo.FoundNonSkip) {
352 CondInfo.FoundNonSkip = true;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000353
354 // Consume the eom token.
355 CurPTHLexer->ParsingPreprocessorDirective = true;
356 LexUnexpandedToken(Tok);
357 assert(Tok.is(tok::eom));
358 CurPTHLexer->ParsingPreprocessorDirective = false;
359
Ted Kremenek268ee702008-12-12 18:34:08 +0000360 break;
361 }
362
363 // Otherwise skip this block.
364 continue;
365 }
366
367 assert(K == tok::pp_elif);
368 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
369
370 // If this is a #elif with a #else before it, report the error.
371 if (CondInfo.FoundElse)
372 Diag(Tok, diag::pp_err_elif_after_else);
373
374 // If this is in a skipping block or if we're already handled this #if
375 // block, don't bother parsing the condition. We just skip this block.
376 if (CondInfo.FoundNonSkip)
377 continue;
378
379 // Evaluate the condition of the #elif.
380 IdentifierInfo *IfNDefMacro = 0;
381 CurPTHLexer->ParsingPreprocessorDirective = true;
382 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
383 CurPTHLexer->ParsingPreprocessorDirective = false;
384
385 // If this condition is true, enter it!
386 if (ShouldEnter) {
387 CondInfo.FoundNonSkip = true;
388 break;
389 }
390
391 // Otherwise, skip this block and go to the next one.
392 continue;
393 }
394}
395
Chris Lattner10725092008-03-09 04:17:44 +0000396/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
397/// return null on failure. isAngled indicates whether the file reference is
398/// for system #include's or not (i.e. using <> instead of "").
399const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
400 const char *FilenameEnd,
401 bool isAngled,
402 const DirectoryLookup *FromDir,
403 const DirectoryLookup *&CurDir) {
404 // If the header lookup mechanism may be relative to the current file, pass in
405 // info about where the current file is.
406 const FileEntry *CurFileEnt = 0;
407 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000408 FileID FID = getCurrentFileLexer()->getFileID();
409 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000410
411 // If there is no file entry associated with this file, it must be the
412 // predefines buffer. Any other file is not lexed with a normal lexer, so
413 // it won't be scanned for preprocessor directives. If we have the
414 // predefines buffer, resolve #include references (which come from the
415 // -include command line argument) as if they came from the main file, this
416 // affects file lookup etc.
417 if (CurFileEnt == 0) {
418 FID = SourceMgr.getMainFileID();
419 CurFileEnt = SourceMgr.getFileEntryForID(FID);
420 }
Chris Lattner10725092008-03-09 04:17:44 +0000421 }
422
423 // Do a standard file entry lookup.
424 CurDir = CurDirLookup;
425 const FileEntry *FE =
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000426 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
427 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner10725092008-03-09 04:17:44 +0000428 if (FE) return FE;
429
430 // Otherwise, see if this is a subframework header. If so, this is relative
431 // to one of the headers on the #include stack. Walk the list of the current
432 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000433 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000434 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000435 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
436 CurFileEnt)))
437 return FE;
438 }
439
440 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
441 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000442 if (IsFileLexer(ISEntry)) {
Chris Lattner10725092008-03-09 04:17:44 +0000443 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000444 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000445 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
446 FilenameEnd, CurFileEnt)))
447 return FE;
448 }
449 }
450
451 // Otherwise, we really couldn't find the file.
452 return 0;
453}
454
Chris Lattner141e71f2008-03-09 01:54:53 +0000455
456//===----------------------------------------------------------------------===//
457// Preprocessor Directive Handling.
458//===----------------------------------------------------------------------===//
459
460/// HandleDirective - This callback is invoked when the lexer sees a # token
461/// at the start of a line. This consumes the directive, modifies the
462/// lexer/preprocessor state, and advances the lexer(s) so that the next token
463/// read is the correct one.
464void Preprocessor::HandleDirective(Token &Result) {
465 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
466
467 // We just parsed a # character at the start of a line, so we're in directive
468 // mode. Tell the lexer this so any newlines we see will be converted into an
469 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000470 CurPPLexer->ParsingPreprocessorDirective = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000471
472 ++NumDirectives;
473
474 // We are about to read a token. For the multiple-include optimization FA to
475 // work, we have to remember if we had read any tokens *before* this
476 // pp-directive.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000477 bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Chris Lattner141e71f2008-03-09 01:54:53 +0000478
Chris Lattner42aa16c2009-03-18 21:00:25 +0000479 // Save the '#' token in case we need to return it later.
480 Token SavedHash = Result;
481
Chris Lattner141e71f2008-03-09 01:54:53 +0000482 // Read the next token, the directive flavor. This isn't expanded due to
483 // C99 6.10.3p8.
484 LexUnexpandedToken(Result);
485
486 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
487 // #define A(x) #x
488 // A(abc
489 // #warning blah
490 // def)
491 // If so, the user is relying on non-portable behavior, emit a diagnostic.
492 if (InMacroArgs)
493 Diag(Result, diag::ext_embedded_directive);
494
495TryAgain:
496 switch (Result.getKind()) {
497 case tok::eom:
498 return; // null directive.
499 case tok::comment:
500 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
501 LexUnexpandedToken(Result);
502 goto TryAgain;
503
Chris Lattner478a18e2009-01-26 06:19:46 +0000504 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000505 if (getLangOptions().AsmPreprocessor)
506 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000507 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000508 default:
509 IdentifierInfo *II = Result.getIdentifierInfo();
510 if (II == 0) break; // Not an identifier.
511
512 // Ask what the preprocessor keyword ID is.
513 switch (II->getPPKeywordID()) {
514 default: break;
515 // C99 6.10.1 - Conditional Inclusion.
516 case tok::pp_if:
517 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
518 case tok::pp_ifdef:
519 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
520 case tok::pp_ifndef:
521 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
522 case tok::pp_elif:
523 return HandleElifDirective(Result);
524 case tok::pp_else:
525 return HandleElseDirective(Result);
526 case tok::pp_endif:
527 return HandleEndifDirective(Result);
528
529 // C99 6.10.2 - Source File Inclusion.
530 case tok::pp_include:
531 return HandleIncludeDirective(Result); // Handle #include.
532
533 // C99 6.10.3 - Macro Replacement.
534 case tok::pp_define:
535 return HandleDefineDirective(Result);
536 case tok::pp_undef:
537 return HandleUndefDirective(Result);
538
539 // C99 6.10.4 - Line Control.
540 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000541 return HandleLineDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000542
543 // C99 6.10.5 - Error Directive.
544 case tok::pp_error:
545 return HandleUserDiagnosticDirective(Result, false);
546
547 // C99 6.10.6 - Pragma Directive.
548 case tok::pp_pragma:
549 return HandlePragmaDirective();
550
551 // GNU Extensions.
552 case tok::pp_import:
553 return HandleImportDirective(Result);
554 case tok::pp_include_next:
555 return HandleIncludeNextDirective(Result);
556
557 case tok::pp_warning:
558 Diag(Result, diag::ext_pp_warning_directive);
559 return HandleUserDiagnosticDirective(Result, true);
560 case tok::pp_ident:
561 return HandleIdentSCCSDirective(Result);
562 case tok::pp_sccs:
563 return HandleIdentSCCSDirective(Result);
564 case tok::pp_assert:
565 //isExtension = true; // FIXME: implement #assert
566 break;
567 case tok::pp_unassert:
568 //isExtension = true; // FIXME: implement #unassert
569 break;
570 }
571 break;
572 }
573
Chris Lattner42aa16c2009-03-18 21:00:25 +0000574 // If this is a .S file, treat unknown # directives as non-preprocessor
575 // directives. This is important because # may be a comment or introduce
576 // various pseudo-ops. Just return the # token and push back the following
577 // token to be lexed next time.
578 if (getLangOptions().AsmPreprocessor) {
579 Token *Toks = new Token[2]();
580 // Return the # and the token after it.
581 Toks[0] = SavedHash;
582 Toks[1] = Result;
583 // Enter this token stream so that we re-lex the tokens. Make sure to
584 // enable macro expansion, in case the token after the # is an identifier
585 // that is expanded.
586 EnterTokenStream(Toks, 2, false, true);
587 return;
588 }
589
Chris Lattner141e71f2008-03-09 01:54:53 +0000590 // If we reached here, the preprocessing token is not valid!
591 Diag(Result, diag::err_pp_invalid_directive);
592
593 // Read the rest of the PP line.
594 DiscardUntilEndOfDirective();
595
596 // Okay, we're done parsing the directive.
597}
598
Chris Lattner478a18e2009-01-26 06:19:46 +0000599/// GetLineValue - Convert a numeric token into an unsigned value, emitting
600/// Diagnostic DiagID if it is invalid, and returning the value in Val.
601static bool GetLineValue(Token &DigitTok, unsigned &Val,
602 unsigned DiagID, Preprocessor &PP) {
603 if (DigitTok.isNot(tok::numeric_constant)) {
604 PP.Diag(DigitTok, DiagID);
605
606 if (DigitTok.isNot(tok::eom))
607 PP.DiscardUntilEndOfDirective();
608 return true;
609 }
610
611 llvm::SmallString<64> IntegerBuffer;
612 IntegerBuffer.resize(DigitTok.getLength());
613 const char *DigitTokBegin = &IntegerBuffer[0];
614 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
615 NumericLiteralParser Literal(DigitTokBegin, DigitTokBegin+ActualLength,
616 DigitTok.getLocation(), PP);
617 if (Literal.hadError)
618 return true; // Error already emitted.
619
620 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
621 PP.Diag(DigitTok, DiagID);
622 return true;
623 }
624
625 // Parse the integer literal into Result.
626 llvm::APInt APVal(32, 0);
627 if (Literal.GetIntegerValue(APVal)) {
628 // Overflow parsing integer literal.
629 PP.Diag(DigitTok, DiagID);
630 return true;
631 }
632 Val = APVal.getZExtValue();
633
634 // Reject 0, this is needed both by #line numbers and flags.
635 if (Val == 0) {
636 PP.Diag(DigitTok, DiagID);
637 PP.DiscardUntilEndOfDirective();
638 return true;
639 }
640
641 return false;
642}
643
Chris Lattner359cc442009-01-26 05:29:08 +0000644/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
645/// acceptable forms are:
646/// # line digit-sequence
647/// # line digit-sequence "s-char-sequence"
648void Preprocessor::HandleLineDirective(Token &Tok) {
649 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
650 // expanded.
651 Token DigitTok;
652 Lex(DigitTok);
653
Chris Lattner359cc442009-01-26 05:29:08 +0000654 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000655 unsigned LineNo;
656 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer, *this))
Chris Lattner359cc442009-01-26 05:29:08 +0000657 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000658
Chris Lattner478a18e2009-01-26 06:19:46 +0000659 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
660 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000661 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
662 if (LineNo >= LineLimit)
663 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
664
Chris Lattner5b9a5042009-01-26 07:57:50 +0000665 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000666 Token StrTok;
667 Lex(StrTok);
668
669 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
670 // string followed by eom.
671 if (StrTok.is(tok::eom))
672 ; // ok
673 else if (StrTok.isNot(tok::string_literal)) {
674 Diag(StrTok, diag::err_pp_line_invalid_filename);
675 DiscardUntilEndOfDirective();
676 return;
677 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000678 // Parse and validate the string, converting it into a unique ID.
679 StringLiteralParser Literal(&StrTok, 1, *this);
680 assert(!Literal.AnyWide && "Didn't allow wide strings in");
681 if (Literal.hadError)
682 return DiscardUntilEndOfDirective();
683 if (Literal.Pascal) {
684 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
685 return DiscardUntilEndOfDirective();
686 }
687 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
688 Literal.GetStringLength());
689
Chris Lattner359cc442009-01-26 05:29:08 +0000690 // Verify that there is nothing after the string, other than EOM.
691 CheckEndOfDirective("#line");
692 }
693
Chris Lattner4c4ea172009-02-03 21:52:55 +0000694 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Chris Lattner359cc442009-01-26 05:29:08 +0000695}
696
Chris Lattner478a18e2009-01-26 06:19:46 +0000697/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
698/// marker directive.
699static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
700 bool &IsSystemHeader, bool &IsExternCHeader,
701 Preprocessor &PP) {
702 unsigned FlagVal;
703 Token FlagTok;
704 PP.Lex(FlagTok);
705 if (FlagTok.is(tok::eom)) return false;
706 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
707 return true;
708
709 if (FlagVal == 1) {
710 IsFileEntry = true;
711
712 PP.Lex(FlagTok);
713 if (FlagTok.is(tok::eom)) return false;
714 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
715 return true;
716 } else if (FlagVal == 2) {
717 IsFileExit = true;
718
Chris Lattner137b6a62009-02-04 06:25:26 +0000719 SourceManager &SM = PP.getSourceManager();
720 // If we are leaving the current presumed file, check to make sure the
721 // presumed include stack isn't empty!
722 FileID CurFileID =
723 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
724 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
725
726 // If there is no include loc (main file) or if the include loc is in a
727 // different physical file, then we aren't in a "1" line marker flag region.
728 SourceLocation IncLoc = PLoc.getIncludeLoc();
729 if (IncLoc.isInvalid() ||
730 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
731 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
732 PP.DiscardUntilEndOfDirective();
733 return true;
734 }
735
Chris Lattner478a18e2009-01-26 06:19:46 +0000736 PP.Lex(FlagTok);
737 if (FlagTok.is(tok::eom)) return false;
738 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
739 return true;
740 }
741
742 // We must have 3 if there are still flags.
743 if (FlagVal != 3) {
744 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000745 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000746 return true;
747 }
748
749 IsSystemHeader = true;
750
751 PP.Lex(FlagTok);
752 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000753 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000754 return true;
755
756 // We must have 4 if there is yet another flag.
757 if (FlagVal != 4) {
758 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000759 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000760 return true;
761 }
762
763 IsExternCHeader = true;
764
765 PP.Lex(FlagTok);
766 if (FlagTok.is(tok::eom)) return false;
767
768 // There are no more valid flags here.
769 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000770 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000771 return true;
772}
773
774/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
775/// one of the following forms:
776///
777/// # 42
778/// # 42 "file" ('1' | '2')?
779/// # 42 "file" ('1' | '2')? '3' '4'?
780///
781void Preprocessor::HandleDigitDirective(Token &DigitTok) {
782 // Validate the number and convert it to an unsigned. GNU does not have a
783 // line # limit other than it fit in 32-bits.
784 unsigned LineNo;
785 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
786 *this))
787 return;
788
789 Token StrTok;
790 Lex(StrTok);
791
792 bool IsFileEntry = false, IsFileExit = false;
793 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000794 int FilenameID = -1;
795
Chris Lattner478a18e2009-01-26 06:19:46 +0000796 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
797 // string followed by eom.
798 if (StrTok.is(tok::eom))
799 ; // ok
800 else if (StrTok.isNot(tok::string_literal)) {
801 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000802 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000803 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000804 // Parse and validate the string, converting it into a unique ID.
805 StringLiteralParser Literal(&StrTok, 1, *this);
806 assert(!Literal.AnyWide && "Didn't allow wide strings in");
807 if (Literal.hadError)
808 return DiscardUntilEndOfDirective();
809 if (Literal.Pascal) {
810 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
811 return DiscardUntilEndOfDirective();
812 }
813 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
814 Literal.GetStringLength());
815
Chris Lattner478a18e2009-01-26 06:19:46 +0000816 // If a filename was present, read any flags that are present.
817 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000818 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000819 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000820 }
Chris Lattner137b6a62009-02-04 06:25:26 +0000821
Chris Lattner9d79eba2009-02-04 05:21:58 +0000822 // Create a line note with this information.
823 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
824 IsFileEntry, IsFileExit,
825 IsSystemHeader, IsExternCHeader);
Chris Lattner478a18e2009-01-26 06:19:46 +0000826}
827
828
Chris Lattner099dd052009-01-26 05:30:54 +0000829/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
830///
Chris Lattner141e71f2008-03-09 01:54:53 +0000831void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
832 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000833 // PTH doesn't emit #warning or #error directives.
834 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000835 return CurPTHLexer->DiscardToEndOfLine();
836
Chris Lattner141e71f2008-03-09 01:54:53 +0000837 // Read the rest of the line raw. We do this because we don't want macros
838 // to be expanded and we don't require that the tokens be valid preprocessing
839 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
840 // collapse multiple consequtive white space between tokens, but this isn't
841 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000842 std::string Message = CurLexer->ReadToEndOfLine();
843 if (isWarning)
844 Diag(Tok, diag::pp_hash_warning) << Message;
845 else
846 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000847}
848
849/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
850///
851void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
852 // Yes, this directive is an extension.
853 Diag(Tok, diag::ext_pp_ident_directive);
854
855 // Read the string argument.
856 Token StrTok;
857 Lex(StrTok);
858
859 // If the token kind isn't a string, it's a malformed directive.
860 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000861 StrTok.isNot(tok::wide_string_literal)) {
862 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000863 if (StrTok.isNot(tok::eom))
864 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000865 return;
866 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000867
868 // Verify that there is nothing after the string, other than EOM.
869 CheckEndOfDirective("#ident");
870
871 if (Callbacks)
872 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
873}
874
875//===----------------------------------------------------------------------===//
876// Preprocessor Include Directive Handling.
877//===----------------------------------------------------------------------===//
878
879/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
880/// checked and spelled filename, e.g. as an operand of #include. This returns
881/// true if the input filename was in <>'s or false if it were in ""'s. The
882/// caller is expected to provide a buffer that is large enough to hold the
883/// spelling of the filename, but is also expected to handle the case when
884/// this method decides to use a different buffer.
885bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
886 const char *&BufStart,
887 const char *&BufEnd) {
888 // Get the text form of the filename.
889 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
890
891 // Make sure the filename is <x> or "x".
892 bool isAngled;
893 if (BufStart[0] == '<') {
894 if (BufEnd[-1] != '>') {
895 Diag(Loc, diag::err_pp_expects_filename);
896 BufStart = 0;
897 return true;
898 }
899 isAngled = true;
900 } else if (BufStart[0] == '"') {
901 if (BufEnd[-1] != '"') {
902 Diag(Loc, diag::err_pp_expects_filename);
903 BufStart = 0;
904 return true;
905 }
906 isAngled = false;
907 } else {
908 Diag(Loc, diag::err_pp_expects_filename);
909 BufStart = 0;
910 return true;
911 }
912
913 // Diagnose #include "" as invalid.
914 if (BufEnd-BufStart <= 2) {
915 Diag(Loc, diag::err_pp_empty_filename);
916 BufStart = 0;
917 return "";
918 }
919
920 // Skip the brackets.
921 ++BufStart;
922 --BufEnd;
923 return isAngled;
924}
925
926/// ConcatenateIncludeName - Handle cases where the #include name is expanded
927/// from a macro as multiple tokens, which need to be glued together. This
928/// occurs for code like:
929/// #define FOO <a/b.h>
930/// #include FOO
931/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
932///
933/// This code concatenates and consumes tokens up to the '>' token. It returns
934/// false if the > was found, otherwise it returns true if it finds and consumes
935/// the EOM marker.
936static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
937 Preprocessor &PP) {
938 Token CurTok;
939
940 PP.Lex(CurTok);
941 while (CurTok.isNot(tok::eom)) {
942 // Append the spelling of this token to the buffer. If there was a space
943 // before it, add it now.
944 if (CurTok.hasLeadingSpace())
945 FilenameBuffer.push_back(' ');
946
947 // Get the spelling of the token, directly into FilenameBuffer if possible.
948 unsigned PreAppendSize = FilenameBuffer.size();
949 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
950
951 const char *BufPtr = &FilenameBuffer[PreAppendSize];
952 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
953
954 // If the token was spelled somewhere else, copy it into FilenameBuffer.
955 if (BufPtr != &FilenameBuffer[PreAppendSize])
956 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
957
958 // Resize FilenameBuffer to the correct size.
959 if (CurTok.getLength() != ActualLen)
960 FilenameBuffer.resize(PreAppendSize+ActualLen);
961
962 // If we found the '>' marker, return success.
963 if (CurTok.is(tok::greater))
964 return false;
965
966 PP.Lex(CurTok);
967 }
968
969 // If we hit the eom marker, emit an error and return true so that the caller
970 // knows the EOM has been read.
971 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
972 return true;
973}
974
975/// HandleIncludeDirective - The "#include" tokens have just been read, read the
976/// file to be included from the lexer, then include it! This is a common
977/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +0000978/// #import. LookupFrom is set when this is a #include_next directive, it
979/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +0000980void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
981 const DirectoryLookup *LookupFrom,
982 bool isImport) {
983
984 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +0000985 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000986
987 // Reserve a buffer to get the spelling.
988 llvm::SmallVector<char, 128> FilenameBuffer;
989 const char *FilenameStart, *FilenameEnd;
990
991 switch (FilenameTok.getKind()) {
992 case tok::eom:
993 // If the token kind is EOM, the error has already been diagnosed.
994 return;
995
996 case tok::angle_string_literal:
997 case tok::string_literal: {
998 FilenameBuffer.resize(FilenameTok.getLength());
999 FilenameStart = &FilenameBuffer[0];
1000 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1001 FilenameEnd = FilenameStart+Len;
1002 break;
1003 }
1004
1005 case tok::less:
1006 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1007 // case, glue the tokens together into FilenameBuffer and interpret those.
1008 FilenameBuffer.push_back('<');
1009 if (ConcatenateIncludeName(FilenameBuffer, *this))
1010 return; // Found <eom> but no ">"? Diagnostic already emitted.
1011 FilenameStart = &FilenameBuffer[0];
1012 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1013 break;
1014 default:
1015 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1016 DiscardUntilEndOfDirective();
1017 return;
1018 }
1019
1020 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
1021 FilenameStart, FilenameEnd);
1022 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1023 // error.
1024 if (FilenameStart == 0) {
1025 DiscardUntilEndOfDirective();
1026 return;
1027 }
1028
1029 // Verify that there is nothing after the filename, other than EOM. Use the
1030 // preprocessor to lex this in case lexing the filename entered a macro.
1031 CheckEndOfDirective("#include");
1032
1033 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001034 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1035 Diag(FilenameTok, diag::err_pp_include_too_deep);
1036 return;
1037 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001038
1039 // Search include directories.
1040 const DirectoryLookup *CurDir;
1041 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1042 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001043 if (File == 0) {
1044 Diag(FilenameTok, diag::err_pp_file_not_found)
1045 << std::string(FilenameStart, FilenameEnd);
1046 return;
1047 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001048
Chris Lattner72181832008-09-26 20:12:23 +00001049 // Ask HeaderInfo if we should enter this #include file. If not, #including
1050 // this file will have no effect.
1051 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001052 return;
Chris Lattner72181832008-09-26 20:12:23 +00001053
1054 // The #included file will be considered to be a system header if either it is
1055 // in a system include directory, or if the #includer is a system include
1056 // header.
Chris Lattner9d728512008-10-27 01:19:25 +00001057 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001058 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001059 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Chris Lattner72181832008-09-26 20:12:23 +00001060
Chris Lattner141e71f2008-03-09 01:54:53 +00001061 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001062 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1063 FileCharacter);
1064 if (FID.isInvalid()) {
Chris Lattner56b05c82008-11-18 08:02:48 +00001065 Diag(FilenameTok, diag::err_pp_file_not_found)
1066 << std::string(FilenameStart, FilenameEnd);
1067 return;
1068 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001069
1070 // Finally, if all is good, enter the new file!
Chris Lattner2b2453a2009-01-17 06:22:33 +00001071 EnterSourceFile(FID, CurDir);
Chris Lattner141e71f2008-03-09 01:54:53 +00001072}
1073
1074/// HandleIncludeNextDirective - Implements #include_next.
1075///
1076void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1077 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1078
1079 // #include_next is like #include, except that we start searching after
1080 // the current found directory. If we can't do this, issue a
1081 // diagnostic.
1082 const DirectoryLookup *Lookup = CurDirLookup;
1083 if (isInPrimaryFile()) {
1084 Lookup = 0;
1085 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1086 } else if (Lookup == 0) {
1087 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1088 } else {
1089 // Start looking up in the next directory.
1090 ++Lookup;
1091 }
1092
1093 return HandleIncludeDirective(IncludeNextTok, Lookup);
1094}
1095
1096/// HandleImportDirective - Implements #import.
1097///
1098void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001099 if (!Features.ObjC1) // #import is standard for ObjC.
1100 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner141e71f2008-03-09 01:54:53 +00001101
1102 return HandleIncludeDirective(ImportTok, 0, true);
1103}
1104
1105//===----------------------------------------------------------------------===//
1106// Preprocessor Macro Directive Handling.
1107//===----------------------------------------------------------------------===//
1108
1109/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1110/// definition has just been read. Lex the rest of the arguments and the
1111/// closing ), updating MI with what we learn. Return true if an error occurs
1112/// parsing the arg list.
1113bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1114 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1115
1116 Token Tok;
1117 while (1) {
1118 LexUnexpandedToken(Tok);
1119 switch (Tok.getKind()) {
1120 case tok::r_paren:
1121 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001122 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001123 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001124 // Otherwise we have #define FOO(A,)
1125 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1126 return true;
1127 case tok::ellipsis: // #define X(... -> C99 varargs
1128 // Warn if use of C99 feature in non-C99 mode.
1129 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1130
1131 // Lex the token after the identifier.
1132 LexUnexpandedToken(Tok);
1133 if (Tok.isNot(tok::r_paren)) {
1134 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1135 return true;
1136 }
1137 // Add the __VA_ARGS__ identifier as an argument.
1138 Arguments.push_back(Ident__VA_ARGS__);
1139 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001140 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001141 return false;
1142 case tok::eom: // #define X(
1143 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1144 return true;
1145 default:
1146 // Handle keywords and identifiers here to accept things like
1147 // #define Foo(for) for.
1148 IdentifierInfo *II = Tok.getIdentifierInfo();
1149 if (II == 0) {
1150 // #define X(1
1151 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1152 return true;
1153 }
1154
1155 // If this is already used as an argument, it is used multiple times (e.g.
1156 // #define X(A,A.
1157 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1158 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001159 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001160 return true;
1161 }
1162
1163 // Add the argument to the macro info.
1164 Arguments.push_back(II);
1165
1166 // Lex the token after the identifier.
1167 LexUnexpandedToken(Tok);
1168
1169 switch (Tok.getKind()) {
1170 default: // #define X(A B
1171 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1172 return true;
1173 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001174 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001175 return false;
1176 case tok::comma: // #define X(A,
1177 break;
1178 case tok::ellipsis: // #define X(A... -> GCC extension
1179 // Diagnose extension.
1180 Diag(Tok, diag::ext_named_variadic_macro);
1181
1182 // Lex the token after the identifier.
1183 LexUnexpandedToken(Tok);
1184 if (Tok.isNot(tok::r_paren)) {
1185 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1186 return true;
1187 }
1188
1189 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001190 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001191 return false;
1192 }
1193 }
1194 }
1195}
1196
1197/// HandleDefineDirective - Implements #define. This consumes the entire macro
1198/// line then lets the caller lex the next real token.
1199void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1200 ++NumDefined;
1201
1202 Token MacroNameTok;
1203 ReadMacroName(MacroNameTok, 1);
1204
1205 // Error reading macro name? If so, diagnostic already issued.
1206 if (MacroNameTok.is(tok::eom))
1207 return;
1208
1209 // If we are supposed to keep comments in #defines, reenable comment saving
1210 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001211 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Chris Lattner141e71f2008-03-09 01:54:53 +00001212
1213 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001214 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001215
1216 Token Tok;
1217 LexUnexpandedToken(Tok);
1218
1219 // If this is a function-like macro definition, parse the argument list,
1220 // marking each of the identifiers as being used as macro arguments. Also,
1221 // check other constraints on the first token of the macro body.
1222 if (Tok.is(tok::eom)) {
1223 // If there is no body to this macro, we have no special handling here.
1224 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
1225 // This is a function-like macro definition. Read the argument list.
1226 MI->setIsFunctionLike();
1227 if (ReadMacroDefinitionArgList(MI)) {
1228 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001229 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001230 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001231 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001232 DiscardUntilEndOfDirective();
1233 return;
1234 }
1235
1236 // Read the first token after the arg list for down below.
1237 LexUnexpandedToken(Tok);
1238 } else if (!Tok.hasLeadingSpace()) {
1239 // C99 requires whitespace between the macro definition and the body. Emit
1240 // a diagnostic for something like "#define X+".
1241 if (Features.C99) {
1242 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1243 } else {
1244 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1245 // one in some cases!
1246 }
1247 } else {
1248 // This is a normal token with leading space. Clear the leading space
1249 // marker on the first token to get proper expansion.
1250 Tok.clearFlag(Token::LeadingSpace);
1251 }
1252
1253 // If this is a definition of a variadic C99 function-like macro, not using
1254 // the GNU named varargs extension, enabled __VA_ARGS__.
1255
1256 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1257 // This gets unpoisoned where it is allowed.
1258 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1259 if (MI->isC99Varargs())
1260 Ident__VA_ARGS__->setIsPoisoned(false);
1261
1262 // Read the rest of the macro body.
1263 if (MI->isObjectLike()) {
1264 // Object-like macros are very simple, just read their body.
1265 while (Tok.isNot(tok::eom)) {
1266 MI->AddTokenToBody(Tok);
1267 // Get the next token of the macro.
1268 LexUnexpandedToken(Tok);
1269 }
1270
1271 } else {
1272 // Otherwise, read the body of a function-like macro. This has to validate
1273 // the # (stringize) operator.
1274 while (Tok.isNot(tok::eom)) {
1275 MI->AddTokenToBody(Tok);
1276
1277 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1278 // parameters in function-like macro expansions.
1279 if (Tok.isNot(tok::hash)) {
1280 // Get the next token of the macro.
1281 LexUnexpandedToken(Tok);
1282 continue;
1283 }
1284
1285 // Get the next token of the macro.
1286 LexUnexpandedToken(Tok);
1287
1288 // Not a macro arg identifier?
1289 if (!Tok.getIdentifierInfo() ||
1290 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1291 Diag(Tok, diag::err_pp_stringize_not_parameter);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001292 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001293
1294 // Disable __VA_ARGS__ again.
1295 Ident__VA_ARGS__->setIsPoisoned(true);
1296 return;
1297 }
1298
1299 // Things look ok, add the param name token to the macro.
1300 MI->AddTokenToBody(Tok);
1301
1302 // Get the next token of the macro.
1303 LexUnexpandedToken(Tok);
1304 }
1305 }
1306
1307
1308 // Disable __VA_ARGS__ again.
1309 Ident__VA_ARGS__->setIsPoisoned(true);
1310
1311 // Check that there is no paste (##) operator at the begining or end of the
1312 // replacement list.
1313 unsigned NumTokens = MI->getNumTokens();
1314 if (NumTokens != 0) {
1315 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1316 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001317 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001318 return;
1319 }
1320 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1321 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001322 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001323 return;
1324 }
1325 }
1326
1327 // If this is the primary source file, remember that this macro hasn't been
1328 // used yet.
1329 if (isInPrimaryFile())
1330 MI->setIsUsed(false);
1331
1332 // Finally, if this identifier already had a macro defined for it, verify that
1333 // the macro bodies are identical and free the old definition.
1334 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001335 // It is very common for system headers to have tons of macro redefinitions
1336 // and for warnings to be disabled in system headers. If this is the case,
1337 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001338 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001339 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1340 if (!OtherMI->isUsed())
1341 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001342
Chris Lattner41c3ae12009-01-16 19:50:11 +00001343 // Macros must be identical. This means all tokes and whitespace
1344 // separation must be the same. C99 6.10.3.2.
1345 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1346 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1347 << MacroNameTok.getIdentifierInfo();
1348 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1349 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001350 }
Chris Lattner41c3ae12009-01-16 19:50:11 +00001351
Ted Kremenek0ea76722008-12-15 19:56:42 +00001352 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001353 }
1354
1355 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
1356}
1357
1358/// HandleUndefDirective - Implements #undef.
1359///
1360void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1361 ++NumUndefined;
1362
1363 Token MacroNameTok;
1364 ReadMacroName(MacroNameTok, 2);
1365
1366 // Error reading macro name? If so, diagnostic already issued.
1367 if (MacroNameTok.is(tok::eom))
1368 return;
1369
1370 // Check to see if this is the last token on the #undef line.
1371 CheckEndOfDirective("#undef");
1372
1373 // Okay, we finally have a valid identifier to undef.
1374 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1375
1376 // If the macro is not defined, this is a noop undef, just return.
1377 if (MI == 0) return;
1378
1379 if (!MI->isUsed())
1380 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1381
1382 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001383 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001384 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1385}
1386
1387
1388//===----------------------------------------------------------------------===//
1389// Preprocessor Conditional Directive Handling.
1390//===----------------------------------------------------------------------===//
1391
1392/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1393/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1394/// if any tokens have been returned or pp-directives activated before this
1395/// #ifndef has been lexed.
1396///
1397void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1398 bool ReadAnyTokensBeforeDirective) {
1399 ++NumIf;
1400 Token DirectiveTok = Result;
1401
1402 Token MacroNameTok;
1403 ReadMacroName(MacroNameTok);
1404
1405 // Error reading macro name? If so, diagnostic already issued.
1406 if (MacroNameTok.is(tok::eom)) {
1407 // Skip code until we get to #endif. This helps with recovery by not
1408 // emitting an error when the #endif is reached.
1409 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1410 /*Foundnonskip*/false, /*FoundElse*/false);
1411 return;
1412 }
1413
1414 // Check to see if this is the last token on the #if[n]def line.
1415 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1416
Ted Kremenek60e45d42008-11-18 00:34:22 +00001417 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001418 // If the start of a top-level #ifdef, inform MIOpt.
1419 if (!ReadAnyTokensBeforeDirective) {
1420 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001421 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001422 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001423 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001424 }
1425
1426 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1427 MacroInfo *MI = getMacroInfo(MII);
1428
1429 // If there is a macro, process it.
1430 if (MI) // Mark it used.
1431 MI->setIsUsed(true);
1432
1433 // Should we include the stuff contained by this directive?
1434 if (!MI == isIfndef) {
1435 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001436 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001437 /*foundnonskip*/true, /*foundelse*/false);
1438 } else {
1439 // No, skip the contents of this block and return the first token after it.
1440 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1441 /*Foundnonskip*/false,
1442 /*FoundElse*/false);
1443 }
1444}
1445
1446/// HandleIfDirective - Implements the #if directive.
1447///
1448void Preprocessor::HandleIfDirective(Token &IfToken,
1449 bool ReadAnyTokensBeforeDirective) {
1450 ++NumIf;
1451
1452 // Parse and evaluation the conditional expression.
1453 IdentifierInfo *IfNDefMacro = 0;
1454 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1455
Nuno Lopes0049db62008-06-01 18:31:24 +00001456
1457 // If this condition is equivalent to #ifndef X, and if this is the first
1458 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001459 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001460 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001461 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001462 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001463 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001464 }
1465
Chris Lattner141e71f2008-03-09 01:54:53 +00001466 // Should we include the stuff contained by this directive?
1467 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001468 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001469 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001470 /*foundnonskip*/true, /*foundelse*/false);
1471 } else {
1472 // No, skip the contents of this block and return the first token after it.
1473 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1474 /*FoundElse*/false);
1475 }
1476}
1477
1478/// HandleEndifDirective - Implements the #endif directive.
1479///
1480void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1481 ++NumEndif;
1482
1483 // Check that this is the whole directive.
1484 CheckEndOfDirective("#endif");
1485
1486 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001487 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001488 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001489 Diag(EndifToken, diag::err_pp_endif_without_if);
1490 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001491 }
1492
1493 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001494 if (CurPPLexer->getConditionalStackDepth() == 0)
1495 CurPPLexer->MIOpt.ExitTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001496
Ted Kremenek60e45d42008-11-18 00:34:22 +00001497 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001498 "This code should only be reachable in the non-skipping case!");
1499}
1500
1501
1502void Preprocessor::HandleElseDirective(Token &Result) {
1503 ++NumElse;
1504
1505 // #else directive in a non-skipping conditional... start skipping.
1506 CheckEndOfDirective("#else");
1507
1508 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001509 if (CurPPLexer->popConditionalLevel(CI)) {
1510 Diag(Result, diag::pp_err_else_without_if);
1511 return;
1512 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001513
1514 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001515 if (CurPPLexer->getConditionalStackDepth() == 0)
1516 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001517
1518 // If this is a #else with a #else before it, report the error.
1519 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1520
1521 // Finally, skip the rest of the contents of this block and return the first
1522 // token after it.
1523 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1524 /*FoundElse*/true);
1525}
1526
1527void Preprocessor::HandleElifDirective(Token &ElifToken) {
1528 ++NumElse;
1529
1530 // #elif directive in a non-skipping conditional... start skipping.
1531 // We don't care what the condition is, because we will always skip it (since
1532 // the block immediately before it was included).
1533 DiscardUntilEndOfDirective();
1534
1535 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001536 if (CurPPLexer->popConditionalLevel(CI)) {
1537 Diag(ElifToken, diag::pp_err_elif_without_if);
1538 return;
1539 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001540
1541 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001542 if (CurPPLexer->getConditionalStackDepth() == 0)
1543 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001544
1545 // If this is a #elif with a #else before it, report the error.
1546 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1547
1548 // Finally, skip the rest of the contents of this block and return the first
1549 // token after it.
1550 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1551 /*FoundElse*/CI.FoundElse);
1552}
1553