blob: e4b36fd15733d3496d4dc0c4c6de5eda96ccaf94 [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
Chris Lattnerab82f412009-04-17 23:30:53 +0000104/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
105/// true, then we consider macros that expand to zero tokens as being ok.
106void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000107 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000108 // Lex unexpanded tokens for most directives: macros might expand to zero
109 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
110 // #line) allow empty macros.
111 if (EnableMacros)
112 Lex(Tmp);
113 else
114 LexUnexpandedToken(Tmp);
Chris Lattner141e71f2008-03-09 01:54:53 +0000115
116 // There should be no tokens after the directive, but we allow them as an
117 // extension.
118 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
119 LexUnexpandedToken(Tmp);
120
121 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000122 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
123 // because it is more trouble than it is worth to insert /**/ and check that
124 // there is no /**/ in the range also.
125 CodeModificationHint FixItHint;
126 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
127 FixItHint = CodeModificationHint::CreateInsertion(Tmp.getLocation(),"//");
128 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << FixItHint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000129 DiscardUntilEndOfDirective();
130 }
131}
132
133
134
135/// SkipExcludedConditionalBlock - We just read a #if or related directive and
136/// decided that the subsequent tokens are in the #if'd out portion of the
137/// file. Lex the rest of the file, until we see an #endif. If
138/// FoundNonSkipPortion is true, then we have already emitted code for part of
139/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
140/// is true, then #else directives are ok, if not, then we have already seen one
141/// so a #else directive is a duplicate. When this returns, the caller can lex
142/// the first valid token.
143void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
144 bool FoundNonSkipPortion,
145 bool FoundElse) {
146 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000147 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000148
Ted Kremenek60e45d42008-11-18 00:34:22 +0000149 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000150 FoundNonSkipPortion, FoundElse);
151
Ted Kremenek268ee702008-12-12 18:34:08 +0000152 if (CurPTHLexer) {
153 PTHSkipExcludedConditionalBlock();
154 return;
155 }
156
Chris Lattner141e71f2008-03-09 01:54:53 +0000157 // Enter raw mode to disable identifier lookup (and thus macro expansion),
158 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000159 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000160 Token Tok;
161 while (1) {
Ted Kremenekf6452c52008-11-18 01:04:47 +0000162 if (CurLexer)
163 CurLexer->Lex(Tok);
164 else
165 CurPTHLexer->Lex(Tok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000166
167 // If this is the end of the buffer, we have an error.
168 if (Tok.is(tok::eof)) {
169 // Emit errors for each unterminated conditional on the stack, including
170 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000171 while (!CurPPLexer->ConditionalStack.empty()) {
172 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000173 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000174 CurPPLexer->ConditionalStack.pop_back();
Chris Lattner141e71f2008-03-09 01:54:53 +0000175 }
176
177 // Just return and let the caller lex after this #include.
178 break;
179 }
180
181 // If this token is not a preprocessor directive, just skip it.
182 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
183 continue;
184
185 // We just parsed a # character at the start of a line, so we're in
186 // directive mode. Tell the lexer this so any newlines we see will be
187 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000188 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000189 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000190
191
192 // Read the next token, the directive flavor.
193 LexUnexpandedToken(Tok);
194
195 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
196 // something bogus), skip it.
197 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000198 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000199 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000200 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000201 continue;
202 }
203
204 // If the first letter isn't i or e, it isn't intesting to us. We know that
205 // this is safe in the face of spelling differences, because there is no way
206 // to spell an i/e in a strange way that is another letter. Skipping this
207 // allows us to avoid looking up the identifier info for #define/#undef and
208 // other common directives.
209 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
210 char FirstChar = RawCharData[0];
211 if (FirstChar >= 'a' && FirstChar <= 'z' &&
212 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000213 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000214 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000215 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000216 continue;
217 }
218
219 // Get the identifier name without trigraphs or embedded newlines. Note
220 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
221 // when skipping.
222 // TODO: could do this with zero copies in the no-clean case by using
223 // strncmp below.
224 char Directive[20];
225 unsigned IdLen;
226 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
227 IdLen = Tok.getLength();
228 memcpy(Directive, RawCharData, IdLen);
229 Directive[IdLen] = 0;
230 } else {
231 std::string DirectiveStr = getSpelling(Tok);
232 IdLen = DirectiveStr.size();
233 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000234 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000235 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000236 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000237 continue;
238 }
239 memcpy(Directive, &DirectiveStr[0], IdLen);
240 Directive[IdLen] = 0;
Chris Lattner202fd2c2009-01-27 05:34:03 +0000241 FirstChar = Directive[0];
Chris Lattner141e71f2008-03-09 01:54:53 +0000242 }
243
244 if (FirstChar == 'i' && Directive[1] == 'f') {
245 if ((IdLen == 2) || // "if"
246 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
247 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
248 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
249 // bother parsing the condition.
250 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000251 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000252 /*foundnonskip*/false,
253 /*fnddelse*/false);
254 }
255 } else if (FirstChar == 'e') {
256 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000257 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000258 PPConditionalInfo CondInfo;
259 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000260 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000261 InCond = InCond; // Silence warning in no-asserts mode.
262 assert(!InCond && "Can't be skipping if not in a conditional!");
263
264 // If we popped the outermost skipping block, we're done skipping!
265 if (!CondInfo.WasSkipping)
266 break;
267 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
268 // #else directive in a skipping conditional. If not in some other
269 // skipping conditional, and if #else hasn't already been seen, enter it
270 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000271 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000272 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000273
274 // If this is a #else with a #else before it, report the error.
275 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
276
277 // Note that we've seen a #else in this conditional.
278 CondInfo.FoundElse = true;
279
280 // If the conditional is at the top level, and the #if block wasn't
281 // entered, enter the #else block now.
282 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
283 CondInfo.FoundNonSkip = true;
284 break;
285 }
286 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000287 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000288
289 bool ShouldEnter;
290 // If this is in a skipping block or if we're already handled this #if
291 // block, don't bother parsing the condition.
292 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
293 DiscardUntilEndOfDirective();
294 ShouldEnter = false;
295 } else {
296 // Restore the value of LexingRawMode so that identifiers are
297 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000298 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
299 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000300 IdentifierInfo *IfNDefMacro = 0;
301 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000302 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 }
304
305 // If this is a #elif with a #else before it, report the error.
306 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
307
308 // If this condition is true, enter it!
309 if (ShouldEnter) {
310 CondInfo.FoundNonSkip = true;
311 break;
312 }
313 }
314 }
315
Ted Kremenek60e45d42008-11-18 00:34:22 +0000316 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000317 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000318 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000319 }
320
321 // Finally, if we are out of the conditional (saw an #endif or ran off the end
322 // of the file, just stop skipping and return to lexing whatever came after
323 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000324 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000325}
326
Ted Kremenek268ee702008-12-12 18:34:08 +0000327void Preprocessor::PTHSkipExcludedConditionalBlock() {
328
329 while(1) {
330 assert(CurPTHLexer);
331 assert(CurPTHLexer->LexingRawMode == false);
332
333 // Skip to the next '#else', '#elif', or #endif.
334 if (CurPTHLexer->SkipBlock()) {
335 // We have reached an #endif. Both the '#' and 'endif' tokens
336 // have been consumed by the PTHLexer. Just pop off the condition level.
337 PPConditionalInfo CondInfo;
338 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
339 InCond = InCond; // Silence warning in no-asserts mode.
340 assert(!InCond && "Can't be skipping if not in a conditional!");
341 break;
342 }
343
344 // We have reached a '#else' or '#elif'. Lex the next token to get
345 // the directive flavor.
346 Token Tok;
347 LexUnexpandedToken(Tok);
348
349 // We can actually look up the IdentifierInfo here since we aren't in
350 // raw mode.
351 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
352
353 if (K == tok::pp_else) {
354 // #else: Enter the else condition. We aren't in a nested condition
355 // since we skip those. We're always in the one matching the last
356 // blocked we skipped.
357 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
358 // Note that we've seen a #else in this conditional.
359 CondInfo.FoundElse = true;
360
361 // If the #if block wasn't entered then enter the #else block now.
362 if (!CondInfo.FoundNonSkip) {
363 CondInfo.FoundNonSkip = true;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000364
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000365 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000366 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000367 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000368 CurPTHLexer->ParsingPreprocessorDirective = false;
369
Ted Kremenek268ee702008-12-12 18:34:08 +0000370 break;
371 }
372
373 // Otherwise skip this block.
374 continue;
375 }
376
377 assert(K == tok::pp_elif);
378 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
379
380 // If this is a #elif with a #else before it, report the error.
381 if (CondInfo.FoundElse)
382 Diag(Tok, diag::pp_err_elif_after_else);
383
384 // If this is in a skipping block or if we're already handled this #if
385 // block, don't bother parsing the condition. We just skip this block.
386 if (CondInfo.FoundNonSkip)
387 continue;
388
389 // Evaluate the condition of the #elif.
390 IdentifierInfo *IfNDefMacro = 0;
391 CurPTHLexer->ParsingPreprocessorDirective = true;
392 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
393 CurPTHLexer->ParsingPreprocessorDirective = false;
394
395 // If this condition is true, enter it!
396 if (ShouldEnter) {
397 CondInfo.FoundNonSkip = true;
398 break;
399 }
400
401 // Otherwise, skip this block and go to the next one.
402 continue;
403 }
404}
405
Chris Lattner10725092008-03-09 04:17:44 +0000406/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
407/// return null on failure. isAngled indicates whether the file reference is
408/// for system #include's or not (i.e. using <> instead of "").
409const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
410 const char *FilenameEnd,
411 bool isAngled,
412 const DirectoryLookup *FromDir,
413 const DirectoryLookup *&CurDir) {
414 // If the header lookup mechanism may be relative to the current file, pass in
415 // info about where the current file is.
416 const FileEntry *CurFileEnt = 0;
417 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000418 FileID FID = getCurrentFileLexer()->getFileID();
419 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000420
421 // If there is no file entry associated with this file, it must be the
422 // predefines buffer. Any other file is not lexed with a normal lexer, so
423 // it won't be scanned for preprocessor directives. If we have the
424 // predefines buffer, resolve #include references (which come from the
425 // -include command line argument) as if they came from the main file, this
426 // affects file lookup etc.
427 if (CurFileEnt == 0) {
428 FID = SourceMgr.getMainFileID();
429 CurFileEnt = SourceMgr.getFileEntryForID(FID);
430 }
Chris Lattner10725092008-03-09 04:17:44 +0000431 }
432
433 // Do a standard file entry lookup.
434 CurDir = CurDirLookup;
435 const FileEntry *FE =
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000436 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
437 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner10725092008-03-09 04:17:44 +0000438 if (FE) return FE;
439
440 // Otherwise, see if this is a subframework header. If so, this is relative
441 // to one of the headers on the #include stack. Walk the list of the current
442 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000443 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000444 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000445 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
446 CurFileEnt)))
447 return FE;
448 }
449
450 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
451 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000452 if (IsFileLexer(ISEntry)) {
Chris Lattner10725092008-03-09 04:17:44 +0000453 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000454 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000455 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
456 FilenameEnd, CurFileEnt)))
457 return FE;
458 }
459 }
460
461 // Otherwise, we really couldn't find the file.
462 return 0;
463}
464
Chris Lattner141e71f2008-03-09 01:54:53 +0000465
466//===----------------------------------------------------------------------===//
467// Preprocessor Directive Handling.
468//===----------------------------------------------------------------------===//
469
470/// HandleDirective - This callback is invoked when the lexer sees a # token
471/// at the start of a line. This consumes the directive, modifies the
472/// lexer/preprocessor state, and advances the lexer(s) so that the next token
473/// read is the correct one.
474void Preprocessor::HandleDirective(Token &Result) {
475 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
476
477 // We just parsed a # character at the start of a line, so we're in directive
478 // mode. Tell the lexer this so any newlines we see will be converted into an
479 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000480 CurPPLexer->ParsingPreprocessorDirective = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000481
482 ++NumDirectives;
483
484 // We are about to read a token. For the multiple-include optimization FA to
485 // work, we have to remember if we had read any tokens *before* this
486 // pp-directive.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000487 bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Chris Lattner141e71f2008-03-09 01:54:53 +0000488
Chris Lattner42aa16c2009-03-18 21:00:25 +0000489 // Save the '#' token in case we need to return it later.
490 Token SavedHash = Result;
491
Chris Lattner141e71f2008-03-09 01:54:53 +0000492 // Read the next token, the directive flavor. This isn't expanded due to
493 // C99 6.10.3p8.
494 LexUnexpandedToken(Result);
495
496 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
497 // #define A(x) #x
498 // A(abc
499 // #warning blah
500 // def)
501 // If so, the user is relying on non-portable behavior, emit a diagnostic.
502 if (InMacroArgs)
503 Diag(Result, diag::ext_embedded_directive);
504
505TryAgain:
506 switch (Result.getKind()) {
507 case tok::eom:
508 return; // null directive.
509 case tok::comment:
510 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
511 LexUnexpandedToken(Result);
512 goto TryAgain;
513
Chris Lattner478a18e2009-01-26 06:19:46 +0000514 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000515 if (getLangOptions().AsmPreprocessor)
516 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000517 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000518 default:
519 IdentifierInfo *II = Result.getIdentifierInfo();
520 if (II == 0) break; // Not an identifier.
521
522 // Ask what the preprocessor keyword ID is.
523 switch (II->getPPKeywordID()) {
524 default: break;
525 // C99 6.10.1 - Conditional Inclusion.
526 case tok::pp_if:
527 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
528 case tok::pp_ifdef:
529 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
530 case tok::pp_ifndef:
531 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
532 case tok::pp_elif:
533 return HandleElifDirective(Result);
534 case tok::pp_else:
535 return HandleElseDirective(Result);
536 case tok::pp_endif:
537 return HandleEndifDirective(Result);
538
539 // C99 6.10.2 - Source File Inclusion.
540 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000541 return HandleIncludeDirective(Result); // Handle #include.
542 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000543 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000544
Chris Lattner141e71f2008-03-09 01:54:53 +0000545 // C99 6.10.3 - Macro Replacement.
546 case tok::pp_define:
547 return HandleDefineDirective(Result);
548 case tok::pp_undef:
549 return HandleUndefDirective(Result);
550
551 // C99 6.10.4 - Line Control.
552 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000553 return HandleLineDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000554
555 // C99 6.10.5 - Error Directive.
556 case tok::pp_error:
557 return HandleUserDiagnosticDirective(Result, false);
558
559 // C99 6.10.6 - Pragma Directive.
560 case tok::pp_pragma:
561 return HandlePragmaDirective();
562
563 // GNU Extensions.
564 case tok::pp_import:
565 return HandleImportDirective(Result);
566 case tok::pp_include_next:
567 return HandleIncludeNextDirective(Result);
568
569 case tok::pp_warning:
570 Diag(Result, diag::ext_pp_warning_directive);
571 return HandleUserDiagnosticDirective(Result, true);
572 case tok::pp_ident:
573 return HandleIdentSCCSDirective(Result);
574 case tok::pp_sccs:
575 return HandleIdentSCCSDirective(Result);
576 case tok::pp_assert:
577 //isExtension = true; // FIXME: implement #assert
578 break;
579 case tok::pp_unassert:
580 //isExtension = true; // FIXME: implement #unassert
581 break;
582 }
583 break;
584 }
585
Chris Lattner42aa16c2009-03-18 21:00:25 +0000586 // If this is a .S file, treat unknown # directives as non-preprocessor
587 // directives. This is important because # may be a comment or introduce
588 // various pseudo-ops. Just return the # token and push back the following
589 // token to be lexed next time.
590 if (getLangOptions().AsmPreprocessor) {
591 Token *Toks = new Token[2]();
592 // Return the # and the token after it.
593 Toks[0] = SavedHash;
594 Toks[1] = Result;
595 // Enter this token stream so that we re-lex the tokens. Make sure to
596 // enable macro expansion, in case the token after the # is an identifier
597 // that is expanded.
598 EnterTokenStream(Toks, 2, false, true);
599 return;
600 }
601
Chris Lattner141e71f2008-03-09 01:54:53 +0000602 // If we reached here, the preprocessing token is not valid!
603 Diag(Result, diag::err_pp_invalid_directive);
604
605 // Read the rest of the PP line.
606 DiscardUntilEndOfDirective();
607
608 // Okay, we're done parsing the directive.
609}
610
Chris Lattner478a18e2009-01-26 06:19:46 +0000611/// GetLineValue - Convert a numeric token into an unsigned value, emitting
612/// Diagnostic DiagID if it is invalid, and returning the value in Val.
613static bool GetLineValue(Token &DigitTok, unsigned &Val,
614 unsigned DiagID, Preprocessor &PP) {
615 if (DigitTok.isNot(tok::numeric_constant)) {
616 PP.Diag(DigitTok, DiagID);
617
618 if (DigitTok.isNot(tok::eom))
619 PP.DiscardUntilEndOfDirective();
620 return true;
621 }
622
623 llvm::SmallString<64> IntegerBuffer;
624 IntegerBuffer.resize(DigitTok.getLength());
625 const char *DigitTokBegin = &IntegerBuffer[0];
626 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
627 NumericLiteralParser Literal(DigitTokBegin, DigitTokBegin+ActualLength,
628 DigitTok.getLocation(), PP);
629 if (Literal.hadError)
630 return true; // Error already emitted.
631
632 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
633 PP.Diag(DigitTok, DiagID);
634 return true;
635 }
636
637 // Parse the integer literal into Result.
638 llvm::APInt APVal(32, 0);
639 if (Literal.GetIntegerValue(APVal)) {
640 // Overflow parsing integer literal.
641 PP.Diag(DigitTok, DiagID);
642 return true;
643 }
644 Val = APVal.getZExtValue();
645
646 // Reject 0, this is needed both by #line numbers and flags.
647 if (Val == 0) {
648 PP.Diag(DigitTok, DiagID);
649 PP.DiscardUntilEndOfDirective();
650 return true;
651 }
652
Chris Lattner58e91d52009-04-17 23:37:49 +0000653 // Warn about hex and octal line numbers. Do this after the check for 0,
654 // because it is octal.
655 if (Literal.getRadix() != 10)
656 PP.Diag(DigitTok, diag::warn_pp_line_decimal);
657
Chris Lattner478a18e2009-01-26 06:19:46 +0000658 return false;
659}
660
Chris Lattner359cc442009-01-26 05:29:08 +0000661/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
662/// acceptable forms are:
663/// # line digit-sequence
664/// # line digit-sequence "s-char-sequence"
665void Preprocessor::HandleLineDirective(Token &Tok) {
666 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
667 // expanded.
668 Token DigitTok;
669 Lex(DigitTok);
670
Chris Lattner359cc442009-01-26 05:29:08 +0000671 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000672 unsigned LineNo;
673 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer, *this))
Chris Lattner359cc442009-01-26 05:29:08 +0000674 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000675
Chris Lattner478a18e2009-01-26 06:19:46 +0000676 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
677 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000678 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
679 if (LineNo >= LineLimit)
680 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
681
Chris Lattner5b9a5042009-01-26 07:57:50 +0000682 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000683 Token StrTok;
684 Lex(StrTok);
685
686 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
687 // string followed by eom.
688 if (StrTok.is(tok::eom))
689 ; // ok
690 else if (StrTok.isNot(tok::string_literal)) {
691 Diag(StrTok, diag::err_pp_line_invalid_filename);
692 DiscardUntilEndOfDirective();
693 return;
694 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000695 // Parse and validate the string, converting it into a unique ID.
696 StringLiteralParser Literal(&StrTok, 1, *this);
697 assert(!Literal.AnyWide && "Didn't allow wide strings in");
698 if (Literal.hadError)
699 return DiscardUntilEndOfDirective();
700 if (Literal.Pascal) {
701 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
702 return DiscardUntilEndOfDirective();
703 }
704 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
705 Literal.GetStringLength());
706
Chris Lattnerab82f412009-04-17 23:30:53 +0000707 // Verify that there is nothing after the string, other than EOM. Because
708 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
709 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000710 }
711
Chris Lattner4c4ea172009-02-03 21:52:55 +0000712 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Chris Lattner16629382009-03-27 17:13:49 +0000713
714 if (Callbacks)
715 Callbacks->FileChanged(DigitTok.getLocation(), PPCallbacks::RenameFile,
716 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000717}
718
Chris Lattner478a18e2009-01-26 06:19:46 +0000719/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
720/// marker directive.
721static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
722 bool &IsSystemHeader, bool &IsExternCHeader,
723 Preprocessor &PP) {
724 unsigned FlagVal;
725 Token FlagTok;
726 PP.Lex(FlagTok);
727 if (FlagTok.is(tok::eom)) return false;
728 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
729 return true;
730
731 if (FlagVal == 1) {
732 IsFileEntry = true;
733
734 PP.Lex(FlagTok);
735 if (FlagTok.is(tok::eom)) return false;
736 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
737 return true;
738 } else if (FlagVal == 2) {
739 IsFileExit = true;
740
Chris Lattner137b6a62009-02-04 06:25:26 +0000741 SourceManager &SM = PP.getSourceManager();
742 // If we are leaving the current presumed file, check to make sure the
743 // presumed include stack isn't empty!
744 FileID CurFileID =
745 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
746 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
747
748 // If there is no include loc (main file) or if the include loc is in a
749 // different physical file, then we aren't in a "1" line marker flag region.
750 SourceLocation IncLoc = PLoc.getIncludeLoc();
751 if (IncLoc.isInvalid() ||
752 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
753 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
754 PP.DiscardUntilEndOfDirective();
755 return true;
756 }
757
Chris Lattner478a18e2009-01-26 06:19:46 +0000758 PP.Lex(FlagTok);
759 if (FlagTok.is(tok::eom)) return false;
760 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
761 return true;
762 }
763
764 // We must have 3 if there are still flags.
765 if (FlagVal != 3) {
766 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000767 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000768 return true;
769 }
770
771 IsSystemHeader = true;
772
773 PP.Lex(FlagTok);
774 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000775 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000776 return true;
777
778 // We must have 4 if there is yet another flag.
779 if (FlagVal != 4) {
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 IsExternCHeader = true;
786
787 PP.Lex(FlagTok);
788 if (FlagTok.is(tok::eom)) return false;
789
790 // There are no more valid flags here.
791 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000792 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000793 return true;
794}
795
796/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
797/// one of the following forms:
798///
799/// # 42
800/// # 42 "file" ('1' | '2')?
801/// # 42 "file" ('1' | '2')? '3' '4'?
802///
803void Preprocessor::HandleDigitDirective(Token &DigitTok) {
804 // Validate the number and convert it to an unsigned. GNU does not have a
805 // line # limit other than it fit in 32-bits.
806 unsigned LineNo;
807 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
808 *this))
809 return;
810
811 Token StrTok;
812 Lex(StrTok);
813
814 bool IsFileEntry = false, IsFileExit = false;
815 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000816 int FilenameID = -1;
817
Chris Lattner478a18e2009-01-26 06:19:46 +0000818 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
819 // string followed by eom.
820 if (StrTok.is(tok::eom))
821 ; // ok
822 else if (StrTok.isNot(tok::string_literal)) {
823 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000824 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000825 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000826 // Parse and validate the string, converting it into a unique ID.
827 StringLiteralParser Literal(&StrTok, 1, *this);
828 assert(!Literal.AnyWide && "Didn't allow wide strings in");
829 if (Literal.hadError)
830 return DiscardUntilEndOfDirective();
831 if (Literal.Pascal) {
832 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
833 return DiscardUntilEndOfDirective();
834 }
835 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
836 Literal.GetStringLength());
837
Chris Lattner478a18e2009-01-26 06:19:46 +0000838 // If a filename was present, read any flags that are present.
839 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000840 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000841 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000842 }
Chris Lattner137b6a62009-02-04 06:25:26 +0000843
Chris Lattner9d79eba2009-02-04 05:21:58 +0000844 // Create a line note with this information.
845 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
846 IsFileEntry, IsFileExit,
847 IsSystemHeader, IsExternCHeader);
Chris Lattner16629382009-03-27 17:13:49 +0000848
849 // If the preprocessor has callbacks installed, notify them of the #line
850 // change. This is used so that the line marker comes out in -E mode for
851 // example.
852 if (Callbacks) {
853 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
854 if (IsFileEntry)
855 Reason = PPCallbacks::EnterFile;
856 else if (IsFileExit)
857 Reason = PPCallbacks::ExitFile;
858 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
859 if (IsExternCHeader)
860 FileKind = SrcMgr::C_ExternCSystem;
861 else if (IsSystemHeader)
862 FileKind = SrcMgr::C_System;
863
864 Callbacks->FileChanged(DigitTok.getLocation(), Reason, FileKind);
865 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000866}
867
868
Chris Lattner099dd052009-01-26 05:30:54 +0000869/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
870///
Chris Lattner141e71f2008-03-09 01:54:53 +0000871void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
872 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000873 // PTH doesn't emit #warning or #error directives.
874 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000875 return CurPTHLexer->DiscardToEndOfLine();
876
Chris Lattner141e71f2008-03-09 01:54:53 +0000877 // Read the rest of the line raw. We do this because we don't want macros
878 // to be expanded and we don't require that the tokens be valid preprocessing
879 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
880 // collapse multiple consequtive white space between tokens, but this isn't
881 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000882 std::string Message = CurLexer->ReadToEndOfLine();
883 if (isWarning)
884 Diag(Tok, diag::pp_hash_warning) << Message;
885 else
886 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000887}
888
889/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
890///
891void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
892 // Yes, this directive is an extension.
893 Diag(Tok, diag::ext_pp_ident_directive);
894
895 // Read the string argument.
896 Token StrTok;
897 Lex(StrTok);
898
899 // If the token kind isn't a string, it's a malformed directive.
900 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000901 StrTok.isNot(tok::wide_string_literal)) {
902 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000903 if (StrTok.isNot(tok::eom))
904 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000905 return;
906 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000907
908 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000909 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000910
911 if (Callbacks)
912 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
913}
914
915//===----------------------------------------------------------------------===//
916// Preprocessor Include Directive Handling.
917//===----------------------------------------------------------------------===//
918
919/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
920/// checked and spelled filename, e.g. as an operand of #include. This returns
921/// true if the input filename was in <>'s or false if it were in ""'s. The
922/// caller is expected to provide a buffer that is large enough to hold the
923/// spelling of the filename, but is also expected to handle the case when
924/// this method decides to use a different buffer.
925bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
926 const char *&BufStart,
927 const char *&BufEnd) {
928 // Get the text form of the filename.
929 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
930
931 // Make sure the filename is <x> or "x".
932 bool isAngled;
933 if (BufStart[0] == '<') {
934 if (BufEnd[-1] != '>') {
935 Diag(Loc, diag::err_pp_expects_filename);
936 BufStart = 0;
937 return true;
938 }
939 isAngled = true;
940 } else if (BufStart[0] == '"') {
941 if (BufEnd[-1] != '"') {
942 Diag(Loc, diag::err_pp_expects_filename);
943 BufStart = 0;
944 return true;
945 }
946 isAngled = false;
947 } else {
948 Diag(Loc, diag::err_pp_expects_filename);
949 BufStart = 0;
950 return true;
951 }
952
953 // Diagnose #include "" as invalid.
954 if (BufEnd-BufStart <= 2) {
955 Diag(Loc, diag::err_pp_empty_filename);
956 BufStart = 0;
957 return "";
958 }
959
960 // Skip the brackets.
961 ++BufStart;
962 --BufEnd;
963 return isAngled;
964}
965
966/// ConcatenateIncludeName - Handle cases where the #include name is expanded
967/// from a macro as multiple tokens, which need to be glued together. This
968/// occurs for code like:
969/// #define FOO <a/b.h>
970/// #include FOO
971/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
972///
973/// This code concatenates and consumes tokens up to the '>' token. It returns
974/// false if the > was found, otherwise it returns true if it finds and consumes
975/// the EOM marker.
976static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
977 Preprocessor &PP) {
978 Token CurTok;
979
980 PP.Lex(CurTok);
981 while (CurTok.isNot(tok::eom)) {
982 // Append the spelling of this token to the buffer. If there was a space
983 // before it, add it now.
984 if (CurTok.hasLeadingSpace())
985 FilenameBuffer.push_back(' ');
986
987 // Get the spelling of the token, directly into FilenameBuffer if possible.
988 unsigned PreAppendSize = FilenameBuffer.size();
989 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
990
991 const char *BufPtr = &FilenameBuffer[PreAppendSize];
992 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
993
994 // If the token was spelled somewhere else, copy it into FilenameBuffer.
995 if (BufPtr != &FilenameBuffer[PreAppendSize])
996 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
997
998 // Resize FilenameBuffer to the correct size.
999 if (CurTok.getLength() != ActualLen)
1000 FilenameBuffer.resize(PreAppendSize+ActualLen);
1001
1002 // If we found the '>' marker, return success.
1003 if (CurTok.is(tok::greater))
1004 return false;
1005
1006 PP.Lex(CurTok);
1007 }
1008
1009 // If we hit the eom marker, emit an error and return true so that the caller
1010 // knows the EOM has been read.
1011 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1012 return true;
1013}
1014
1015/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1016/// file to be included from the lexer, then include it! This is a common
1017/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001018/// #import. LookupFrom is set when this is a #include_next directive, it
1019/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001020void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1021 const DirectoryLookup *LookupFrom,
1022 bool isImport) {
1023
1024 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001025 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001026
1027 // Reserve a buffer to get the spelling.
1028 llvm::SmallVector<char, 128> FilenameBuffer;
1029 const char *FilenameStart, *FilenameEnd;
1030
1031 switch (FilenameTok.getKind()) {
1032 case tok::eom:
1033 // If the token kind is EOM, the error has already been diagnosed.
1034 return;
1035
1036 case tok::angle_string_literal:
1037 case tok::string_literal: {
1038 FilenameBuffer.resize(FilenameTok.getLength());
1039 FilenameStart = &FilenameBuffer[0];
1040 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1041 FilenameEnd = FilenameStart+Len;
1042 break;
1043 }
1044
1045 case tok::less:
1046 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1047 // case, glue the tokens together into FilenameBuffer and interpret those.
1048 FilenameBuffer.push_back('<');
1049 if (ConcatenateIncludeName(FilenameBuffer, *this))
1050 return; // Found <eom> but no ">"? Diagnostic already emitted.
1051 FilenameStart = &FilenameBuffer[0];
1052 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1053 break;
1054 default:
1055 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1056 DiscardUntilEndOfDirective();
1057 return;
1058 }
1059
1060 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
1061 FilenameStart, FilenameEnd);
1062 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1063 // error.
1064 if (FilenameStart == 0) {
1065 DiscardUntilEndOfDirective();
1066 return;
1067 }
1068
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001069 // Verify that there is nothing after the filename, other than EOM. Note that
1070 // we allow macros that expand to nothing after the filename, because this
1071 // falls into the category of "#include pp-tokens new-line" specified in
1072 // C99 6.10.2p4.
1073 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getName(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001074
1075 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001076 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1077 Diag(FilenameTok, diag::err_pp_include_too_deep);
1078 return;
1079 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001080
1081 // Search include directories.
1082 const DirectoryLookup *CurDir;
1083 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1084 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001085 if (File == 0) {
1086 Diag(FilenameTok, diag::err_pp_file_not_found)
1087 << std::string(FilenameStart, FilenameEnd);
1088 return;
1089 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001090
Chris Lattner72181832008-09-26 20:12:23 +00001091 // Ask HeaderInfo if we should enter this #include file. If not, #including
1092 // this file will have no effect.
1093 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001094 return;
Chris Lattner72181832008-09-26 20:12:23 +00001095
1096 // The #included file will be considered to be a system header if either it is
1097 // in a system include directory, or if the #includer is a system include
1098 // header.
Chris Lattner9d728512008-10-27 01:19:25 +00001099 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001100 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001101 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Chris Lattner72181832008-09-26 20:12:23 +00001102
Chris Lattner141e71f2008-03-09 01:54:53 +00001103 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001104 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1105 FileCharacter);
1106 if (FID.isInvalid()) {
Chris Lattner56b05c82008-11-18 08:02:48 +00001107 Diag(FilenameTok, diag::err_pp_file_not_found)
1108 << std::string(FilenameStart, FilenameEnd);
1109 return;
1110 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001111
1112 // Finally, if all is good, enter the new file!
Chris Lattner2b2453a2009-01-17 06:22:33 +00001113 EnterSourceFile(FID, CurDir);
Chris Lattner141e71f2008-03-09 01:54:53 +00001114}
1115
1116/// HandleIncludeNextDirective - Implements #include_next.
1117///
1118void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1119 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1120
1121 // #include_next is like #include, except that we start searching after
1122 // the current found directory. If we can't do this, issue a
1123 // diagnostic.
1124 const DirectoryLookup *Lookup = CurDirLookup;
1125 if (isInPrimaryFile()) {
1126 Lookup = 0;
1127 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1128 } else if (Lookup == 0) {
1129 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1130 } else {
1131 // Start looking up in the next directory.
1132 ++Lookup;
1133 }
1134
1135 return HandleIncludeDirective(IncludeNextTok, Lookup);
1136}
1137
1138/// HandleImportDirective - Implements #import.
1139///
1140void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001141 if (!Features.ObjC1) // #import is standard for ObjC.
1142 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner141e71f2008-03-09 01:54:53 +00001143
1144 return HandleIncludeDirective(ImportTok, 0, true);
1145}
1146
Chris Lattnerde076652009-04-08 18:46:40 +00001147/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1148/// pseudo directive in the predefines buffer. This handles it by sucking all
1149/// tokens through the preprocessor and discarding them (only keeping the side
1150/// effects on the preprocessor).
1151void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1152 // This directive should only occur in the predefines buffer. If not, emit an
1153 // error and reject it.
1154 SourceLocation Loc = IncludeMacrosTok.getLocation();
1155 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1156 Diag(IncludeMacrosTok.getLocation(),
1157 diag::pp_include_macros_out_of_predefines);
1158 DiscardUntilEndOfDirective();
1159 return;
1160 }
1161
Chris Lattnerfd105112009-04-08 20:53:24 +00001162 // Treat this as a normal #include for checking purposes. If this is
1163 // successful, it will push a new lexer onto the include stack.
1164 HandleIncludeDirective(IncludeMacrosTok, 0, false);
1165
1166 Token TmpTok;
1167 do {
1168 Lex(TmpTok);
1169 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1170 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001171}
1172
Chris Lattner141e71f2008-03-09 01:54:53 +00001173//===----------------------------------------------------------------------===//
1174// Preprocessor Macro Directive Handling.
1175//===----------------------------------------------------------------------===//
1176
1177/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1178/// definition has just been read. Lex the rest of the arguments and the
1179/// closing ), updating MI with what we learn. Return true if an error occurs
1180/// parsing the arg list.
1181bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1182 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1183
1184 Token Tok;
1185 while (1) {
1186 LexUnexpandedToken(Tok);
1187 switch (Tok.getKind()) {
1188 case tok::r_paren:
1189 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001190 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001191 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001192 // Otherwise we have #define FOO(A,)
1193 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1194 return true;
1195 case tok::ellipsis: // #define X(... -> C99 varargs
1196 // Warn if use of C99 feature in non-C99 mode.
1197 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1198
1199 // Lex the token after the identifier.
1200 LexUnexpandedToken(Tok);
1201 if (Tok.isNot(tok::r_paren)) {
1202 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1203 return true;
1204 }
1205 // Add the __VA_ARGS__ identifier as an argument.
1206 Arguments.push_back(Ident__VA_ARGS__);
1207 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001208 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001209 return false;
1210 case tok::eom: // #define X(
1211 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1212 return true;
1213 default:
1214 // Handle keywords and identifiers here to accept things like
1215 // #define Foo(for) for.
1216 IdentifierInfo *II = Tok.getIdentifierInfo();
1217 if (II == 0) {
1218 // #define X(1
1219 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1220 return true;
1221 }
1222
1223 // If this is already used as an argument, it is used multiple times (e.g.
1224 // #define X(A,A.
1225 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1226 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001227 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001228 return true;
1229 }
1230
1231 // Add the argument to the macro info.
1232 Arguments.push_back(II);
1233
1234 // Lex the token after the identifier.
1235 LexUnexpandedToken(Tok);
1236
1237 switch (Tok.getKind()) {
1238 default: // #define X(A B
1239 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1240 return true;
1241 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001242 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001243 return false;
1244 case tok::comma: // #define X(A,
1245 break;
1246 case tok::ellipsis: // #define X(A... -> GCC extension
1247 // Diagnose extension.
1248 Diag(Tok, diag::ext_named_variadic_macro);
1249
1250 // Lex the token after the identifier.
1251 LexUnexpandedToken(Tok);
1252 if (Tok.isNot(tok::r_paren)) {
1253 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1254 return true;
1255 }
1256
1257 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001258 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001259 return false;
1260 }
1261 }
1262 }
1263}
1264
1265/// HandleDefineDirective - Implements #define. This consumes the entire macro
1266/// line then lets the caller lex the next real token.
1267void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1268 ++NumDefined;
1269
1270 Token MacroNameTok;
1271 ReadMacroName(MacroNameTok, 1);
1272
1273 // Error reading macro name? If so, diagnostic already issued.
1274 if (MacroNameTok.is(tok::eom))
1275 return;
1276
1277 // If we are supposed to keep comments in #defines, reenable comment saving
1278 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001279 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Chris Lattner141e71f2008-03-09 01:54:53 +00001280
1281 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001282 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001283
1284 Token Tok;
1285 LexUnexpandedToken(Tok);
1286
1287 // If this is a function-like macro definition, parse the argument list,
1288 // marking each of the identifiers as being used as macro arguments. Also,
1289 // check other constraints on the first token of the macro body.
1290 if (Tok.is(tok::eom)) {
1291 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001292 } else if (Tok.hasLeadingSpace()) {
1293 // This is a normal token with leading space. Clear the leading space
1294 // marker on the first token to get proper expansion.
1295 Tok.clearFlag(Token::LeadingSpace);
1296 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001297 // This is a function-like macro definition. Read the argument list.
1298 MI->setIsFunctionLike();
1299 if (ReadMacroDefinitionArgList(MI)) {
1300 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001301 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001302 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001303 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001304 DiscardUntilEndOfDirective();
1305 return;
1306 }
1307
1308 // Read the first token after the arg list for down below.
1309 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001310 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001311 // C99 requires whitespace between the macro definition and the body. Emit
1312 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001313 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001314 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001315 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1316 // first character of a replacement list is not a character required by
1317 // subclause 5.2.1, then there shall be white-space separation between the
1318 // identifier and the replacement list.". 5.2.1 lists this set:
1319 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1320 // is irrelevant here.
1321 bool isInvalid = false;
1322 if (Tok.is(tok::at)) // @ is not in the list above.
1323 isInvalid = true;
1324 else if (Tok.is(tok::unknown)) {
1325 // If we have an unknown token, it is something strange like "`". Since
1326 // all of valid characters would have lexed into a single character
1327 // token of some sort, we know this is not a valid case.
1328 isInvalid = true;
1329 }
1330 if (isInvalid)
1331 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1332 else
1333 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001334 }
1335
1336 // If this is a definition of a variadic C99 function-like macro, not using
1337 // the GNU named varargs extension, enabled __VA_ARGS__.
1338
1339 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1340 // This gets unpoisoned where it is allowed.
1341 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1342 if (MI->isC99Varargs())
1343 Ident__VA_ARGS__->setIsPoisoned(false);
1344
1345 // Read the rest of the macro body.
1346 if (MI->isObjectLike()) {
1347 // Object-like macros are very simple, just read their body.
1348 while (Tok.isNot(tok::eom)) {
1349 MI->AddTokenToBody(Tok);
1350 // Get the next token of the macro.
1351 LexUnexpandedToken(Tok);
1352 }
1353
1354 } else {
1355 // Otherwise, read the body of a function-like macro. This has to validate
1356 // the # (stringize) operator.
1357 while (Tok.isNot(tok::eom)) {
1358 MI->AddTokenToBody(Tok);
1359
1360 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1361 // parameters in function-like macro expansions.
1362 if (Tok.isNot(tok::hash)) {
1363 // Get the next token of the macro.
1364 LexUnexpandedToken(Tok);
1365 continue;
1366 }
1367
1368 // Get the next token of the macro.
1369 LexUnexpandedToken(Tok);
1370
1371 // Not a macro arg identifier?
1372 if (!Tok.getIdentifierInfo() ||
1373 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1374 Diag(Tok, diag::err_pp_stringize_not_parameter);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001375 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001376
1377 // Disable __VA_ARGS__ again.
1378 Ident__VA_ARGS__->setIsPoisoned(true);
1379 return;
1380 }
1381
1382 // Things look ok, add the param name token to the macro.
1383 MI->AddTokenToBody(Tok);
1384
1385 // Get the next token of the macro.
1386 LexUnexpandedToken(Tok);
1387 }
1388 }
1389
1390
1391 // Disable __VA_ARGS__ again.
1392 Ident__VA_ARGS__->setIsPoisoned(true);
1393
1394 // Check that there is no paste (##) operator at the begining or end of the
1395 // replacement list.
1396 unsigned NumTokens = MI->getNumTokens();
1397 if (NumTokens != 0) {
1398 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1399 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001400 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001401 return;
1402 }
1403 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1404 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001405 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001406 return;
1407 }
1408 }
1409
1410 // If this is the primary source file, remember that this macro hasn't been
1411 // used yet.
1412 if (isInPrimaryFile())
1413 MI->setIsUsed(false);
1414
1415 // Finally, if this identifier already had a macro defined for it, verify that
1416 // the macro bodies are identical and free the old definition.
1417 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001418 // It is very common for system headers to have tons of macro redefinitions
1419 // and for warnings to be disabled in system headers. If this is the case,
1420 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001421 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001422 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1423 if (!OtherMI->isUsed())
1424 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001425
Chris Lattner41c3ae12009-01-16 19:50:11 +00001426 // Macros must be identical. This means all tokes and whitespace
1427 // separation must be the same. C99 6.10.3.2.
1428 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1429 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1430 << MacroNameTok.getIdentifierInfo();
1431 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1432 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001433 }
Chris Lattner41c3ae12009-01-16 19:50:11 +00001434
Ted Kremenek0ea76722008-12-15 19:56:42 +00001435 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001436 }
1437
1438 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001439
1440 // If the callbacks want to know, tell them about the macro definition.
1441 if (Callbacks)
1442 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001443}
1444
1445/// HandleUndefDirective - Implements #undef.
1446///
1447void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1448 ++NumUndefined;
1449
1450 Token MacroNameTok;
1451 ReadMacroName(MacroNameTok, 2);
1452
1453 // Error reading macro name? If so, diagnostic already issued.
1454 if (MacroNameTok.is(tok::eom))
1455 return;
1456
1457 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001458 CheckEndOfDirective("undef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001459
1460 // Okay, we finally have a valid identifier to undef.
1461 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1462
1463 // If the macro is not defined, this is a noop undef, just return.
1464 if (MI == 0) return;
1465
1466 if (!MI->isUsed())
1467 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1468
1469 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001470 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001471 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1472}
1473
1474
1475//===----------------------------------------------------------------------===//
1476// Preprocessor Conditional Directive Handling.
1477//===----------------------------------------------------------------------===//
1478
1479/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1480/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1481/// if any tokens have been returned or pp-directives activated before this
1482/// #ifndef has been lexed.
1483///
1484void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1485 bool ReadAnyTokensBeforeDirective) {
1486 ++NumIf;
1487 Token DirectiveTok = Result;
1488
1489 Token MacroNameTok;
1490 ReadMacroName(MacroNameTok);
1491
1492 // Error reading macro name? If so, diagnostic already issued.
1493 if (MacroNameTok.is(tok::eom)) {
1494 // Skip code until we get to #endif. This helps with recovery by not
1495 // emitting an error when the #endif is reached.
1496 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1497 /*Foundnonskip*/false, /*FoundElse*/false);
1498 return;
1499 }
1500
1501 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001502 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001503
Ted Kremenek60e45d42008-11-18 00:34:22 +00001504 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001505 // If the start of a top-level #ifdef, inform MIOpt.
1506 if (!ReadAnyTokensBeforeDirective) {
1507 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001508 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001509 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001510 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001511 }
1512
1513 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1514 MacroInfo *MI = getMacroInfo(MII);
1515
1516 // If there is a macro, process it.
1517 if (MI) // Mark it used.
1518 MI->setIsUsed(true);
1519
1520 // Should we include the stuff contained by this directive?
1521 if (!MI == isIfndef) {
1522 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001523 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001524 /*foundnonskip*/true, /*foundelse*/false);
1525 } else {
1526 // No, skip the contents of this block and return the first token after it.
1527 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1528 /*Foundnonskip*/false,
1529 /*FoundElse*/false);
1530 }
1531}
1532
1533/// HandleIfDirective - Implements the #if directive.
1534///
1535void Preprocessor::HandleIfDirective(Token &IfToken,
1536 bool ReadAnyTokensBeforeDirective) {
1537 ++NumIf;
1538
1539 // Parse and evaluation the conditional expression.
1540 IdentifierInfo *IfNDefMacro = 0;
1541 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1542
Nuno Lopes0049db62008-06-01 18:31:24 +00001543
1544 // If this condition is equivalent to #ifndef X, and if this is the first
1545 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001546 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001547 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001548 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001549 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001550 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001551 }
1552
Chris Lattner141e71f2008-03-09 01:54:53 +00001553 // Should we include the stuff contained by this directive?
1554 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001555 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001556 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001557 /*foundnonskip*/true, /*foundelse*/false);
1558 } else {
1559 // No, skip the contents of this block and return the first token after it.
1560 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1561 /*FoundElse*/false);
1562 }
1563}
1564
1565/// HandleEndifDirective - Implements the #endif directive.
1566///
1567void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1568 ++NumEndif;
1569
1570 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001571 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +00001572
1573 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001574 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001575 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001576 Diag(EndifToken, diag::err_pp_endif_without_if);
1577 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001578 }
1579
1580 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001581 if (CurPPLexer->getConditionalStackDepth() == 0)
1582 CurPPLexer->MIOpt.ExitTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001583
Ted Kremenek60e45d42008-11-18 00:34:22 +00001584 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001585 "This code should only be reachable in the non-skipping case!");
1586}
1587
1588
1589void Preprocessor::HandleElseDirective(Token &Result) {
1590 ++NumElse;
1591
1592 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001593 CheckEndOfDirective("else");
Chris Lattner141e71f2008-03-09 01:54:53 +00001594
1595 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001596 if (CurPPLexer->popConditionalLevel(CI)) {
1597 Diag(Result, diag::pp_err_else_without_if);
1598 return;
1599 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001600
1601 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001602 if (CurPPLexer->getConditionalStackDepth() == 0)
1603 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001604
1605 // If this is a #else with a #else before it, report the error.
1606 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1607
1608 // Finally, skip the rest of the contents of this block and return the first
1609 // token after it.
1610 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1611 /*FoundElse*/true);
1612}
1613
1614void Preprocessor::HandleElifDirective(Token &ElifToken) {
1615 ++NumElse;
1616
1617 // #elif directive in a non-skipping conditional... start skipping.
1618 // We don't care what the condition is, because we will always skip it (since
1619 // the block immediately before it was included).
1620 DiscardUntilEndOfDirective();
1621
1622 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001623 if (CurPPLexer->popConditionalLevel(CI)) {
1624 Diag(ElifToken, diag::pp_err_elif_without_if);
1625 return;
1626 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001627
1628 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001629 if (CurPPLexer->getConditionalStackDepth() == 0)
1630 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001631
1632 // If this is a #elif with a #else before it, report the error.
1633 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1634
1635 // Finally, skip the rest of the contents of this block and return the first
1636 // token after it.
1637 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1638 /*FoundElse*/CI.FoundElse);
1639}
1640