blob: 742076956d2eb456d7c6529746dce7f303c3e982 [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 Lattner959875a2009-04-14 05:15:20 +0000117 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
118 // because it is more trouble than it is worth to insert /**/ and check that
119 // there is no /**/ in the range also.
120 CodeModificationHint FixItHint;
121 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
122 FixItHint = CodeModificationHint::CreateInsertion(Tmp.getLocation(),"//");
123 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << FixItHint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000124 DiscardUntilEndOfDirective();
125 }
126}
127
128
129
130/// SkipExcludedConditionalBlock - We just read a #if or related directive and
131/// decided that the subsequent tokens are in the #if'd out portion of the
132/// file. Lex the rest of the file, until we see an #endif. If
133/// FoundNonSkipPortion is true, then we have already emitted code for part of
134/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
135/// is true, then #else directives are ok, if not, then we have already seen one
136/// so a #else directive is a duplicate. When this returns, the caller can lex
137/// the first valid token.
138void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
139 bool FoundNonSkipPortion,
140 bool FoundElse) {
141 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000142 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000143
Ted Kremenek60e45d42008-11-18 00:34:22 +0000144 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000145 FoundNonSkipPortion, FoundElse);
146
Ted Kremenek268ee702008-12-12 18:34:08 +0000147 if (CurPTHLexer) {
148 PTHSkipExcludedConditionalBlock();
149 return;
150 }
151
Chris Lattner141e71f2008-03-09 01:54:53 +0000152 // Enter raw mode to disable identifier lookup (and thus macro expansion),
153 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000154 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000155 Token Tok;
156 while (1) {
Ted Kremenekf6452c52008-11-18 01:04:47 +0000157 if (CurLexer)
158 CurLexer->Lex(Tok);
159 else
160 CurPTHLexer->Lex(Tok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000161
162 // If this is the end of the buffer, we have an error.
163 if (Tok.is(tok::eof)) {
164 // Emit errors for each unterminated conditional on the stack, including
165 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000166 while (!CurPPLexer->ConditionalStack.empty()) {
167 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000168 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000169 CurPPLexer->ConditionalStack.pop_back();
Chris Lattner141e71f2008-03-09 01:54:53 +0000170 }
171
172 // Just return and let the caller lex after this #include.
173 break;
174 }
175
176 // If this token is not a preprocessor directive, just skip it.
177 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
178 continue;
179
180 // We just parsed a # character at the start of a line, so we're in
181 // directive mode. Tell the lexer this so any newlines we see will be
182 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000183 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000184 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000185
186
187 // Read the next token, the directive flavor.
188 LexUnexpandedToken(Tok);
189
190 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
191 // something bogus), skip it.
192 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000193 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000194 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000195 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000196 continue;
197 }
198
199 // If the first letter isn't i or e, it isn't intesting to us. We know that
200 // this is safe in the face of spelling differences, because there is no way
201 // to spell an i/e in a strange way that is another letter. Skipping this
202 // allows us to avoid looking up the identifier info for #define/#undef and
203 // other common directives.
204 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
205 char FirstChar = RawCharData[0];
206 if (FirstChar >= 'a' && FirstChar <= 'z' &&
207 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000208 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000209 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000210 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000211 continue;
212 }
213
214 // Get the identifier name without trigraphs or embedded newlines. Note
215 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
216 // when skipping.
217 // TODO: could do this with zero copies in the no-clean case by using
218 // strncmp below.
219 char Directive[20];
220 unsigned IdLen;
221 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
222 IdLen = Tok.getLength();
223 memcpy(Directive, RawCharData, IdLen);
224 Directive[IdLen] = 0;
225 } else {
226 std::string DirectiveStr = getSpelling(Tok);
227 IdLen = DirectiveStr.size();
228 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000229 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000230 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000231 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000232 continue;
233 }
234 memcpy(Directive, &DirectiveStr[0], IdLen);
235 Directive[IdLen] = 0;
Chris Lattner202fd2c2009-01-27 05:34:03 +0000236 FirstChar = Directive[0];
Chris Lattner141e71f2008-03-09 01:54:53 +0000237 }
238
239 if (FirstChar == 'i' && Directive[1] == 'f') {
240 if ((IdLen == 2) || // "if"
241 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
242 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
243 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
244 // bother parsing the condition.
245 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000246 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000247 /*foundnonskip*/false,
248 /*fnddelse*/false);
249 }
250 } else if (FirstChar == 'e') {
251 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000252 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000253 PPConditionalInfo CondInfo;
254 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000255 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000256 InCond = InCond; // Silence warning in no-asserts mode.
257 assert(!InCond && "Can't be skipping if not in a conditional!");
258
259 // If we popped the outermost skipping block, we're done skipping!
260 if (!CondInfo.WasSkipping)
261 break;
262 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
263 // #else directive in a skipping conditional. If not in some other
264 // skipping conditional, and if #else hasn't already been seen, enter it
265 // as a non-skipping conditional.
Chris Lattner35410d52009-04-14 05:07:49 +0000266 CheckEndOfDirective("else");
Ted Kremenek60e45d42008-11-18 00:34:22 +0000267 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000268
269 // If this is a #else with a #else before it, report the error.
270 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
271
272 // Note that we've seen a #else in this conditional.
273 CondInfo.FoundElse = true;
274
275 // If the conditional is at the top level, and the #if block wasn't
276 // entered, enter the #else block now.
277 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
278 CondInfo.FoundNonSkip = true;
279 break;
280 }
281 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000282 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000283
284 bool ShouldEnter;
285 // If this is in a skipping block or if we're already handled this #if
286 // block, don't bother parsing the condition.
287 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
288 DiscardUntilEndOfDirective();
289 ShouldEnter = false;
290 } else {
291 // Restore the value of LexingRawMode so that identifiers are
292 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000293 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
294 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000295 IdentifierInfo *IfNDefMacro = 0;
296 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000297 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000298 }
299
300 // If this is a #elif with a #else before it, report the error.
301 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
302
303 // If this condition is true, enter it!
304 if (ShouldEnter) {
305 CondInfo.FoundNonSkip = true;
306 break;
307 }
308 }
309 }
310
Ted Kremenek60e45d42008-11-18 00:34:22 +0000311 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000312 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000313 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000314 }
315
316 // Finally, if we are out of the conditional (saw an #endif or ran off the end
317 // of the file, just stop skipping and return to lexing whatever came after
318 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000319 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000320}
321
Ted Kremenek268ee702008-12-12 18:34:08 +0000322void Preprocessor::PTHSkipExcludedConditionalBlock() {
323
324 while(1) {
325 assert(CurPTHLexer);
326 assert(CurPTHLexer->LexingRawMode == false);
327
328 // Skip to the next '#else', '#elif', or #endif.
329 if (CurPTHLexer->SkipBlock()) {
330 // We have reached an #endif. Both the '#' and 'endif' tokens
331 // have been consumed by the PTHLexer. Just pop off the condition level.
332 PPConditionalInfo CondInfo;
333 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
334 InCond = InCond; // Silence warning in no-asserts mode.
335 assert(!InCond && "Can't be skipping if not in a conditional!");
336 break;
337 }
338
339 // We have reached a '#else' or '#elif'. Lex the next token to get
340 // the directive flavor.
341 Token Tok;
342 LexUnexpandedToken(Tok);
343
344 // We can actually look up the IdentifierInfo here since we aren't in
345 // raw mode.
346 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
347
348 if (K == tok::pp_else) {
349 // #else: Enter the else condition. We aren't in a nested condition
350 // since we skip those. We're always in the one matching the last
351 // blocked we skipped.
352 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
353 // Note that we've seen a #else in this conditional.
354 CondInfo.FoundElse = true;
355
356 // If the #if block wasn't entered then enter the #else block now.
357 if (!CondInfo.FoundNonSkip) {
358 CondInfo.FoundNonSkip = true;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000359
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000360 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000361 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000362 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000363 CurPTHLexer->ParsingPreprocessorDirective = false;
364
Ted Kremenek268ee702008-12-12 18:34:08 +0000365 break;
366 }
367
368 // Otherwise skip this block.
369 continue;
370 }
371
372 assert(K == tok::pp_elif);
373 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
374
375 // If this is a #elif with a #else before it, report the error.
376 if (CondInfo.FoundElse)
377 Diag(Tok, diag::pp_err_elif_after_else);
378
379 // If this is in a skipping block or if we're already handled this #if
380 // block, don't bother parsing the condition. We just skip this block.
381 if (CondInfo.FoundNonSkip)
382 continue;
383
384 // Evaluate the condition of the #elif.
385 IdentifierInfo *IfNDefMacro = 0;
386 CurPTHLexer->ParsingPreprocessorDirective = true;
387 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
388 CurPTHLexer->ParsingPreprocessorDirective = false;
389
390 // If this condition is true, enter it!
391 if (ShouldEnter) {
392 CondInfo.FoundNonSkip = true;
393 break;
394 }
395
396 // Otherwise, skip this block and go to the next one.
397 continue;
398 }
399}
400
Chris Lattner10725092008-03-09 04:17:44 +0000401/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
402/// return null on failure. isAngled indicates whether the file reference is
403/// for system #include's or not (i.e. using <> instead of "").
404const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
405 const char *FilenameEnd,
406 bool isAngled,
407 const DirectoryLookup *FromDir,
408 const DirectoryLookup *&CurDir) {
409 // If the header lookup mechanism may be relative to the current file, pass in
410 // info about where the current file is.
411 const FileEntry *CurFileEnt = 0;
412 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000413 FileID FID = getCurrentFileLexer()->getFileID();
414 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000415
416 // If there is no file entry associated with this file, it must be the
417 // predefines buffer. Any other file is not lexed with a normal lexer, so
418 // it won't be scanned for preprocessor directives. If we have the
419 // predefines buffer, resolve #include references (which come from the
420 // -include command line argument) as if they came from the main file, this
421 // affects file lookup etc.
422 if (CurFileEnt == 0) {
423 FID = SourceMgr.getMainFileID();
424 CurFileEnt = SourceMgr.getFileEntryForID(FID);
425 }
Chris Lattner10725092008-03-09 04:17:44 +0000426 }
427
428 // Do a standard file entry lookup.
429 CurDir = CurDirLookup;
430 const FileEntry *FE =
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000431 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
432 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner10725092008-03-09 04:17:44 +0000433 if (FE) return FE;
434
435 // Otherwise, see if this is a subframework header. If so, this is relative
436 // to one of the headers on the #include stack. Walk the list of the current
437 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000438 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000439 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000440 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
441 CurFileEnt)))
442 return FE;
443 }
444
445 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
446 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000447 if (IsFileLexer(ISEntry)) {
Chris Lattner10725092008-03-09 04:17:44 +0000448 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000449 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000450 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
451 FilenameEnd, CurFileEnt)))
452 return FE;
453 }
454 }
455
456 // Otherwise, we really couldn't find the file.
457 return 0;
458}
459
Chris Lattner141e71f2008-03-09 01:54:53 +0000460
461//===----------------------------------------------------------------------===//
462// Preprocessor Directive Handling.
463//===----------------------------------------------------------------------===//
464
465/// HandleDirective - This callback is invoked when the lexer sees a # token
466/// at the start of a line. This consumes the directive, modifies the
467/// lexer/preprocessor state, and advances the lexer(s) so that the next token
468/// read is the correct one.
469void Preprocessor::HandleDirective(Token &Result) {
470 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
471
472 // We just parsed a # character at the start of a line, so we're in directive
473 // mode. Tell the lexer this so any newlines we see will be converted into an
474 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000475 CurPPLexer->ParsingPreprocessorDirective = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000476
477 ++NumDirectives;
478
479 // We are about to read a token. For the multiple-include optimization FA to
480 // work, we have to remember if we had read any tokens *before* this
481 // pp-directive.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000482 bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Chris Lattner141e71f2008-03-09 01:54:53 +0000483
Chris Lattner42aa16c2009-03-18 21:00:25 +0000484 // Save the '#' token in case we need to return it later.
485 Token SavedHash = Result;
486
Chris Lattner141e71f2008-03-09 01:54:53 +0000487 // Read the next token, the directive flavor. This isn't expanded due to
488 // C99 6.10.3p8.
489 LexUnexpandedToken(Result);
490
491 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
492 // #define A(x) #x
493 // A(abc
494 // #warning blah
495 // def)
496 // If so, the user is relying on non-portable behavior, emit a diagnostic.
497 if (InMacroArgs)
498 Diag(Result, diag::ext_embedded_directive);
499
500TryAgain:
501 switch (Result.getKind()) {
502 case tok::eom:
503 return; // null directive.
504 case tok::comment:
505 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
506 LexUnexpandedToken(Result);
507 goto TryAgain;
508
Chris Lattner478a18e2009-01-26 06:19:46 +0000509 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000510 if (getLangOptions().AsmPreprocessor)
511 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000512 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000513 default:
514 IdentifierInfo *II = Result.getIdentifierInfo();
515 if (II == 0) break; // Not an identifier.
516
517 // Ask what the preprocessor keyword ID is.
518 switch (II->getPPKeywordID()) {
519 default: break;
520 // C99 6.10.1 - Conditional Inclusion.
521 case tok::pp_if:
522 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
523 case tok::pp_ifdef:
524 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
525 case tok::pp_ifndef:
526 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
527 case tok::pp_elif:
528 return HandleElifDirective(Result);
529 case tok::pp_else:
530 return HandleElseDirective(Result);
531 case tok::pp_endif:
532 return HandleEndifDirective(Result);
533
534 // C99 6.10.2 - Source File Inclusion.
535 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000536 return HandleIncludeDirective(Result); // Handle #include.
537 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000538 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000539
Chris Lattner141e71f2008-03-09 01:54:53 +0000540 // C99 6.10.3 - Macro Replacement.
541 case tok::pp_define:
542 return HandleDefineDirective(Result);
543 case tok::pp_undef:
544 return HandleUndefDirective(Result);
545
546 // C99 6.10.4 - Line Control.
547 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000548 return HandleLineDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000549
550 // C99 6.10.5 - Error Directive.
551 case tok::pp_error:
552 return HandleUserDiagnosticDirective(Result, false);
553
554 // C99 6.10.6 - Pragma Directive.
555 case tok::pp_pragma:
556 return HandlePragmaDirective();
557
558 // GNU Extensions.
559 case tok::pp_import:
560 return HandleImportDirective(Result);
561 case tok::pp_include_next:
562 return HandleIncludeNextDirective(Result);
563
564 case tok::pp_warning:
565 Diag(Result, diag::ext_pp_warning_directive);
566 return HandleUserDiagnosticDirective(Result, true);
567 case tok::pp_ident:
568 return HandleIdentSCCSDirective(Result);
569 case tok::pp_sccs:
570 return HandleIdentSCCSDirective(Result);
571 case tok::pp_assert:
572 //isExtension = true; // FIXME: implement #assert
573 break;
574 case tok::pp_unassert:
575 //isExtension = true; // FIXME: implement #unassert
576 break;
577 }
578 break;
579 }
580
Chris Lattner42aa16c2009-03-18 21:00:25 +0000581 // If this is a .S file, treat unknown # directives as non-preprocessor
582 // directives. This is important because # may be a comment or introduce
583 // various pseudo-ops. Just return the # token and push back the following
584 // token to be lexed next time.
585 if (getLangOptions().AsmPreprocessor) {
586 Token *Toks = new Token[2]();
587 // Return the # and the token after it.
588 Toks[0] = SavedHash;
589 Toks[1] = Result;
590 // Enter this token stream so that we re-lex the tokens. Make sure to
591 // enable macro expansion, in case the token after the # is an identifier
592 // that is expanded.
593 EnterTokenStream(Toks, 2, false, true);
594 return;
595 }
596
Chris Lattner141e71f2008-03-09 01:54:53 +0000597 // If we reached here, the preprocessing token is not valid!
598 Diag(Result, diag::err_pp_invalid_directive);
599
600 // Read the rest of the PP line.
601 DiscardUntilEndOfDirective();
602
603 // Okay, we're done parsing the directive.
604}
605
Chris Lattner478a18e2009-01-26 06:19:46 +0000606/// GetLineValue - Convert a numeric token into an unsigned value, emitting
607/// Diagnostic DiagID if it is invalid, and returning the value in Val.
608static bool GetLineValue(Token &DigitTok, unsigned &Val,
609 unsigned DiagID, Preprocessor &PP) {
610 if (DigitTok.isNot(tok::numeric_constant)) {
611 PP.Diag(DigitTok, DiagID);
612
613 if (DigitTok.isNot(tok::eom))
614 PP.DiscardUntilEndOfDirective();
615 return true;
616 }
617
618 llvm::SmallString<64> IntegerBuffer;
619 IntegerBuffer.resize(DigitTok.getLength());
620 const char *DigitTokBegin = &IntegerBuffer[0];
621 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
622 NumericLiteralParser Literal(DigitTokBegin, DigitTokBegin+ActualLength,
623 DigitTok.getLocation(), PP);
624 if (Literal.hadError)
625 return true; // Error already emitted.
626
627 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
628 PP.Diag(DigitTok, DiagID);
629 return true;
630 }
631
632 // Parse the integer literal into Result.
633 llvm::APInt APVal(32, 0);
634 if (Literal.GetIntegerValue(APVal)) {
635 // Overflow parsing integer literal.
636 PP.Diag(DigitTok, DiagID);
637 return true;
638 }
639 Val = APVal.getZExtValue();
640
641 // Reject 0, this is needed both by #line numbers and flags.
642 if (Val == 0) {
643 PP.Diag(DigitTok, DiagID);
644 PP.DiscardUntilEndOfDirective();
645 return true;
646 }
647
648 return false;
649}
650
Chris Lattner359cc442009-01-26 05:29:08 +0000651/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
652/// acceptable forms are:
653/// # line digit-sequence
654/// # line digit-sequence "s-char-sequence"
655void Preprocessor::HandleLineDirective(Token &Tok) {
656 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
657 // expanded.
658 Token DigitTok;
659 Lex(DigitTok);
660
Chris Lattner359cc442009-01-26 05:29:08 +0000661 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000662 unsigned LineNo;
663 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer, *this))
Chris Lattner359cc442009-01-26 05:29:08 +0000664 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000665
Chris Lattner478a18e2009-01-26 06:19:46 +0000666 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
667 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000668 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
669 if (LineNo >= LineLimit)
670 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
671
Chris Lattner5b9a5042009-01-26 07:57:50 +0000672 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000673 Token StrTok;
674 Lex(StrTok);
675
676 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
677 // string followed by eom.
678 if (StrTok.is(tok::eom))
679 ; // ok
680 else if (StrTok.isNot(tok::string_literal)) {
681 Diag(StrTok, diag::err_pp_line_invalid_filename);
682 DiscardUntilEndOfDirective();
683 return;
684 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000685 // Parse and validate the string, converting it into a unique ID.
686 StringLiteralParser Literal(&StrTok, 1, *this);
687 assert(!Literal.AnyWide && "Didn't allow wide strings in");
688 if (Literal.hadError)
689 return DiscardUntilEndOfDirective();
690 if (Literal.Pascal) {
691 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
692 return DiscardUntilEndOfDirective();
693 }
694 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
695 Literal.GetStringLength());
696
Chris Lattner359cc442009-01-26 05:29:08 +0000697 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000698 CheckEndOfDirective("line");
Chris Lattner359cc442009-01-26 05:29:08 +0000699 }
700
Chris Lattner4c4ea172009-02-03 21:52:55 +0000701 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Chris Lattner16629382009-03-27 17:13:49 +0000702
703 if (Callbacks)
704 Callbacks->FileChanged(DigitTok.getLocation(), PPCallbacks::RenameFile,
705 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000706}
707
Chris Lattner478a18e2009-01-26 06:19:46 +0000708/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
709/// marker directive.
710static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
711 bool &IsSystemHeader, bool &IsExternCHeader,
712 Preprocessor &PP) {
713 unsigned FlagVal;
714 Token FlagTok;
715 PP.Lex(FlagTok);
716 if (FlagTok.is(tok::eom)) return false;
717 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
718 return true;
719
720 if (FlagVal == 1) {
721 IsFileEntry = true;
722
723 PP.Lex(FlagTok);
724 if (FlagTok.is(tok::eom)) return false;
725 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
726 return true;
727 } else if (FlagVal == 2) {
728 IsFileExit = true;
729
Chris Lattner137b6a62009-02-04 06:25:26 +0000730 SourceManager &SM = PP.getSourceManager();
731 // If we are leaving the current presumed file, check to make sure the
732 // presumed include stack isn't empty!
733 FileID CurFileID =
734 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
735 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
736
737 // If there is no include loc (main file) or if the include loc is in a
738 // different physical file, then we aren't in a "1" line marker flag region.
739 SourceLocation IncLoc = PLoc.getIncludeLoc();
740 if (IncLoc.isInvalid() ||
741 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
742 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
743 PP.DiscardUntilEndOfDirective();
744 return true;
745 }
746
Chris Lattner478a18e2009-01-26 06:19:46 +0000747 PP.Lex(FlagTok);
748 if (FlagTok.is(tok::eom)) return false;
749 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
750 return true;
751 }
752
753 // We must have 3 if there are still flags.
754 if (FlagVal != 3) {
755 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000756 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000757 return true;
758 }
759
760 IsSystemHeader = true;
761
762 PP.Lex(FlagTok);
763 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000764 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000765 return true;
766
767 // We must have 4 if there is yet another flag.
768 if (FlagVal != 4) {
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 IsExternCHeader = true;
775
776 PP.Lex(FlagTok);
777 if (FlagTok.is(tok::eom)) return false;
778
779 // There are no more valid flags here.
780 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000781 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000782 return true;
783}
784
785/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
786/// one of the following forms:
787///
788/// # 42
789/// # 42 "file" ('1' | '2')?
790/// # 42 "file" ('1' | '2')? '3' '4'?
791///
792void Preprocessor::HandleDigitDirective(Token &DigitTok) {
793 // Validate the number and convert it to an unsigned. GNU does not have a
794 // line # limit other than it fit in 32-bits.
795 unsigned LineNo;
796 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
797 *this))
798 return;
799
800 Token StrTok;
801 Lex(StrTok);
802
803 bool IsFileEntry = false, IsFileExit = false;
804 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000805 int FilenameID = -1;
806
Chris Lattner478a18e2009-01-26 06:19:46 +0000807 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
808 // string followed by eom.
809 if (StrTok.is(tok::eom))
810 ; // ok
811 else if (StrTok.isNot(tok::string_literal)) {
812 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000813 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000814 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000815 // Parse and validate the string, converting it into a unique ID.
816 StringLiteralParser Literal(&StrTok, 1, *this);
817 assert(!Literal.AnyWide && "Didn't allow wide strings in");
818 if (Literal.hadError)
819 return DiscardUntilEndOfDirective();
820 if (Literal.Pascal) {
821 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
822 return DiscardUntilEndOfDirective();
823 }
824 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
825 Literal.GetStringLength());
826
Chris Lattner478a18e2009-01-26 06:19:46 +0000827 // If a filename was present, read any flags that are present.
828 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000829 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000830 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000831 }
Chris Lattner137b6a62009-02-04 06:25:26 +0000832
Chris Lattner9d79eba2009-02-04 05:21:58 +0000833 // Create a line note with this information.
834 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
835 IsFileEntry, IsFileExit,
836 IsSystemHeader, IsExternCHeader);
Chris Lattner16629382009-03-27 17:13:49 +0000837
838 // If the preprocessor has callbacks installed, notify them of the #line
839 // change. This is used so that the line marker comes out in -E mode for
840 // example.
841 if (Callbacks) {
842 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
843 if (IsFileEntry)
844 Reason = PPCallbacks::EnterFile;
845 else if (IsFileExit)
846 Reason = PPCallbacks::ExitFile;
847 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
848 if (IsExternCHeader)
849 FileKind = SrcMgr::C_ExternCSystem;
850 else if (IsSystemHeader)
851 FileKind = SrcMgr::C_System;
852
853 Callbacks->FileChanged(DigitTok.getLocation(), Reason, FileKind);
854 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000855}
856
857
Chris Lattner099dd052009-01-26 05:30:54 +0000858/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
859///
Chris Lattner141e71f2008-03-09 01:54:53 +0000860void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
861 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000862 // PTH doesn't emit #warning or #error directives.
863 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000864 return CurPTHLexer->DiscardToEndOfLine();
865
Chris Lattner141e71f2008-03-09 01:54:53 +0000866 // Read the rest of the line raw. We do this because we don't want macros
867 // to be expanded and we don't require that the tokens be valid preprocessing
868 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
869 // collapse multiple consequtive white space between tokens, but this isn't
870 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000871 std::string Message = CurLexer->ReadToEndOfLine();
872 if (isWarning)
873 Diag(Tok, diag::pp_hash_warning) << Message;
874 else
875 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000876}
877
878/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
879///
880void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
881 // Yes, this directive is an extension.
882 Diag(Tok, diag::ext_pp_ident_directive);
883
884 // Read the string argument.
885 Token StrTok;
886 Lex(StrTok);
887
888 // If the token kind isn't a string, it's a malformed directive.
889 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000890 StrTok.isNot(tok::wide_string_literal)) {
891 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000892 if (StrTok.isNot(tok::eom))
893 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000894 return;
895 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000896
897 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000898 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000899
900 if (Callbacks)
901 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
902}
903
904//===----------------------------------------------------------------------===//
905// Preprocessor Include Directive Handling.
906//===----------------------------------------------------------------------===//
907
908/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
909/// checked and spelled filename, e.g. as an operand of #include. This returns
910/// true if the input filename was in <>'s or false if it were in ""'s. The
911/// caller is expected to provide a buffer that is large enough to hold the
912/// spelling of the filename, but is also expected to handle the case when
913/// this method decides to use a different buffer.
914bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
915 const char *&BufStart,
916 const char *&BufEnd) {
917 // Get the text form of the filename.
918 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
919
920 // Make sure the filename is <x> or "x".
921 bool isAngled;
922 if (BufStart[0] == '<') {
923 if (BufEnd[-1] != '>') {
924 Diag(Loc, diag::err_pp_expects_filename);
925 BufStart = 0;
926 return true;
927 }
928 isAngled = true;
929 } else if (BufStart[0] == '"') {
930 if (BufEnd[-1] != '"') {
931 Diag(Loc, diag::err_pp_expects_filename);
932 BufStart = 0;
933 return true;
934 }
935 isAngled = false;
936 } else {
937 Diag(Loc, diag::err_pp_expects_filename);
938 BufStart = 0;
939 return true;
940 }
941
942 // Diagnose #include "" as invalid.
943 if (BufEnd-BufStart <= 2) {
944 Diag(Loc, diag::err_pp_empty_filename);
945 BufStart = 0;
946 return "";
947 }
948
949 // Skip the brackets.
950 ++BufStart;
951 --BufEnd;
952 return isAngled;
953}
954
955/// ConcatenateIncludeName - Handle cases where the #include name is expanded
956/// from a macro as multiple tokens, which need to be glued together. This
957/// occurs for code like:
958/// #define FOO <a/b.h>
959/// #include FOO
960/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
961///
962/// This code concatenates and consumes tokens up to the '>' token. It returns
963/// false if the > was found, otherwise it returns true if it finds and consumes
964/// the EOM marker.
965static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
966 Preprocessor &PP) {
967 Token CurTok;
968
969 PP.Lex(CurTok);
970 while (CurTok.isNot(tok::eom)) {
971 // Append the spelling of this token to the buffer. If there was a space
972 // before it, add it now.
973 if (CurTok.hasLeadingSpace())
974 FilenameBuffer.push_back(' ');
975
976 // Get the spelling of the token, directly into FilenameBuffer if possible.
977 unsigned PreAppendSize = FilenameBuffer.size();
978 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
979
980 const char *BufPtr = &FilenameBuffer[PreAppendSize];
981 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
982
983 // If the token was spelled somewhere else, copy it into FilenameBuffer.
984 if (BufPtr != &FilenameBuffer[PreAppendSize])
985 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
986
987 // Resize FilenameBuffer to the correct size.
988 if (CurTok.getLength() != ActualLen)
989 FilenameBuffer.resize(PreAppendSize+ActualLen);
990
991 // If we found the '>' marker, return success.
992 if (CurTok.is(tok::greater))
993 return false;
994
995 PP.Lex(CurTok);
996 }
997
998 // If we hit the eom marker, emit an error and return true so that the caller
999 // knows the EOM has been read.
1000 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1001 return true;
1002}
1003
1004/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1005/// file to be included from the lexer, then include it! This is a common
1006/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001007/// #import. LookupFrom is set when this is a #include_next directive, it
1008/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001009void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1010 const DirectoryLookup *LookupFrom,
1011 bool isImport) {
1012
1013 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001014 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001015
1016 // Reserve a buffer to get the spelling.
1017 llvm::SmallVector<char, 128> FilenameBuffer;
1018 const char *FilenameStart, *FilenameEnd;
1019
1020 switch (FilenameTok.getKind()) {
1021 case tok::eom:
1022 // If the token kind is EOM, the error has already been diagnosed.
1023 return;
1024
1025 case tok::angle_string_literal:
1026 case tok::string_literal: {
1027 FilenameBuffer.resize(FilenameTok.getLength());
1028 FilenameStart = &FilenameBuffer[0];
1029 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1030 FilenameEnd = FilenameStart+Len;
1031 break;
1032 }
1033
1034 case tok::less:
1035 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1036 // case, glue the tokens together into FilenameBuffer and interpret those.
1037 FilenameBuffer.push_back('<');
1038 if (ConcatenateIncludeName(FilenameBuffer, *this))
1039 return; // Found <eom> but no ">"? Diagnostic already emitted.
1040 FilenameStart = &FilenameBuffer[0];
1041 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1042 break;
1043 default:
1044 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1045 DiscardUntilEndOfDirective();
1046 return;
1047 }
1048
1049 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
1050 FilenameStart, FilenameEnd);
1051 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1052 // error.
1053 if (FilenameStart == 0) {
1054 DiscardUntilEndOfDirective();
1055 return;
1056 }
1057
Chris Lattnerfd105112009-04-08 20:53:24 +00001058 // Verify that there is nothing after the filename, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +00001059 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getName());
Chris Lattner141e71f2008-03-09 01:54:53 +00001060
1061 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001062 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1063 Diag(FilenameTok, diag::err_pp_include_too_deep);
1064 return;
1065 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001066
1067 // Search include directories.
1068 const DirectoryLookup *CurDir;
1069 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1070 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001071 if (File == 0) {
1072 Diag(FilenameTok, diag::err_pp_file_not_found)
1073 << std::string(FilenameStart, FilenameEnd);
1074 return;
1075 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001076
Chris Lattner72181832008-09-26 20:12:23 +00001077 // Ask HeaderInfo if we should enter this #include file. If not, #including
1078 // this file will have no effect.
1079 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001080 return;
Chris Lattner72181832008-09-26 20:12:23 +00001081
1082 // The #included file will be considered to be a system header if either it is
1083 // in a system include directory, or if the #includer is a system include
1084 // header.
Chris Lattner9d728512008-10-27 01:19:25 +00001085 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001086 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001087 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Chris Lattner72181832008-09-26 20:12:23 +00001088
Chris Lattner141e71f2008-03-09 01:54:53 +00001089 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001090 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1091 FileCharacter);
1092 if (FID.isInvalid()) {
Chris Lattner56b05c82008-11-18 08:02:48 +00001093 Diag(FilenameTok, diag::err_pp_file_not_found)
1094 << std::string(FilenameStart, FilenameEnd);
1095 return;
1096 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001097
1098 // Finally, if all is good, enter the new file!
Chris Lattner2b2453a2009-01-17 06:22:33 +00001099 EnterSourceFile(FID, CurDir);
Chris Lattner141e71f2008-03-09 01:54:53 +00001100}
1101
1102/// HandleIncludeNextDirective - Implements #include_next.
1103///
1104void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1105 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1106
1107 // #include_next is like #include, except that we start searching after
1108 // the current found directory. If we can't do this, issue a
1109 // diagnostic.
1110 const DirectoryLookup *Lookup = CurDirLookup;
1111 if (isInPrimaryFile()) {
1112 Lookup = 0;
1113 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1114 } else if (Lookup == 0) {
1115 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1116 } else {
1117 // Start looking up in the next directory.
1118 ++Lookup;
1119 }
1120
1121 return HandleIncludeDirective(IncludeNextTok, Lookup);
1122}
1123
1124/// HandleImportDirective - Implements #import.
1125///
1126void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001127 if (!Features.ObjC1) // #import is standard for ObjC.
1128 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner141e71f2008-03-09 01:54:53 +00001129
1130 return HandleIncludeDirective(ImportTok, 0, true);
1131}
1132
Chris Lattnerde076652009-04-08 18:46:40 +00001133/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1134/// pseudo directive in the predefines buffer. This handles it by sucking all
1135/// tokens through the preprocessor and discarding them (only keeping the side
1136/// effects on the preprocessor).
1137void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1138 // This directive should only occur in the predefines buffer. If not, emit an
1139 // error and reject it.
1140 SourceLocation Loc = IncludeMacrosTok.getLocation();
1141 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1142 Diag(IncludeMacrosTok.getLocation(),
1143 diag::pp_include_macros_out_of_predefines);
1144 DiscardUntilEndOfDirective();
1145 return;
1146 }
1147
Chris Lattnerfd105112009-04-08 20:53:24 +00001148 // Treat this as a normal #include for checking purposes. If this is
1149 // successful, it will push a new lexer onto the include stack.
1150 HandleIncludeDirective(IncludeMacrosTok, 0, false);
1151
1152 Token TmpTok;
1153 do {
1154 Lex(TmpTok);
1155 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1156 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001157}
1158
Chris Lattner141e71f2008-03-09 01:54:53 +00001159//===----------------------------------------------------------------------===//
1160// Preprocessor Macro Directive Handling.
1161//===----------------------------------------------------------------------===//
1162
1163/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1164/// definition has just been read. Lex the rest of the arguments and the
1165/// closing ), updating MI with what we learn. Return true if an error occurs
1166/// parsing the arg list.
1167bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1168 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1169
1170 Token Tok;
1171 while (1) {
1172 LexUnexpandedToken(Tok);
1173 switch (Tok.getKind()) {
1174 case tok::r_paren:
1175 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001176 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001177 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001178 // Otherwise we have #define FOO(A,)
1179 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1180 return true;
1181 case tok::ellipsis: // #define X(... -> C99 varargs
1182 // Warn if use of C99 feature in non-C99 mode.
1183 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1184
1185 // Lex the token after the identifier.
1186 LexUnexpandedToken(Tok);
1187 if (Tok.isNot(tok::r_paren)) {
1188 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1189 return true;
1190 }
1191 // Add the __VA_ARGS__ identifier as an argument.
1192 Arguments.push_back(Ident__VA_ARGS__);
1193 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001194 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001195 return false;
1196 case tok::eom: // #define X(
1197 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1198 return true;
1199 default:
1200 // Handle keywords and identifiers here to accept things like
1201 // #define Foo(for) for.
1202 IdentifierInfo *II = Tok.getIdentifierInfo();
1203 if (II == 0) {
1204 // #define X(1
1205 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1206 return true;
1207 }
1208
1209 // If this is already used as an argument, it is used multiple times (e.g.
1210 // #define X(A,A.
1211 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1212 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001213 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001214 return true;
1215 }
1216
1217 // Add the argument to the macro info.
1218 Arguments.push_back(II);
1219
1220 // Lex the token after the identifier.
1221 LexUnexpandedToken(Tok);
1222
1223 switch (Tok.getKind()) {
1224 default: // #define X(A B
1225 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1226 return true;
1227 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001228 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001229 return false;
1230 case tok::comma: // #define X(A,
1231 break;
1232 case tok::ellipsis: // #define X(A... -> GCC extension
1233 // Diagnose extension.
1234 Diag(Tok, diag::ext_named_variadic_macro);
1235
1236 // Lex the token after the identifier.
1237 LexUnexpandedToken(Tok);
1238 if (Tok.isNot(tok::r_paren)) {
1239 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1240 return true;
1241 }
1242
1243 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001244 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001245 return false;
1246 }
1247 }
1248 }
1249}
1250
1251/// HandleDefineDirective - Implements #define. This consumes the entire macro
1252/// line then lets the caller lex the next real token.
1253void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1254 ++NumDefined;
1255
1256 Token MacroNameTok;
1257 ReadMacroName(MacroNameTok, 1);
1258
1259 // Error reading macro name? If so, diagnostic already issued.
1260 if (MacroNameTok.is(tok::eom))
1261 return;
1262
1263 // If we are supposed to keep comments in #defines, reenable comment saving
1264 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001265 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Chris Lattner141e71f2008-03-09 01:54:53 +00001266
1267 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001268 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001269
1270 Token Tok;
1271 LexUnexpandedToken(Tok);
1272
1273 // If this is a function-like macro definition, parse the argument list,
1274 // marking each of the identifiers as being used as macro arguments. Also,
1275 // check other constraints on the first token of the macro body.
1276 if (Tok.is(tok::eom)) {
1277 // If there is no body to this macro, we have no special handling here.
1278 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
1279 // This is a function-like macro definition. Read the argument list.
1280 MI->setIsFunctionLike();
1281 if (ReadMacroDefinitionArgList(MI)) {
1282 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001283 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001284 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001285 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001286 DiscardUntilEndOfDirective();
1287 return;
1288 }
1289
1290 // Read the first token after the arg list for down below.
1291 LexUnexpandedToken(Tok);
1292 } else if (!Tok.hasLeadingSpace()) {
1293 // C99 requires whitespace between the macro definition and the body. Emit
1294 // a diagnostic for something like "#define X+".
1295 if (Features.C99) {
1296 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1297 } else {
1298 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1299 // one in some cases!
1300 }
1301 } else {
1302 // This is a normal token with leading space. Clear the leading space
1303 // marker on the first token to get proper expansion.
1304 Tok.clearFlag(Token::LeadingSpace);
1305 }
1306
1307 // If this is a definition of a variadic C99 function-like macro, not using
1308 // the GNU named varargs extension, enabled __VA_ARGS__.
1309
1310 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1311 // This gets unpoisoned where it is allowed.
1312 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1313 if (MI->isC99Varargs())
1314 Ident__VA_ARGS__->setIsPoisoned(false);
1315
1316 // Read the rest of the macro body.
1317 if (MI->isObjectLike()) {
1318 // Object-like macros are very simple, just read their body.
1319 while (Tok.isNot(tok::eom)) {
1320 MI->AddTokenToBody(Tok);
1321 // Get the next token of the macro.
1322 LexUnexpandedToken(Tok);
1323 }
1324
1325 } else {
1326 // Otherwise, read the body of a function-like macro. This has to validate
1327 // the # (stringize) operator.
1328 while (Tok.isNot(tok::eom)) {
1329 MI->AddTokenToBody(Tok);
1330
1331 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1332 // parameters in function-like macro expansions.
1333 if (Tok.isNot(tok::hash)) {
1334 // Get the next token of the macro.
1335 LexUnexpandedToken(Tok);
1336 continue;
1337 }
1338
1339 // Get the next token of the macro.
1340 LexUnexpandedToken(Tok);
1341
1342 // Not a macro arg identifier?
1343 if (!Tok.getIdentifierInfo() ||
1344 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1345 Diag(Tok, diag::err_pp_stringize_not_parameter);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001346 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001347
1348 // Disable __VA_ARGS__ again.
1349 Ident__VA_ARGS__->setIsPoisoned(true);
1350 return;
1351 }
1352
1353 // Things look ok, add the param name token to the macro.
1354 MI->AddTokenToBody(Tok);
1355
1356 // Get the next token of the macro.
1357 LexUnexpandedToken(Tok);
1358 }
1359 }
1360
1361
1362 // Disable __VA_ARGS__ again.
1363 Ident__VA_ARGS__->setIsPoisoned(true);
1364
1365 // Check that there is no paste (##) operator at the begining or end of the
1366 // replacement list.
1367 unsigned NumTokens = MI->getNumTokens();
1368 if (NumTokens != 0) {
1369 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1370 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001371 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001372 return;
1373 }
1374 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1375 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001376 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001377 return;
1378 }
1379 }
1380
1381 // If this is the primary source file, remember that this macro hasn't been
1382 // used yet.
1383 if (isInPrimaryFile())
1384 MI->setIsUsed(false);
1385
1386 // Finally, if this identifier already had a macro defined for it, verify that
1387 // the macro bodies are identical and free the old definition.
1388 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001389 // It is very common for system headers to have tons of macro redefinitions
1390 // and for warnings to be disabled in system headers. If this is the case,
1391 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001392 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001393 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1394 if (!OtherMI->isUsed())
1395 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001396
Chris Lattner41c3ae12009-01-16 19:50:11 +00001397 // Macros must be identical. This means all tokes and whitespace
1398 // separation must be the same. C99 6.10.3.2.
1399 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1400 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1401 << MacroNameTok.getIdentifierInfo();
1402 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1403 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001404 }
Chris Lattner41c3ae12009-01-16 19:50:11 +00001405
Ted Kremenek0ea76722008-12-15 19:56:42 +00001406 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001407 }
1408
1409 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001410
1411 // If the callbacks want to know, tell them about the macro definition.
1412 if (Callbacks)
1413 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001414}
1415
1416/// HandleUndefDirective - Implements #undef.
1417///
1418void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1419 ++NumUndefined;
1420
1421 Token MacroNameTok;
1422 ReadMacroName(MacroNameTok, 2);
1423
1424 // Error reading macro name? If so, diagnostic already issued.
1425 if (MacroNameTok.is(tok::eom))
1426 return;
1427
1428 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001429 CheckEndOfDirective("undef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001430
1431 // Okay, we finally have a valid identifier to undef.
1432 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1433
1434 // If the macro is not defined, this is a noop undef, just return.
1435 if (MI == 0) return;
1436
1437 if (!MI->isUsed())
1438 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1439
1440 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001441 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001442 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1443}
1444
1445
1446//===----------------------------------------------------------------------===//
1447// Preprocessor Conditional Directive Handling.
1448//===----------------------------------------------------------------------===//
1449
1450/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1451/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1452/// if any tokens have been returned or pp-directives activated before this
1453/// #ifndef has been lexed.
1454///
1455void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1456 bool ReadAnyTokensBeforeDirective) {
1457 ++NumIf;
1458 Token DirectiveTok = Result;
1459
1460 Token MacroNameTok;
1461 ReadMacroName(MacroNameTok);
1462
1463 // Error reading macro name? If so, diagnostic already issued.
1464 if (MacroNameTok.is(tok::eom)) {
1465 // Skip code until we get to #endif. This helps with recovery by not
1466 // emitting an error when the #endif is reached.
1467 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1468 /*Foundnonskip*/false, /*FoundElse*/false);
1469 return;
1470 }
1471
1472 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001473 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001474
Ted Kremenek60e45d42008-11-18 00:34:22 +00001475 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001476 // If the start of a top-level #ifdef, inform MIOpt.
1477 if (!ReadAnyTokensBeforeDirective) {
1478 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001479 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001480 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001481 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001482 }
1483
1484 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1485 MacroInfo *MI = getMacroInfo(MII);
1486
1487 // If there is a macro, process it.
1488 if (MI) // Mark it used.
1489 MI->setIsUsed(true);
1490
1491 // Should we include the stuff contained by this directive?
1492 if (!MI == isIfndef) {
1493 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001494 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001495 /*foundnonskip*/true, /*foundelse*/false);
1496 } else {
1497 // No, skip the contents of this block and return the first token after it.
1498 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1499 /*Foundnonskip*/false,
1500 /*FoundElse*/false);
1501 }
1502}
1503
1504/// HandleIfDirective - Implements the #if directive.
1505///
1506void Preprocessor::HandleIfDirective(Token &IfToken,
1507 bool ReadAnyTokensBeforeDirective) {
1508 ++NumIf;
1509
1510 // Parse and evaluation the conditional expression.
1511 IdentifierInfo *IfNDefMacro = 0;
1512 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1513
Nuno Lopes0049db62008-06-01 18:31:24 +00001514
1515 // If this condition is equivalent to #ifndef X, and if this is the first
1516 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001517 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001518 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001519 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001520 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001521 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001522 }
1523
Chris Lattner141e71f2008-03-09 01:54:53 +00001524 // Should we include the stuff contained by this directive?
1525 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001526 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001527 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001528 /*foundnonskip*/true, /*foundelse*/false);
1529 } else {
1530 // No, skip the contents of this block and return the first token after it.
1531 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1532 /*FoundElse*/false);
1533 }
1534}
1535
1536/// HandleEndifDirective - Implements the #endif directive.
1537///
1538void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1539 ++NumEndif;
1540
1541 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001542 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +00001543
1544 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001545 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001546 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001547 Diag(EndifToken, diag::err_pp_endif_without_if);
1548 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001549 }
1550
1551 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001552 if (CurPPLexer->getConditionalStackDepth() == 0)
1553 CurPPLexer->MIOpt.ExitTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001554
Ted Kremenek60e45d42008-11-18 00:34:22 +00001555 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001556 "This code should only be reachable in the non-skipping case!");
1557}
1558
1559
1560void Preprocessor::HandleElseDirective(Token &Result) {
1561 ++NumElse;
1562
1563 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001564 CheckEndOfDirective("else");
Chris Lattner141e71f2008-03-09 01:54:53 +00001565
1566 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001567 if (CurPPLexer->popConditionalLevel(CI)) {
1568 Diag(Result, diag::pp_err_else_without_if);
1569 return;
1570 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001571
1572 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001573 if (CurPPLexer->getConditionalStackDepth() == 0)
1574 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001575
1576 // If this is a #else with a #else before it, report the error.
1577 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1578
1579 // Finally, skip the rest of the contents of this block and return the first
1580 // token after it.
1581 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1582 /*FoundElse*/true);
1583}
1584
1585void Preprocessor::HandleElifDirective(Token &ElifToken) {
1586 ++NumElse;
1587
1588 // #elif directive in a non-skipping conditional... start skipping.
1589 // We don't care what the condition is, because we will always skip it (since
1590 // the block immediately before it was included).
1591 DiscardUntilEndOfDirective();
1592
1593 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001594 if (CurPPLexer->popConditionalLevel(CI)) {
1595 Diag(ElifToken, diag::pp_err_elif_without_if);
1596 return;
1597 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001598
1599 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001600 if (CurPPLexer->getConditionalStackDepth() == 0)
1601 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001602
1603 // If this is a #elif with a #else before it, report the error.
1604 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1605
1606 // Finally, skip the rest of the contents of this block and return the first
1607 // token after it.
1608 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1609 /*FoundElse*/CI.FoundElse);
1610}
1611