blob: 24b943254cff78db472a06603b9072a1c03a49cd [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
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000354 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000355 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000356 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000357 CurPTHLexer->ParsingPreprocessorDirective = false;
358
Ted Kremenek268ee702008-12-12 18:34:08 +0000359 break;
360 }
361
362 // Otherwise skip this block.
363 continue;
364 }
365
366 assert(K == tok::pp_elif);
367 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
368
369 // If this is a #elif with a #else before it, report the error.
370 if (CondInfo.FoundElse)
371 Diag(Tok, diag::pp_err_elif_after_else);
372
373 // If this is in a skipping block or if we're already handled this #if
374 // block, don't bother parsing the condition. We just skip this block.
375 if (CondInfo.FoundNonSkip)
376 continue;
377
378 // Evaluate the condition of the #elif.
379 IdentifierInfo *IfNDefMacro = 0;
380 CurPTHLexer->ParsingPreprocessorDirective = true;
381 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
382 CurPTHLexer->ParsingPreprocessorDirective = false;
383
384 // If this condition is true, enter it!
385 if (ShouldEnter) {
386 CondInfo.FoundNonSkip = true;
387 break;
388 }
389
390 // Otherwise, skip this block and go to the next one.
391 continue;
392 }
393}
394
Chris Lattner10725092008-03-09 04:17:44 +0000395/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
396/// return null on failure. isAngled indicates whether the file reference is
397/// for system #include's or not (i.e. using <> instead of "").
398const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
399 const char *FilenameEnd,
400 bool isAngled,
401 const DirectoryLookup *FromDir,
402 const DirectoryLookup *&CurDir) {
403 // If the header lookup mechanism may be relative to the current file, pass in
404 // info about where the current file is.
405 const FileEntry *CurFileEnt = 0;
406 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000407 FileID FID = getCurrentFileLexer()->getFileID();
408 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000409
410 // If there is no file entry associated with this file, it must be the
411 // predefines buffer. Any other file is not lexed with a normal lexer, so
412 // it won't be scanned for preprocessor directives. If we have the
413 // predefines buffer, resolve #include references (which come from the
414 // -include command line argument) as if they came from the main file, this
415 // affects file lookup etc.
416 if (CurFileEnt == 0) {
417 FID = SourceMgr.getMainFileID();
418 CurFileEnt = SourceMgr.getFileEntryForID(FID);
419 }
Chris Lattner10725092008-03-09 04:17:44 +0000420 }
421
422 // Do a standard file entry lookup.
423 CurDir = CurDirLookup;
424 const FileEntry *FE =
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000425 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
426 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner10725092008-03-09 04:17:44 +0000427 if (FE) return FE;
428
429 // Otherwise, see if this is a subframework header. If so, this is relative
430 // to one of the headers on the #include stack. Walk the list of the current
431 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000432 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000433 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000434 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
435 CurFileEnt)))
436 return FE;
437 }
438
439 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
440 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000441 if (IsFileLexer(ISEntry)) {
Chris Lattner10725092008-03-09 04:17:44 +0000442 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000443 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000444 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
445 FilenameEnd, CurFileEnt)))
446 return FE;
447 }
448 }
449
450 // Otherwise, we really couldn't find the file.
451 return 0;
452}
453
Chris Lattner141e71f2008-03-09 01:54:53 +0000454
455//===----------------------------------------------------------------------===//
456// Preprocessor Directive Handling.
457//===----------------------------------------------------------------------===//
458
459/// HandleDirective - This callback is invoked when the lexer sees a # token
460/// at the start of a line. This consumes the directive, modifies the
461/// lexer/preprocessor state, and advances the lexer(s) so that the next token
462/// read is the correct one.
463void Preprocessor::HandleDirective(Token &Result) {
464 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
465
466 // We just parsed a # character at the start of a line, so we're in directive
467 // mode. Tell the lexer this so any newlines we see will be converted into an
468 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000469 CurPPLexer->ParsingPreprocessorDirective = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000470
471 ++NumDirectives;
472
473 // We are about to read a token. For the multiple-include optimization FA to
474 // work, we have to remember if we had read any tokens *before* this
475 // pp-directive.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000476 bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Chris Lattner141e71f2008-03-09 01:54:53 +0000477
Chris Lattner42aa16c2009-03-18 21:00:25 +0000478 // Save the '#' token in case we need to return it later.
479 Token SavedHash = Result;
480
Chris Lattner141e71f2008-03-09 01:54:53 +0000481 // Read the next token, the directive flavor. This isn't expanded due to
482 // C99 6.10.3p8.
483 LexUnexpandedToken(Result);
484
485 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
486 // #define A(x) #x
487 // A(abc
488 // #warning blah
489 // def)
490 // If so, the user is relying on non-portable behavior, emit a diagnostic.
491 if (InMacroArgs)
492 Diag(Result, diag::ext_embedded_directive);
493
494TryAgain:
495 switch (Result.getKind()) {
496 case tok::eom:
497 return; // null directive.
498 case tok::comment:
499 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
500 LexUnexpandedToken(Result);
501 goto TryAgain;
502
Chris Lattner478a18e2009-01-26 06:19:46 +0000503 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000504 if (getLangOptions().AsmPreprocessor)
505 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000506 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000507 default:
508 IdentifierInfo *II = Result.getIdentifierInfo();
509 if (II == 0) break; // Not an identifier.
510
511 // Ask what the preprocessor keyword ID is.
512 switch (II->getPPKeywordID()) {
513 default: break;
514 // C99 6.10.1 - Conditional Inclusion.
515 case tok::pp_if:
516 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
517 case tok::pp_ifdef:
518 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
519 case tok::pp_ifndef:
520 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
521 case tok::pp_elif:
522 return HandleElifDirective(Result);
523 case tok::pp_else:
524 return HandleElseDirective(Result);
525 case tok::pp_endif:
526 return HandleEndifDirective(Result);
527
528 // C99 6.10.2 - Source File Inclusion.
529 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000530 return HandleIncludeDirective(Result); // Handle #include.
531 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000532 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000533
Chris Lattner141e71f2008-03-09 01:54:53 +0000534 // C99 6.10.3 - Macro Replacement.
535 case tok::pp_define:
536 return HandleDefineDirective(Result);
537 case tok::pp_undef:
538 return HandleUndefDirective(Result);
539
540 // C99 6.10.4 - Line Control.
541 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000542 return HandleLineDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000543
544 // C99 6.10.5 - Error Directive.
545 case tok::pp_error:
546 return HandleUserDiagnosticDirective(Result, false);
547
548 // C99 6.10.6 - Pragma Directive.
549 case tok::pp_pragma:
550 return HandlePragmaDirective();
551
552 // GNU Extensions.
553 case tok::pp_import:
554 return HandleImportDirective(Result);
555 case tok::pp_include_next:
556 return HandleIncludeNextDirective(Result);
557
558 case tok::pp_warning:
559 Diag(Result, diag::ext_pp_warning_directive);
560 return HandleUserDiagnosticDirective(Result, true);
561 case tok::pp_ident:
562 return HandleIdentSCCSDirective(Result);
563 case tok::pp_sccs:
564 return HandleIdentSCCSDirective(Result);
565 case tok::pp_assert:
566 //isExtension = true; // FIXME: implement #assert
567 break;
568 case tok::pp_unassert:
569 //isExtension = true; // FIXME: implement #unassert
570 break;
571 }
572 break;
573 }
574
Chris Lattner42aa16c2009-03-18 21:00:25 +0000575 // If this is a .S file, treat unknown # directives as non-preprocessor
576 // directives. This is important because # may be a comment or introduce
577 // various pseudo-ops. Just return the # token and push back the following
578 // token to be lexed next time.
579 if (getLangOptions().AsmPreprocessor) {
580 Token *Toks = new Token[2]();
581 // Return the # and the token after it.
582 Toks[0] = SavedHash;
583 Toks[1] = Result;
584 // Enter this token stream so that we re-lex the tokens. Make sure to
585 // enable macro expansion, in case the token after the # is an identifier
586 // that is expanded.
587 EnterTokenStream(Toks, 2, false, true);
588 return;
589 }
590
Chris Lattner141e71f2008-03-09 01:54:53 +0000591 // If we reached here, the preprocessing token is not valid!
592 Diag(Result, diag::err_pp_invalid_directive);
593
594 // Read the rest of the PP line.
595 DiscardUntilEndOfDirective();
596
597 // Okay, we're done parsing the directive.
598}
599
Chris Lattner478a18e2009-01-26 06:19:46 +0000600/// GetLineValue - Convert a numeric token into an unsigned value, emitting
601/// Diagnostic DiagID if it is invalid, and returning the value in Val.
602static bool GetLineValue(Token &DigitTok, unsigned &Val,
603 unsigned DiagID, Preprocessor &PP) {
604 if (DigitTok.isNot(tok::numeric_constant)) {
605 PP.Diag(DigitTok, DiagID);
606
607 if (DigitTok.isNot(tok::eom))
608 PP.DiscardUntilEndOfDirective();
609 return true;
610 }
611
612 llvm::SmallString<64> IntegerBuffer;
613 IntegerBuffer.resize(DigitTok.getLength());
614 const char *DigitTokBegin = &IntegerBuffer[0];
615 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
616 NumericLiteralParser Literal(DigitTokBegin, DigitTokBegin+ActualLength,
617 DigitTok.getLocation(), PP);
618 if (Literal.hadError)
619 return true; // Error already emitted.
620
621 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
622 PP.Diag(DigitTok, DiagID);
623 return true;
624 }
625
626 // Parse the integer literal into Result.
627 llvm::APInt APVal(32, 0);
628 if (Literal.GetIntegerValue(APVal)) {
629 // Overflow parsing integer literal.
630 PP.Diag(DigitTok, DiagID);
631 return true;
632 }
633 Val = APVal.getZExtValue();
634
635 // Reject 0, this is needed both by #line numbers and flags.
636 if (Val == 0) {
637 PP.Diag(DigitTok, DiagID);
638 PP.DiscardUntilEndOfDirective();
639 return true;
640 }
641
642 return false;
643}
644
Chris Lattner359cc442009-01-26 05:29:08 +0000645/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
646/// acceptable forms are:
647/// # line digit-sequence
648/// # line digit-sequence "s-char-sequence"
649void Preprocessor::HandleLineDirective(Token &Tok) {
650 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
651 // expanded.
652 Token DigitTok;
653 Lex(DigitTok);
654
Chris Lattner359cc442009-01-26 05:29:08 +0000655 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000656 unsigned LineNo;
657 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer, *this))
Chris Lattner359cc442009-01-26 05:29:08 +0000658 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000659
Chris Lattner478a18e2009-01-26 06:19:46 +0000660 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
661 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000662 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
663 if (LineNo >= LineLimit)
664 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
665
Chris Lattner5b9a5042009-01-26 07:57:50 +0000666 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000667 Token StrTok;
668 Lex(StrTok);
669
670 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
671 // string followed by eom.
672 if (StrTok.is(tok::eom))
673 ; // ok
674 else if (StrTok.isNot(tok::string_literal)) {
675 Diag(StrTok, diag::err_pp_line_invalid_filename);
676 DiscardUntilEndOfDirective();
677 return;
678 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000679 // Parse and validate the string, converting it into a unique ID.
680 StringLiteralParser Literal(&StrTok, 1, *this);
681 assert(!Literal.AnyWide && "Didn't allow wide strings in");
682 if (Literal.hadError)
683 return DiscardUntilEndOfDirective();
684 if (Literal.Pascal) {
685 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
686 return DiscardUntilEndOfDirective();
687 }
688 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
689 Literal.GetStringLength());
690
Chris Lattner359cc442009-01-26 05:29:08 +0000691 // Verify that there is nothing after the string, other than EOM.
692 CheckEndOfDirective("#line");
693 }
694
Chris Lattner4c4ea172009-02-03 21:52:55 +0000695 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Chris Lattner16629382009-03-27 17:13:49 +0000696
697 if (Callbacks)
698 Callbacks->FileChanged(DigitTok.getLocation(), PPCallbacks::RenameFile,
699 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000700}
701
Chris Lattner478a18e2009-01-26 06:19:46 +0000702/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
703/// marker directive.
704static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
705 bool &IsSystemHeader, bool &IsExternCHeader,
706 Preprocessor &PP) {
707 unsigned FlagVal;
708 Token FlagTok;
709 PP.Lex(FlagTok);
710 if (FlagTok.is(tok::eom)) return false;
711 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
712 return true;
713
714 if (FlagVal == 1) {
715 IsFileEntry = true;
716
717 PP.Lex(FlagTok);
718 if (FlagTok.is(tok::eom)) return false;
719 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
720 return true;
721 } else if (FlagVal == 2) {
722 IsFileExit = true;
723
Chris Lattner137b6a62009-02-04 06:25:26 +0000724 SourceManager &SM = PP.getSourceManager();
725 // If we are leaving the current presumed file, check to make sure the
726 // presumed include stack isn't empty!
727 FileID CurFileID =
728 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
729 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
730
731 // If there is no include loc (main file) or if the include loc is in a
732 // different physical file, then we aren't in a "1" line marker flag region.
733 SourceLocation IncLoc = PLoc.getIncludeLoc();
734 if (IncLoc.isInvalid() ||
735 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
736 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
737 PP.DiscardUntilEndOfDirective();
738 return true;
739 }
740
Chris Lattner478a18e2009-01-26 06:19:46 +0000741 PP.Lex(FlagTok);
742 if (FlagTok.is(tok::eom)) return false;
743 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
744 return true;
745 }
746
747 // We must have 3 if there are still flags.
748 if (FlagVal != 3) {
749 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000750 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000751 return true;
752 }
753
754 IsSystemHeader = true;
755
756 PP.Lex(FlagTok);
757 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000758 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000759 return true;
760
761 // We must have 4 if there is yet another flag.
762 if (FlagVal != 4) {
763 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000764 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000765 return true;
766 }
767
768 IsExternCHeader = true;
769
770 PP.Lex(FlagTok);
771 if (FlagTok.is(tok::eom)) return false;
772
773 // There are no more valid flags here.
774 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000775 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000776 return true;
777}
778
779/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
780/// one of the following forms:
781///
782/// # 42
783/// # 42 "file" ('1' | '2')?
784/// # 42 "file" ('1' | '2')? '3' '4'?
785///
786void Preprocessor::HandleDigitDirective(Token &DigitTok) {
787 // Validate the number and convert it to an unsigned. GNU does not have a
788 // line # limit other than it fit in 32-bits.
789 unsigned LineNo;
790 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
791 *this))
792 return;
793
794 Token StrTok;
795 Lex(StrTok);
796
797 bool IsFileEntry = false, IsFileExit = false;
798 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000799 int FilenameID = -1;
800
Chris Lattner478a18e2009-01-26 06:19:46 +0000801 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
802 // string followed by eom.
803 if (StrTok.is(tok::eom))
804 ; // ok
805 else if (StrTok.isNot(tok::string_literal)) {
806 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000807 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000808 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000809 // Parse and validate the string, converting it into a unique ID.
810 StringLiteralParser Literal(&StrTok, 1, *this);
811 assert(!Literal.AnyWide && "Didn't allow wide strings in");
812 if (Literal.hadError)
813 return DiscardUntilEndOfDirective();
814 if (Literal.Pascal) {
815 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
816 return DiscardUntilEndOfDirective();
817 }
818 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
819 Literal.GetStringLength());
820
Chris Lattner478a18e2009-01-26 06:19:46 +0000821 // If a filename was present, read any flags that are present.
822 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000823 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000824 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000825 }
Chris Lattner137b6a62009-02-04 06:25:26 +0000826
Chris Lattner9d79eba2009-02-04 05:21:58 +0000827 // Create a line note with this information.
828 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
829 IsFileEntry, IsFileExit,
830 IsSystemHeader, IsExternCHeader);
Chris Lattner16629382009-03-27 17:13:49 +0000831
832 // If the preprocessor has callbacks installed, notify them of the #line
833 // change. This is used so that the line marker comes out in -E mode for
834 // example.
835 if (Callbacks) {
836 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
837 if (IsFileEntry)
838 Reason = PPCallbacks::EnterFile;
839 else if (IsFileExit)
840 Reason = PPCallbacks::ExitFile;
841 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
842 if (IsExternCHeader)
843 FileKind = SrcMgr::C_ExternCSystem;
844 else if (IsSystemHeader)
845 FileKind = SrcMgr::C_System;
846
847 Callbacks->FileChanged(DigitTok.getLocation(), Reason, FileKind);
848 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000849}
850
851
Chris Lattner099dd052009-01-26 05:30:54 +0000852/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
853///
Chris Lattner141e71f2008-03-09 01:54:53 +0000854void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
855 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000856 // PTH doesn't emit #warning or #error directives.
857 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000858 return CurPTHLexer->DiscardToEndOfLine();
859
Chris Lattner141e71f2008-03-09 01:54:53 +0000860 // Read the rest of the line raw. We do this because we don't want macros
861 // to be expanded and we don't require that the tokens be valid preprocessing
862 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
863 // collapse multiple consequtive white space between tokens, but this isn't
864 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000865 std::string Message = CurLexer->ReadToEndOfLine();
866 if (isWarning)
867 Diag(Tok, diag::pp_hash_warning) << Message;
868 else
869 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000870}
871
872/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
873///
874void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
875 // Yes, this directive is an extension.
876 Diag(Tok, diag::ext_pp_ident_directive);
877
878 // Read the string argument.
879 Token StrTok;
880 Lex(StrTok);
881
882 // If the token kind isn't a string, it's a malformed directive.
883 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000884 StrTok.isNot(tok::wide_string_literal)) {
885 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000886 if (StrTok.isNot(tok::eom))
887 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000888 return;
889 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000890
891 // Verify that there is nothing after the string, other than EOM.
892 CheckEndOfDirective("#ident");
893
894 if (Callbacks)
895 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
896}
897
898//===----------------------------------------------------------------------===//
899// Preprocessor Include Directive Handling.
900//===----------------------------------------------------------------------===//
901
902/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
903/// checked and spelled filename, e.g. as an operand of #include. This returns
904/// true if the input filename was in <>'s or false if it were in ""'s. The
905/// caller is expected to provide a buffer that is large enough to hold the
906/// spelling of the filename, but is also expected to handle the case when
907/// this method decides to use a different buffer.
908bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
909 const char *&BufStart,
910 const char *&BufEnd) {
911 // Get the text form of the filename.
912 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
913
914 // Make sure the filename is <x> or "x".
915 bool isAngled;
916 if (BufStart[0] == '<') {
917 if (BufEnd[-1] != '>') {
918 Diag(Loc, diag::err_pp_expects_filename);
919 BufStart = 0;
920 return true;
921 }
922 isAngled = true;
923 } else if (BufStart[0] == '"') {
924 if (BufEnd[-1] != '"') {
925 Diag(Loc, diag::err_pp_expects_filename);
926 BufStart = 0;
927 return true;
928 }
929 isAngled = false;
930 } else {
931 Diag(Loc, diag::err_pp_expects_filename);
932 BufStart = 0;
933 return true;
934 }
935
936 // Diagnose #include "" as invalid.
937 if (BufEnd-BufStart <= 2) {
938 Diag(Loc, diag::err_pp_empty_filename);
939 BufStart = 0;
940 return "";
941 }
942
943 // Skip the brackets.
944 ++BufStart;
945 --BufEnd;
946 return isAngled;
947}
948
949/// ConcatenateIncludeName - Handle cases where the #include name is expanded
950/// from a macro as multiple tokens, which need to be glued together. This
951/// occurs for code like:
952/// #define FOO <a/b.h>
953/// #include FOO
954/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
955///
956/// This code concatenates and consumes tokens up to the '>' token. It returns
957/// false if the > was found, otherwise it returns true if it finds and consumes
958/// the EOM marker.
959static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
960 Preprocessor &PP) {
961 Token CurTok;
962
963 PP.Lex(CurTok);
964 while (CurTok.isNot(tok::eom)) {
965 // Append the spelling of this token to the buffer. If there was a space
966 // before it, add it now.
967 if (CurTok.hasLeadingSpace())
968 FilenameBuffer.push_back(' ');
969
970 // Get the spelling of the token, directly into FilenameBuffer if possible.
971 unsigned PreAppendSize = FilenameBuffer.size();
972 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
973
974 const char *BufPtr = &FilenameBuffer[PreAppendSize];
975 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
976
977 // If the token was spelled somewhere else, copy it into FilenameBuffer.
978 if (BufPtr != &FilenameBuffer[PreAppendSize])
979 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
980
981 // Resize FilenameBuffer to the correct size.
982 if (CurTok.getLength() != ActualLen)
983 FilenameBuffer.resize(PreAppendSize+ActualLen);
984
985 // If we found the '>' marker, return success.
986 if (CurTok.is(tok::greater))
987 return false;
988
989 PP.Lex(CurTok);
990 }
991
992 // If we hit the eom marker, emit an error and return true so that the caller
993 // knows the EOM has been read.
994 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
995 return true;
996}
997
998/// HandleIncludeDirective - The "#include" tokens have just been read, read the
999/// file to be included from the lexer, then include it! This is a common
1000/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001001/// #import. LookupFrom is set when this is a #include_next directive, it
1002/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001003void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1004 const DirectoryLookup *LookupFrom,
1005 bool isImport) {
1006
1007 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001008 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001009
1010 // Reserve a buffer to get the spelling.
1011 llvm::SmallVector<char, 128> FilenameBuffer;
1012 const char *FilenameStart, *FilenameEnd;
1013
1014 switch (FilenameTok.getKind()) {
1015 case tok::eom:
1016 // If the token kind is EOM, the error has already been diagnosed.
1017 return;
1018
1019 case tok::angle_string_literal:
1020 case tok::string_literal: {
1021 FilenameBuffer.resize(FilenameTok.getLength());
1022 FilenameStart = &FilenameBuffer[0];
1023 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1024 FilenameEnd = FilenameStart+Len;
1025 break;
1026 }
1027
1028 case tok::less:
1029 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1030 // case, glue the tokens together into FilenameBuffer and interpret those.
1031 FilenameBuffer.push_back('<');
1032 if (ConcatenateIncludeName(FilenameBuffer, *this))
1033 return; // Found <eom> but no ">"? Diagnostic already emitted.
1034 FilenameStart = &FilenameBuffer[0];
1035 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1036 break;
1037 default:
1038 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1039 DiscardUntilEndOfDirective();
1040 return;
1041 }
1042
1043 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
1044 FilenameStart, FilenameEnd);
1045 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1046 // error.
1047 if (FilenameStart == 0) {
1048 DiscardUntilEndOfDirective();
1049 return;
1050 }
1051
Chris Lattnerfd105112009-04-08 20:53:24 +00001052 // Verify that there is nothing after the filename, other than EOM.
Chris Lattner141e71f2008-03-09 01:54:53 +00001053 CheckEndOfDirective("#include");
1054
1055 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001056 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1057 Diag(FilenameTok, diag::err_pp_include_too_deep);
1058 return;
1059 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001060
1061 // Search include directories.
1062 const DirectoryLookup *CurDir;
1063 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1064 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001065 if (File == 0) {
1066 Diag(FilenameTok, diag::err_pp_file_not_found)
1067 << std::string(FilenameStart, FilenameEnd);
1068 return;
1069 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001070
Chris Lattner72181832008-09-26 20:12:23 +00001071 // Ask HeaderInfo if we should enter this #include file. If not, #including
1072 // this file will have no effect.
1073 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001074 return;
Chris Lattner72181832008-09-26 20:12:23 +00001075
1076 // The #included file will be considered to be a system header if either it is
1077 // in a system include directory, or if the #includer is a system include
1078 // header.
Chris Lattner9d728512008-10-27 01:19:25 +00001079 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001080 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001081 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Chris Lattner72181832008-09-26 20:12:23 +00001082
Chris Lattner141e71f2008-03-09 01:54:53 +00001083 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001084 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1085 FileCharacter);
1086 if (FID.isInvalid()) {
Chris Lattner56b05c82008-11-18 08:02:48 +00001087 Diag(FilenameTok, diag::err_pp_file_not_found)
1088 << std::string(FilenameStart, FilenameEnd);
1089 return;
1090 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001091
1092 // Finally, if all is good, enter the new file!
Chris Lattner2b2453a2009-01-17 06:22:33 +00001093 EnterSourceFile(FID, CurDir);
Chris Lattner141e71f2008-03-09 01:54:53 +00001094}
1095
1096/// HandleIncludeNextDirective - Implements #include_next.
1097///
1098void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1099 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1100
1101 // #include_next is like #include, except that we start searching after
1102 // the current found directory. If we can't do this, issue a
1103 // diagnostic.
1104 const DirectoryLookup *Lookup = CurDirLookup;
1105 if (isInPrimaryFile()) {
1106 Lookup = 0;
1107 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1108 } else if (Lookup == 0) {
1109 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1110 } else {
1111 // Start looking up in the next directory.
1112 ++Lookup;
1113 }
1114
1115 return HandleIncludeDirective(IncludeNextTok, Lookup);
1116}
1117
1118/// HandleImportDirective - Implements #import.
1119///
1120void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001121 if (!Features.ObjC1) // #import is standard for ObjC.
1122 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner141e71f2008-03-09 01:54:53 +00001123
1124 return HandleIncludeDirective(ImportTok, 0, true);
1125}
1126
Chris Lattnerde076652009-04-08 18:46:40 +00001127/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1128/// pseudo directive in the predefines buffer. This handles it by sucking all
1129/// tokens through the preprocessor and discarding them (only keeping the side
1130/// effects on the preprocessor).
1131void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1132 // This directive should only occur in the predefines buffer. If not, emit an
1133 // error and reject it.
1134 SourceLocation Loc = IncludeMacrosTok.getLocation();
1135 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1136 Diag(IncludeMacrosTok.getLocation(),
1137 diag::pp_include_macros_out_of_predefines);
1138 DiscardUntilEndOfDirective();
1139 return;
1140 }
1141
Chris Lattnerfd105112009-04-08 20:53:24 +00001142 // Treat this as a normal #include for checking purposes. If this is
1143 // successful, it will push a new lexer onto the include stack.
1144 HandleIncludeDirective(IncludeMacrosTok, 0, false);
1145
1146 Token TmpTok;
1147 do {
1148 Lex(TmpTok);
1149 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1150 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001151}
1152
Chris Lattner141e71f2008-03-09 01:54:53 +00001153//===----------------------------------------------------------------------===//
1154// Preprocessor Macro Directive Handling.
1155//===----------------------------------------------------------------------===//
1156
1157/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1158/// definition has just been read. Lex the rest of the arguments and the
1159/// closing ), updating MI with what we learn. Return true if an error occurs
1160/// parsing the arg list.
1161bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1162 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1163
1164 Token Tok;
1165 while (1) {
1166 LexUnexpandedToken(Tok);
1167 switch (Tok.getKind()) {
1168 case tok::r_paren:
1169 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001170 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001171 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001172 // Otherwise we have #define FOO(A,)
1173 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1174 return true;
1175 case tok::ellipsis: // #define X(... -> C99 varargs
1176 // Warn if use of C99 feature in non-C99 mode.
1177 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1178
1179 // Lex the token after the identifier.
1180 LexUnexpandedToken(Tok);
1181 if (Tok.isNot(tok::r_paren)) {
1182 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1183 return true;
1184 }
1185 // Add the __VA_ARGS__ identifier as an argument.
1186 Arguments.push_back(Ident__VA_ARGS__);
1187 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001188 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001189 return false;
1190 case tok::eom: // #define X(
1191 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1192 return true;
1193 default:
1194 // Handle keywords and identifiers here to accept things like
1195 // #define Foo(for) for.
1196 IdentifierInfo *II = Tok.getIdentifierInfo();
1197 if (II == 0) {
1198 // #define X(1
1199 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1200 return true;
1201 }
1202
1203 // If this is already used as an argument, it is used multiple times (e.g.
1204 // #define X(A,A.
1205 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1206 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001207 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001208 return true;
1209 }
1210
1211 // Add the argument to the macro info.
1212 Arguments.push_back(II);
1213
1214 // Lex the token after the identifier.
1215 LexUnexpandedToken(Tok);
1216
1217 switch (Tok.getKind()) {
1218 default: // #define X(A B
1219 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1220 return true;
1221 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001222 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001223 return false;
1224 case tok::comma: // #define X(A,
1225 break;
1226 case tok::ellipsis: // #define X(A... -> GCC extension
1227 // Diagnose extension.
1228 Diag(Tok, diag::ext_named_variadic_macro);
1229
1230 // Lex the token after the identifier.
1231 LexUnexpandedToken(Tok);
1232 if (Tok.isNot(tok::r_paren)) {
1233 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1234 return true;
1235 }
1236
1237 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001238 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001239 return false;
1240 }
1241 }
1242 }
1243}
1244
1245/// HandleDefineDirective - Implements #define. This consumes the entire macro
1246/// line then lets the caller lex the next real token.
1247void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1248 ++NumDefined;
1249
1250 Token MacroNameTok;
1251 ReadMacroName(MacroNameTok, 1);
1252
1253 // Error reading macro name? If so, diagnostic already issued.
1254 if (MacroNameTok.is(tok::eom))
1255 return;
1256
1257 // If we are supposed to keep comments in #defines, reenable comment saving
1258 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001259 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Chris Lattner141e71f2008-03-09 01:54:53 +00001260
1261 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001262 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001263
1264 Token Tok;
1265 LexUnexpandedToken(Tok);
1266
1267 // If this is a function-like macro definition, parse the argument list,
1268 // marking each of the identifiers as being used as macro arguments. Also,
1269 // check other constraints on the first token of the macro body.
1270 if (Tok.is(tok::eom)) {
1271 // If there is no body to this macro, we have no special handling here.
1272 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
1273 // This is a function-like macro definition. Read the argument list.
1274 MI->setIsFunctionLike();
1275 if (ReadMacroDefinitionArgList(MI)) {
1276 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001277 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001278 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001279 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001280 DiscardUntilEndOfDirective();
1281 return;
1282 }
1283
1284 // Read the first token after the arg list for down below.
1285 LexUnexpandedToken(Tok);
1286 } else if (!Tok.hasLeadingSpace()) {
1287 // C99 requires whitespace between the macro definition and the body. Emit
1288 // a diagnostic for something like "#define X+".
1289 if (Features.C99) {
1290 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1291 } else {
1292 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1293 // one in some cases!
1294 }
1295 } else {
1296 // This is a normal token with leading space. Clear the leading space
1297 // marker on the first token to get proper expansion.
1298 Tok.clearFlag(Token::LeadingSpace);
1299 }
1300
1301 // If this is a definition of a variadic C99 function-like macro, not using
1302 // the GNU named varargs extension, enabled __VA_ARGS__.
1303
1304 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1305 // This gets unpoisoned where it is allowed.
1306 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1307 if (MI->isC99Varargs())
1308 Ident__VA_ARGS__->setIsPoisoned(false);
1309
1310 // Read the rest of the macro body.
1311 if (MI->isObjectLike()) {
1312 // Object-like macros are very simple, just read their body.
1313 while (Tok.isNot(tok::eom)) {
1314 MI->AddTokenToBody(Tok);
1315 // Get the next token of the macro.
1316 LexUnexpandedToken(Tok);
1317 }
1318
1319 } else {
1320 // Otherwise, read the body of a function-like macro. This has to validate
1321 // the # (stringize) operator.
1322 while (Tok.isNot(tok::eom)) {
1323 MI->AddTokenToBody(Tok);
1324
1325 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1326 // parameters in function-like macro expansions.
1327 if (Tok.isNot(tok::hash)) {
1328 // Get the next token of the macro.
1329 LexUnexpandedToken(Tok);
1330 continue;
1331 }
1332
1333 // Get the next token of the macro.
1334 LexUnexpandedToken(Tok);
1335
1336 // Not a macro arg identifier?
1337 if (!Tok.getIdentifierInfo() ||
1338 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1339 Diag(Tok, diag::err_pp_stringize_not_parameter);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001340 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001341
1342 // Disable __VA_ARGS__ again.
1343 Ident__VA_ARGS__->setIsPoisoned(true);
1344 return;
1345 }
1346
1347 // Things look ok, add the param name token to the macro.
1348 MI->AddTokenToBody(Tok);
1349
1350 // Get the next token of the macro.
1351 LexUnexpandedToken(Tok);
1352 }
1353 }
1354
1355
1356 // Disable __VA_ARGS__ again.
1357 Ident__VA_ARGS__->setIsPoisoned(true);
1358
1359 // Check that there is no paste (##) operator at the begining or end of the
1360 // replacement list.
1361 unsigned NumTokens = MI->getNumTokens();
1362 if (NumTokens != 0) {
1363 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1364 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001365 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001366 return;
1367 }
1368 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1369 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001370 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001371 return;
1372 }
1373 }
1374
1375 // If this is the primary source file, remember that this macro hasn't been
1376 // used yet.
1377 if (isInPrimaryFile())
1378 MI->setIsUsed(false);
1379
1380 // Finally, if this identifier already had a macro defined for it, verify that
1381 // the macro bodies are identical and free the old definition.
1382 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001383 // It is very common for system headers to have tons of macro redefinitions
1384 // and for warnings to be disabled in system headers. If this is the case,
1385 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001386 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001387 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1388 if (!OtherMI->isUsed())
1389 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001390
Chris Lattner41c3ae12009-01-16 19:50:11 +00001391 // Macros must be identical. This means all tokes and whitespace
1392 // separation must be the same. C99 6.10.3.2.
1393 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1394 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1395 << MacroNameTok.getIdentifierInfo();
1396 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1397 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001398 }
Chris Lattner41c3ae12009-01-16 19:50:11 +00001399
Ted Kremenek0ea76722008-12-15 19:56:42 +00001400 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001401 }
1402
1403 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001404
1405 // If the callbacks want to know, tell them about the macro definition.
1406 if (Callbacks)
1407 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001408}
1409
1410/// HandleUndefDirective - Implements #undef.
1411///
1412void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1413 ++NumUndefined;
1414
1415 Token MacroNameTok;
1416 ReadMacroName(MacroNameTok, 2);
1417
1418 // Error reading macro name? If so, diagnostic already issued.
1419 if (MacroNameTok.is(tok::eom))
1420 return;
1421
1422 // Check to see if this is the last token on the #undef line.
1423 CheckEndOfDirective("#undef");
1424
1425 // Okay, we finally have a valid identifier to undef.
1426 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1427
1428 // If the macro is not defined, this is a noop undef, just return.
1429 if (MI == 0) return;
1430
1431 if (!MI->isUsed())
1432 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1433
1434 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001435 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001436 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1437}
1438
1439
1440//===----------------------------------------------------------------------===//
1441// Preprocessor Conditional Directive Handling.
1442//===----------------------------------------------------------------------===//
1443
1444/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1445/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1446/// if any tokens have been returned or pp-directives activated before this
1447/// #ifndef has been lexed.
1448///
1449void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1450 bool ReadAnyTokensBeforeDirective) {
1451 ++NumIf;
1452 Token DirectiveTok = Result;
1453
1454 Token MacroNameTok;
1455 ReadMacroName(MacroNameTok);
1456
1457 // Error reading macro name? If so, diagnostic already issued.
1458 if (MacroNameTok.is(tok::eom)) {
1459 // Skip code until we get to #endif. This helps with recovery by not
1460 // emitting an error when the #endif is reached.
1461 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1462 /*Foundnonskip*/false, /*FoundElse*/false);
1463 return;
1464 }
1465
1466 // Check to see if this is the last token on the #if[n]def line.
1467 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1468
Ted Kremenek60e45d42008-11-18 00:34:22 +00001469 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001470 // If the start of a top-level #ifdef, inform MIOpt.
1471 if (!ReadAnyTokensBeforeDirective) {
1472 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001473 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001474 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001475 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001476 }
1477
1478 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1479 MacroInfo *MI = getMacroInfo(MII);
1480
1481 // If there is a macro, process it.
1482 if (MI) // Mark it used.
1483 MI->setIsUsed(true);
1484
1485 // Should we include the stuff contained by this directive?
1486 if (!MI == isIfndef) {
1487 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001488 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001489 /*foundnonskip*/true, /*foundelse*/false);
1490 } else {
1491 // No, skip the contents of this block and return the first token after it.
1492 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1493 /*Foundnonskip*/false,
1494 /*FoundElse*/false);
1495 }
1496}
1497
1498/// HandleIfDirective - Implements the #if directive.
1499///
1500void Preprocessor::HandleIfDirective(Token &IfToken,
1501 bool ReadAnyTokensBeforeDirective) {
1502 ++NumIf;
1503
1504 // Parse and evaluation the conditional expression.
1505 IdentifierInfo *IfNDefMacro = 0;
1506 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1507
Nuno Lopes0049db62008-06-01 18:31:24 +00001508
1509 // If this condition is equivalent to #ifndef X, and if this is the first
1510 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001511 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001512 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001513 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001514 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001515 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001516 }
1517
Chris Lattner141e71f2008-03-09 01:54:53 +00001518 // Should we include the stuff contained by this directive?
1519 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001520 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001521 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001522 /*foundnonskip*/true, /*foundelse*/false);
1523 } else {
1524 // No, skip the contents of this block and return the first token after it.
1525 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1526 /*FoundElse*/false);
1527 }
1528}
1529
1530/// HandleEndifDirective - Implements the #endif directive.
1531///
1532void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1533 ++NumEndif;
1534
1535 // Check that this is the whole directive.
1536 CheckEndOfDirective("#endif");
1537
1538 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001539 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001540 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001541 Diag(EndifToken, diag::err_pp_endif_without_if);
1542 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001543 }
1544
1545 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001546 if (CurPPLexer->getConditionalStackDepth() == 0)
1547 CurPPLexer->MIOpt.ExitTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001548
Ted Kremenek60e45d42008-11-18 00:34:22 +00001549 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001550 "This code should only be reachable in the non-skipping case!");
1551}
1552
1553
1554void Preprocessor::HandleElseDirective(Token &Result) {
1555 ++NumElse;
1556
1557 // #else directive in a non-skipping conditional... start skipping.
1558 CheckEndOfDirective("#else");
1559
1560 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001561 if (CurPPLexer->popConditionalLevel(CI)) {
1562 Diag(Result, diag::pp_err_else_without_if);
1563 return;
1564 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001565
1566 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001567 if (CurPPLexer->getConditionalStackDepth() == 0)
1568 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001569
1570 // If this is a #else with a #else before it, report the error.
1571 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1572
1573 // Finally, skip the rest of the contents of this block and return the first
1574 // token after it.
1575 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1576 /*FoundElse*/true);
1577}
1578
1579void Preprocessor::HandleElifDirective(Token &ElifToken) {
1580 ++NumElse;
1581
1582 // #elif directive in a non-skipping conditional... start skipping.
1583 // We don't care what the condition is, because we will always skip it (since
1584 // the block immediately before it was included).
1585 DiscardUntilEndOfDirective();
1586
1587 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001588 if (CurPPLexer->popConditionalLevel(CI)) {
1589 Diag(ElifToken, diag::pp_err_elif_without_if);
1590 return;
1591 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001592
1593 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001594 if (CurPPLexer->getConditionalStackDepth() == 0)
1595 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001596
1597 // If this is a #elif with a #else before it, report the error.
1598 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1599
1600 // Finally, skip the rest of the contents of this block and return the first
1601 // token after it.
1602 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1603 /*FoundElse*/CI.FoundElse);
1604}
1605