blob: f5c60eb49438658a1bcd4df0efcb5594a07b4528 [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 Lattner6e290142009-11-30 04:18:44 +000019#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000021#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000022using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// Utility Methods for Preprocessor Directive Handling.
26//===----------------------------------------------------------------------===//
27
Chris Lattner0301b3f2009-02-20 22:19:20 +000028MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
Ted Kremenek0ea76722008-12-15 19:56:42 +000029 MacroInfo *MI;
Mike Stump1eb44332009-09-09 15:08:12 +000030
Ted Kremenek0ea76722008-12-15 19:56:42 +000031 if (!MICache.empty()) {
32 MI = MICache.back();
33 MICache.pop_back();
Chris Lattner0301b3f2009-02-20 22:19:20 +000034 } else
35 MI = (MacroInfo*) BP.Allocate<MacroInfo>();
Ted Kremenek0ea76722008-12-15 19:56:42 +000036 new (MI) MacroInfo(L);
37 return MI;
38}
39
Chris Lattner0301b3f2009-02-20 22:19:20 +000040/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
41/// be reused for allocating new MacroInfo objects.
42void Preprocessor::ReleaseMacroInfo(MacroInfo* MI) {
43 MICache.push_back(MI);
Chris Lattner685befe2009-02-20 22:46:43 +000044 MI->FreeArgumentList(BP);
Chris Lattner0301b3f2009-02-20 22:19:20 +000045}
46
47
Chris Lattner141e71f2008-03-09 01:54:53 +000048/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
49/// current line until the tok::eom token is found.
50void Preprocessor::DiscardUntilEndOfDirective() {
51 Token Tmp;
52 do {
53 LexUnexpandedToken(Tmp);
54 } while (Tmp.isNot(tok::eom));
55}
56
Chris Lattner141e71f2008-03-09 01:54:53 +000057/// ReadMacroName - Lex and validate a macro name, which occurs after a
58/// #define or #undef. This sets the token kind to eom and discards the rest
59/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
60/// this is due to a a #define, 2 if #undef directive, 0 if it is something
61/// else (e.g. #ifdef).
62void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
63 // Read the token, don't allow macro expansion on it.
64 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner141e71f2008-03-09 01:54:53 +000066 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000067 if (MacroNameTok.is(tok::eom)) {
68 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
69 return;
70 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner141e71f2008-03-09 01:54:53 +000072 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
73 if (II == 0) {
74 std::string Spelling = getSpelling(MacroNameTok);
Chris Lattner9485d232008-12-13 20:12:40 +000075 const IdentifierInfo &Info = Identifiers.get(Spelling);
76 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +000077 // C++ 2.5p2: Alternative tokens behave the same as its primary token
78 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +000079 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000080 else
81 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
82 // Fall through on error.
83 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
84 // Error if defining "defined": C99 6.10.8.4.
85 Diag(MacroNameTok, diag::err_defined_macro_name);
86 } else if (isDefineUndef && II->hasMacroDefinition() &&
87 getMacroInfo(II)->isBuiltinMacro()) {
88 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
89 if (isDefineUndef == 1)
90 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
91 else
92 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
93 } else {
94 // Okay, we got a good identifier node. Return it.
95 return;
96 }
Mike Stump1eb44332009-09-09 15:08:12 +000097
Chris Lattner141e71f2008-03-09 01:54:53 +000098 // Invalid macro name, read and discard the rest of the line. Then set the
99 // token kind to tok::eom.
100 MacroNameTok.setKind(tok::eom);
101 return DiscardUntilEndOfDirective();
102}
103
104/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattnerab82f412009-04-17 23:30:53 +0000105/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
106/// true, then we consider macros that expand to zero tokens as being ok.
107void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000108 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000109 // Lex unexpanded tokens for most directives: macros might expand to zero
110 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
111 // #line) allow empty macros.
112 if (EnableMacros)
113 Lex(Tmp);
114 else
115 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Chris Lattner141e71f2008-03-09 01:54:53 +0000117 // There should be no tokens after the directive, but we allow them as an
118 // extension.
119 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
120 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattner141e71f2008-03-09 01:54:53 +0000122 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000123 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
124 // because it is more trouble than it is worth to insert /**/ and check that
125 // there is no /**/ in the range also.
126 CodeModificationHint FixItHint;
127 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
128 FixItHint = CodeModificationHint::CreateInsertion(Tmp.getLocation(),"//");
129 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << FixItHint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000130 DiscardUntilEndOfDirective();
131 }
132}
133
134
135
136/// SkipExcludedConditionalBlock - We just read a #if or related directive and
137/// decided that the subsequent tokens are in the #if'd out portion of the
138/// file. Lex the rest of the file, until we see an #endif. If
139/// FoundNonSkipPortion is true, then we have already emitted code for part of
140/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
141/// is true, then #else directives are ok, if not, then we have already seen one
142/// so a #else directive is a duplicate. When this returns, the caller can lex
143/// the first valid token.
144void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
145 bool FoundNonSkipPortion,
146 bool FoundElse) {
147 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000148 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000149
Ted Kremenek60e45d42008-11-18 00:34:22 +0000150 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000151 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Ted Kremenek268ee702008-12-12 18:34:08 +0000153 if (CurPTHLexer) {
154 PTHSkipExcludedConditionalBlock();
155 return;
156 }
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Chris Lattner141e71f2008-03-09 01:54:53 +0000158 // Enter raw mode to disable identifier lookup (and thus macro expansion),
159 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000160 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000161 Token Tok;
162 while (1) {
Ted Kremenekf6452c52008-11-18 01:04:47 +0000163 if (CurLexer)
164 CurLexer->Lex(Tok);
165 else
166 CurPTHLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattner141e71f2008-03-09 01:54:53 +0000168 // If this is the end of the buffer, we have an error.
169 if (Tok.is(tok::eof)) {
170 // Emit errors for each unterminated conditional on the stack, including
171 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000172 while (!CurPPLexer->ConditionalStack.empty()) {
173 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000174 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000175 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000176 }
177
Chris Lattner141e71f2008-03-09 01:54:53 +0000178 // Just return and let the caller lex after this #include.
179 break;
180 }
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattner141e71f2008-03-09 01:54:53 +0000182 // If this token is not a preprocessor directive, just skip it.
183 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
184 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattner141e71f2008-03-09 01:54:53 +0000186 // We just parsed a # character at the start of a line, so we're in
187 // directive mode. Tell the lexer this so any newlines we see will be
188 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000189 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000190 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000191
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner141e71f2008-03-09 01:54:53 +0000193 // Read the next token, the directive flavor.
194 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner141e71f2008-03-09 01:54:53 +0000196 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
197 // something bogus), skip it.
198 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000199 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000200 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000201 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000202 continue;
203 }
204
205 // If the first letter isn't i or e, it isn't intesting to us. We know that
206 // this is safe in the face of spelling differences, because there is no way
207 // to spell an i/e in a strange way that is another letter. Skipping this
208 // allows us to avoid looking up the identifier info for #define/#undef and
209 // other common directives.
210 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
211 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000212 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000213 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000214 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000215 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000216 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000217 continue;
218 }
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattner141e71f2008-03-09 01:54:53 +0000220 // Get the identifier name without trigraphs or embedded newlines. Note
221 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
222 // when skipping.
223 // TODO: could do this with zero copies in the no-clean case by using
224 // strncmp below.
225 char Directive[20];
226 unsigned IdLen;
227 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
228 IdLen = Tok.getLength();
229 memcpy(Directive, RawCharData, IdLen);
230 Directive[IdLen] = 0;
231 } else {
232 std::string DirectiveStr = getSpelling(Tok);
233 IdLen = DirectiveStr.size();
234 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000235 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000236 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000237 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000238 continue;
239 }
240 memcpy(Directive, &DirectiveStr[0], IdLen);
241 Directive[IdLen] = 0;
Chris Lattner202fd2c2009-01-27 05:34:03 +0000242 FirstChar = Directive[0];
Chris Lattner141e71f2008-03-09 01:54:53 +0000243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattner141e71f2008-03-09 01:54:53 +0000245 if (FirstChar == 'i' && Directive[1] == 'f') {
246 if ((IdLen == 2) || // "if"
247 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
248 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
249 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
250 // bother parsing the condition.
251 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000252 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000253 /*foundnonskip*/false,
254 /*fnddelse*/false);
255 }
256 } else if (FirstChar == 'e') {
257 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000258 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000259 PPConditionalInfo CondInfo;
260 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000261 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000262 InCond = InCond; // Silence warning in no-asserts mode.
263 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Chris Lattner141e71f2008-03-09 01:54:53 +0000265 // If we popped the outermost skipping block, we're done skipping!
266 if (!CondInfo.WasSkipping)
267 break;
268 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
269 // #else directive in a skipping conditional. If not in some other
270 // skipping conditional, and if #else hasn't already been seen, enter it
271 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000272 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000273 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattner141e71f2008-03-09 01:54:53 +0000275 // If this is a #else with a #else before it, report the error.
276 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattner141e71f2008-03-09 01:54:53 +0000278 // Note that we've seen a #else in this conditional.
279 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattner141e71f2008-03-09 01:54:53 +0000281 // If the conditional is at the top level, and the #if block wasn't
282 // entered, enter the #else block now.
283 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
284 CondInfo.FoundNonSkip = true;
285 break;
286 }
287 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000288 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000289
290 bool ShouldEnter;
291 // If this is in a skipping block or if we're already handled this #if
292 // block, don't bother parsing the condition.
293 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
294 DiscardUntilEndOfDirective();
295 ShouldEnter = false;
296 } else {
297 // Restore the value of LexingRawMode so that identifiers are
298 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000299 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
300 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000301 IdentifierInfo *IfNDefMacro = 0;
302 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000303 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000304 }
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattner141e71f2008-03-09 01:54:53 +0000306 // If this is a #elif with a #else before it, report the error.
307 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattner141e71f2008-03-09 01:54:53 +0000309 // If this condition is true, enter it!
310 if (ShouldEnter) {
311 CondInfo.FoundNonSkip = true;
312 break;
313 }
314 }
315 }
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Ted Kremenek60e45d42008-11-18 00:34:22 +0000317 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000318 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000319 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000320 }
321
322 // Finally, if we are out of the conditional (saw an #endif or ran off the end
323 // of the file, just stop skipping and return to lexing whatever came after
324 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000325 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000326}
327
Ted Kremenek268ee702008-12-12 18:34:08 +0000328void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000329
330 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000331 assert(CurPTHLexer);
332 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Ted Kremenek268ee702008-12-12 18:34:08 +0000334 // Skip to the next '#else', '#elif', or #endif.
335 if (CurPTHLexer->SkipBlock()) {
336 // We have reached an #endif. Both the '#' and 'endif' tokens
337 // have been consumed by the PTHLexer. Just pop off the condition level.
338 PPConditionalInfo CondInfo;
339 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
340 InCond = InCond; // Silence warning in no-asserts mode.
341 assert(!InCond && "Can't be skipping if not in a conditional!");
342 break;
343 }
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Ted Kremenek268ee702008-12-12 18:34:08 +0000345 // We have reached a '#else' or '#elif'. Lex the next token to get
346 // the directive flavor.
347 Token Tok;
348 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Ted Kremenek268ee702008-12-12 18:34:08 +0000350 // We can actually look up the IdentifierInfo here since we aren't in
351 // raw mode.
352 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
353
354 if (K == tok::pp_else) {
355 // #else: Enter the else condition. We aren't in a nested condition
356 // since we skip those. We're always in the one matching the last
357 // blocked we skipped.
358 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
359 // Note that we've seen a #else in this conditional.
360 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Ted Kremenek268ee702008-12-12 18:34:08 +0000362 // If the #if block wasn't entered then enter the #else block now.
363 if (!CondInfo.FoundNonSkip) {
364 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000366 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000367 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000368 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000369 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Ted Kremenek268ee702008-12-12 18:34:08 +0000371 break;
372 }
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Ted Kremenek268ee702008-12-12 18:34:08 +0000374 // Otherwise skip this block.
375 continue;
376 }
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Ted Kremenek268ee702008-12-12 18:34:08 +0000378 assert(K == tok::pp_elif);
379 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
380
381 // If this is a #elif with a #else before it, report the error.
382 if (CondInfo.FoundElse)
383 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Ted Kremenek268ee702008-12-12 18:34:08 +0000385 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000386 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000387 if (CondInfo.FoundNonSkip)
388 continue;
389
390 // Evaluate the condition of the #elif.
391 IdentifierInfo *IfNDefMacro = 0;
392 CurPTHLexer->ParsingPreprocessorDirective = true;
393 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
394 CurPTHLexer->ParsingPreprocessorDirective = false;
395
396 // If this condition is true, enter it!
397 if (ShouldEnter) {
398 CondInfo.FoundNonSkip = true;
399 break;
400 }
401
402 // Otherwise, skip this block and go to the next one.
403 continue;
404 }
405}
406
Chris Lattner10725092008-03-09 04:17:44 +0000407/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
408/// return null on failure. isAngled indicates whether the file reference is
409/// for system #include's or not (i.e. using <> instead of "").
410const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
411 const char *FilenameEnd,
412 bool isAngled,
413 const DirectoryLookup *FromDir,
414 const DirectoryLookup *&CurDir) {
415 // If the header lookup mechanism may be relative to the current file, pass in
416 // info about where the current file is.
417 const FileEntry *CurFileEnt = 0;
418 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000419 FileID FID = getCurrentFileLexer()->getFileID();
420 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000422 // If there is no file entry associated with this file, it must be the
423 // predefines buffer. Any other file is not lexed with a normal lexer, so
424 // it won't be scanned for preprocessor directives. If we have the
425 // predefines buffer, resolve #include references (which come from the
426 // -include command line argument) as if they came from the main file, this
427 // affects file lookup etc.
428 if (CurFileEnt == 0) {
429 FID = SourceMgr.getMainFileID();
430 CurFileEnt = SourceMgr.getFileEntryForID(FID);
431 }
Chris Lattner10725092008-03-09 04:17:44 +0000432 }
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattner10725092008-03-09 04:17:44 +0000434 // Do a standard file entry lookup.
435 CurDir = CurDirLookup;
436 const FileEntry *FE =
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000437 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
438 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner10725092008-03-09 04:17:44 +0000439 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chris Lattner10725092008-03-09 04:17:44 +0000441 // Otherwise, see if this is a subframework header. If so, this is relative
442 // to one of the headers on the #include stack. Walk the list of the current
443 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000444 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000445 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000446 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
447 CurFileEnt)))
448 return FE;
449 }
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattner10725092008-03-09 04:17:44 +0000451 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
452 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000453 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000454 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000455 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000456 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
457 FilenameEnd, CurFileEnt)))
458 return FE;
459 }
460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner10725092008-03-09 04:17:44 +0000462 // Otherwise, we really couldn't find the file.
463 return 0;
464}
465
Chris Lattner141e71f2008-03-09 01:54:53 +0000466
467//===----------------------------------------------------------------------===//
468// Preprocessor Directive Handling.
469//===----------------------------------------------------------------------===//
470
471/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000472/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000473/// lexer/preprocessor state, and advances the lexer(s) so that the next token
474/// read is the correct one.
475void Preprocessor::HandleDirective(Token &Result) {
476 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Chris Lattner141e71f2008-03-09 01:54:53 +0000478 // We just parsed a # character at the start of a line, so we're in directive
479 // mode. Tell the lexer this so any newlines we see will be converted into an
480 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000481 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Chris Lattner141e71f2008-03-09 01:54:53 +0000483 ++NumDirectives;
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000484
Chris Lattner141e71f2008-03-09 01:54:53 +0000485 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000486 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000487 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000488 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Chris Lattner42aa16c2009-03-18 21:00:25 +0000490 // Save the '#' token in case we need to return it later.
491 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Chris Lattner141e71f2008-03-09 01:54:53 +0000493 // Read the next token, the directive flavor. This isn't expanded due to
494 // C99 6.10.3p8.
495 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Chris Lattner141e71f2008-03-09 01:54:53 +0000497 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
498 // #define A(x) #x
499 // A(abc
500 // #warning blah
501 // def)
502 // If so, the user is relying on non-portable behavior, emit a diagnostic.
503 if (InMacroArgs)
504 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Chris Lattner141e71f2008-03-09 01:54:53 +0000506TryAgain:
507 switch (Result.getKind()) {
508 case tok::eom:
509 return; // null directive.
510 case tok::comment:
511 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
512 LexUnexpandedToken(Result);
513 goto TryAgain;
514
Chris Lattner478a18e2009-01-26 06:19:46 +0000515 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000516 if (getLangOptions().AsmPreprocessor)
517 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000518 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000519 default:
520 IdentifierInfo *II = Result.getIdentifierInfo();
521 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattner141e71f2008-03-09 01:54:53 +0000523 // Ask what the preprocessor keyword ID is.
524 switch (II->getPPKeywordID()) {
525 default: break;
526 // C99 6.10.1 - Conditional Inclusion.
527 case tok::pp_if:
528 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
529 case tok::pp_ifdef:
530 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
531 case tok::pp_ifndef:
532 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
533 case tok::pp_elif:
534 return HandleElifDirective(Result);
535 case tok::pp_else:
536 return HandleElseDirective(Result);
537 case tok::pp_endif:
538 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Chris Lattner141e71f2008-03-09 01:54:53 +0000540 // C99 6.10.2 - Source File Inclusion.
541 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000542 return HandleIncludeDirective(Result); // Handle #include.
543 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000544 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattner141e71f2008-03-09 01:54:53 +0000546 // C99 6.10.3 - Macro Replacement.
547 case tok::pp_define:
548 return HandleDefineDirective(Result);
549 case tok::pp_undef:
550 return HandleUndefDirective(Result);
551
552 // C99 6.10.4 - Line Control.
553 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000554 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Chris Lattner141e71f2008-03-09 01:54:53 +0000556 // C99 6.10.5 - Error Directive.
557 case tok::pp_error:
558 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner141e71f2008-03-09 01:54:53 +0000560 // C99 6.10.6 - Pragma Directive.
561 case tok::pp_pragma:
562 return HandlePragmaDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattner141e71f2008-03-09 01:54:53 +0000564 // GNU Extensions.
565 case tok::pp_import:
566 return HandleImportDirective(Result);
567 case tok::pp_include_next:
568 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattner141e71f2008-03-09 01:54:53 +0000570 case tok::pp_warning:
571 Diag(Result, diag::ext_pp_warning_directive);
572 return HandleUserDiagnosticDirective(Result, true);
573 case tok::pp_ident:
574 return HandleIdentSCCSDirective(Result);
575 case tok::pp_sccs:
576 return HandleIdentSCCSDirective(Result);
577 case tok::pp_assert:
578 //isExtension = true; // FIXME: implement #assert
579 break;
580 case tok::pp_unassert:
581 //isExtension = true; // FIXME: implement #unassert
582 break;
583 }
584 break;
585 }
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner42aa16c2009-03-18 21:00:25 +0000587 // If this is a .S file, treat unknown # directives as non-preprocessor
588 // directives. This is important because # may be a comment or introduce
589 // various pseudo-ops. Just return the # token and push back the following
590 // token to be lexed next time.
591 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000592 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000593 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000594 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000595 Toks[1] = Result;
596 // Enter this token stream so that we re-lex the tokens. Make sure to
597 // enable macro expansion, in case the token after the # is an identifier
598 // that is expanded.
599 EnterTokenStream(Toks, 2, false, true);
600 return;
601 }
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Chris Lattner141e71f2008-03-09 01:54:53 +0000603 // If we reached here, the preprocessing token is not valid!
604 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Chris Lattner141e71f2008-03-09 01:54:53 +0000606 // Read the rest of the PP line.
607 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattner141e71f2008-03-09 01:54:53 +0000609 // Okay, we're done parsing the directive.
610}
611
Chris Lattner478a18e2009-01-26 06:19:46 +0000612/// GetLineValue - Convert a numeric token into an unsigned value, emitting
613/// Diagnostic DiagID if it is invalid, and returning the value in Val.
614static bool GetLineValue(Token &DigitTok, unsigned &Val,
615 unsigned DiagID, Preprocessor &PP) {
616 if (DigitTok.isNot(tok::numeric_constant)) {
617 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Chris Lattner478a18e2009-01-26 06:19:46 +0000619 if (DigitTok.isNot(tok::eom))
620 PP.DiscardUntilEndOfDirective();
621 return true;
622 }
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattner478a18e2009-01-26 06:19:46 +0000624 llvm::SmallString<64> IntegerBuffer;
625 IntegerBuffer.resize(DigitTok.getLength());
626 const char *DigitTokBegin = &IntegerBuffer[0];
627 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000629 // Verify that we have a simple digit-sequence, and compute the value. This
630 // is always a simple digit string computed in decimal, so we do this manually
631 // here.
632 Val = 0;
633 for (unsigned i = 0; i != ActualLength; ++i) {
634 if (!isdigit(DigitTokBegin[i])) {
635 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
636 diag::err_pp_line_digit_sequence);
637 PP.DiscardUntilEndOfDirective();
638 return true;
639 }
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000641 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
642 if (NextVal < Val) { // overflow.
643 PP.Diag(DigitTok, DiagID);
644 PP.DiscardUntilEndOfDirective();
645 return true;
646 }
647 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000648 }
Mike Stump1eb44332009-09-09 15:08:12 +0000649
650 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000651 if (Val == 0) {
652 PP.Diag(DigitTok, DiagID);
653 PP.DiscardUntilEndOfDirective();
654 return true;
655 }
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000657 if (DigitTokBegin[0] == '0')
658 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Chris Lattner478a18e2009-01-26 06:19:46 +0000660 return false;
661}
662
Mike Stump1eb44332009-09-09 15:08:12 +0000663/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000664/// acceptable forms are:
665/// # line digit-sequence
666/// # line digit-sequence "s-char-sequence"
667void Preprocessor::HandleLineDirective(Token &Tok) {
668 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
669 // expanded.
670 Token DigitTok;
671 Lex(DigitTok);
672
Chris Lattner359cc442009-01-26 05:29:08 +0000673 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000674 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000675 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000676 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000677
Chris Lattner478a18e2009-01-26 06:19:46 +0000678 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
679 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000680 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
681 if (LineNo >= LineLimit)
682 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattner5b9a5042009-01-26 07:57:50 +0000684 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000685 Token StrTok;
686 Lex(StrTok);
687
688 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
689 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000690 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000691 ; // ok
692 else if (StrTok.isNot(tok::string_literal)) {
693 Diag(StrTok, diag::err_pp_line_invalid_filename);
694 DiscardUntilEndOfDirective();
695 return;
696 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000697 // Parse and validate the string, converting it into a unique ID.
698 StringLiteralParser Literal(&StrTok, 1, *this);
699 assert(!Literal.AnyWide && "Didn't allow wide strings in");
700 if (Literal.hadError)
701 return DiscardUntilEndOfDirective();
702 if (Literal.Pascal) {
703 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
704 return DiscardUntilEndOfDirective();
705 }
706 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
707 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattnerab82f412009-04-17 23:30:53 +0000709 // Verify that there is nothing after the string, other than EOM. Because
710 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
711 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000712 }
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattner4c4ea172009-02-03 21:52:55 +0000714 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Chris Lattner16629382009-03-27 17:13:49 +0000716 if (Callbacks)
717 Callbacks->FileChanged(DigitTok.getLocation(), PPCallbacks::RenameFile,
718 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000719}
720
Chris Lattner478a18e2009-01-26 06:19:46 +0000721/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
722/// marker directive.
723static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
724 bool &IsSystemHeader, bool &IsExternCHeader,
725 Preprocessor &PP) {
726 unsigned FlagVal;
727 Token FlagTok;
728 PP.Lex(FlagTok);
729 if (FlagTok.is(tok::eom)) return false;
730 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
731 return true;
732
733 if (FlagVal == 1) {
734 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Chris Lattner478a18e2009-01-26 06:19:46 +0000736 PP.Lex(FlagTok);
737 if (FlagTok.is(tok::eom)) return false;
738 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
739 return true;
740 } else if (FlagVal == 2) {
741 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Chris Lattner137b6a62009-02-04 06:25:26 +0000743 SourceManager &SM = PP.getSourceManager();
744 // If we are leaving the current presumed file, check to make sure the
745 // presumed include stack isn't empty!
746 FileID CurFileID =
747 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
748 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Chris Lattner137b6a62009-02-04 06:25:26 +0000750 // If there is no include loc (main file) or if the include loc is in a
751 // different physical file, then we aren't in a "1" line marker flag region.
752 SourceLocation IncLoc = PLoc.getIncludeLoc();
753 if (IncLoc.isInvalid() ||
754 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
755 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
756 PP.DiscardUntilEndOfDirective();
757 return true;
758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Chris Lattner478a18e2009-01-26 06:19:46 +0000760 PP.Lex(FlagTok);
761 if (FlagTok.is(tok::eom)) return false;
762 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
763 return true;
764 }
765
766 // We must have 3 if there are still flags.
767 if (FlagVal != 3) {
768 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000769 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000770 return true;
771 }
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Chris Lattner478a18e2009-01-26 06:19:46 +0000773 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Chris Lattner478a18e2009-01-26 06:19:46 +0000775 PP.Lex(FlagTok);
776 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000777 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000778 return true;
779
780 // We must have 4 if there is yet another flag.
781 if (FlagVal != 4) {
782 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000783 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000784 return true;
785 }
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattner478a18e2009-01-26 06:19:46 +0000787 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Chris Lattner478a18e2009-01-26 06:19:46 +0000789 PP.Lex(FlagTok);
790 if (FlagTok.is(tok::eom)) return false;
791
792 // There are no more valid flags here.
793 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000794 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000795 return true;
796}
797
798/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
799/// one of the following forms:
800///
801/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000802/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000803/// # 42 "file" ('1' | '2')? '3' '4'?
804///
805void Preprocessor::HandleDigitDirective(Token &DigitTok) {
806 // Validate the number and convert it to an unsigned. GNU does not have a
807 // line # limit other than it fit in 32-bits.
808 unsigned LineNo;
809 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
810 *this))
811 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Chris Lattner478a18e2009-01-26 06:19:46 +0000813 Token StrTok;
814 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Chris Lattner478a18e2009-01-26 06:19:46 +0000816 bool IsFileEntry = false, IsFileExit = false;
817 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000818 int FilenameID = -1;
819
Chris Lattner478a18e2009-01-26 06:19:46 +0000820 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
821 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000822 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000823 ; // ok
824 else if (StrTok.isNot(tok::string_literal)) {
825 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000826 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000827 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000828 // Parse and validate the string, converting it into a unique ID.
829 StringLiteralParser Literal(&StrTok, 1, *this);
830 assert(!Literal.AnyWide && "Didn't allow wide strings in");
831 if (Literal.hadError)
832 return DiscardUntilEndOfDirective();
833 if (Literal.Pascal) {
834 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
835 return DiscardUntilEndOfDirective();
836 }
837 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
838 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattner478a18e2009-01-26 06:19:46 +0000840 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000841 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000842 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000843 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000844 }
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Chris Lattner9d79eba2009-02-04 05:21:58 +0000846 // Create a line note with this information.
847 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000848 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000849 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Chris Lattner16629382009-03-27 17:13:49 +0000851 // If the preprocessor has callbacks installed, notify them of the #line
852 // change. This is used so that the line marker comes out in -E mode for
853 // example.
854 if (Callbacks) {
855 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
856 if (IsFileEntry)
857 Reason = PPCallbacks::EnterFile;
858 else if (IsFileExit)
859 Reason = PPCallbacks::ExitFile;
860 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
861 if (IsExternCHeader)
862 FileKind = SrcMgr::C_ExternCSystem;
863 else if (IsSystemHeader)
864 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Chris Lattner16629382009-03-27 17:13:49 +0000866 Callbacks->FileChanged(DigitTok.getLocation(), Reason, FileKind);
867 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000868}
869
870
Chris Lattner099dd052009-01-26 05:30:54 +0000871/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
872///
Mike Stump1eb44332009-09-09 15:08:12 +0000873void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000874 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000875 // PTH doesn't emit #warning or #error directives.
876 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000877 return CurPTHLexer->DiscardToEndOfLine();
878
Chris Lattner141e71f2008-03-09 01:54:53 +0000879 // Read the rest of the line raw. We do this because we don't want macros
880 // to be expanded and we don't require that the tokens be valid preprocessing
881 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
882 // collapse multiple consequtive white space between tokens, but this isn't
883 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000884 std::string Message = CurLexer->ReadToEndOfLine();
885 if (isWarning)
886 Diag(Tok, diag::pp_hash_warning) << Message;
887 else
888 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000889}
890
891/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
892///
893void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
894 // Yes, this directive is an extension.
895 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattner141e71f2008-03-09 01:54:53 +0000897 // Read the string argument.
898 Token StrTok;
899 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chris Lattner141e71f2008-03-09 01:54:53 +0000901 // If the token kind isn't a string, it's a malformed directive.
902 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000903 StrTok.isNot(tok::wide_string_literal)) {
904 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000905 if (StrTok.isNot(tok::eom))
906 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000907 return;
908 }
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Chris Lattner141e71f2008-03-09 01:54:53 +0000910 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000911 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000912
913 if (Callbacks)
914 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
915}
916
917//===----------------------------------------------------------------------===//
918// Preprocessor Include Directive Handling.
919//===----------------------------------------------------------------------===//
920
921/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
922/// checked and spelled filename, e.g. as an operand of #include. This returns
923/// true if the input filename was in <>'s or false if it were in ""'s. The
924/// caller is expected to provide a buffer that is large enough to hold the
925/// spelling of the filename, but is also expected to handle the case when
926/// this method decides to use a different buffer.
927bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
928 const char *&BufStart,
929 const char *&BufEnd) {
930 // Get the text form of the filename.
931 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattner141e71f2008-03-09 01:54:53 +0000933 // Make sure the filename is <x> or "x".
934 bool isAngled;
935 if (BufStart[0] == '<') {
936 if (BufEnd[-1] != '>') {
937 Diag(Loc, diag::err_pp_expects_filename);
938 BufStart = 0;
939 return true;
940 }
941 isAngled = true;
942 } else if (BufStart[0] == '"') {
943 if (BufEnd[-1] != '"') {
944 Diag(Loc, diag::err_pp_expects_filename);
945 BufStart = 0;
946 return true;
947 }
948 isAngled = false;
949 } else {
950 Diag(Loc, diag::err_pp_expects_filename);
951 BufStart = 0;
952 return true;
953 }
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Chris Lattner141e71f2008-03-09 01:54:53 +0000955 // Diagnose #include "" as invalid.
956 if (BufEnd-BufStart <= 2) {
957 Diag(Loc, diag::err_pp_empty_filename);
958 BufStart = 0;
959 return "";
960 }
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Chris Lattner141e71f2008-03-09 01:54:53 +0000962 // Skip the brackets.
963 ++BufStart;
964 --BufEnd;
965 return isAngled;
966}
967
968/// ConcatenateIncludeName - Handle cases where the #include name is expanded
969/// from a macro as multiple tokens, which need to be glued together. This
970/// occurs for code like:
971/// #define FOO <a/b.h>
972/// #include FOO
973/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
974///
975/// This code concatenates and consumes tokens up to the '>' token. It returns
976/// false if the > was found, otherwise it returns true if it finds and consumes
977/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +0000978bool Preprocessor::ConcatenateIncludeName(
979 llvm::SmallVector<char, 128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000980 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +0000981
John Thompsona28cc092009-10-30 13:49:06 +0000982 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000983 while (CurTok.isNot(tok::eom)) {
984 // Append the spelling of this token to the buffer. If there was a space
985 // before it, add it now.
986 if (CurTok.hasLeadingSpace())
987 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Chris Lattner141e71f2008-03-09 01:54:53 +0000989 // Get the spelling of the token, directly into FilenameBuffer if possible.
990 unsigned PreAppendSize = FilenameBuffer.size();
991 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Chris Lattner141e71f2008-03-09 01:54:53 +0000993 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +0000994 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Chris Lattner141e71f2008-03-09 01:54:53 +0000996 // If the token was spelled somewhere else, copy it into FilenameBuffer.
997 if (BufPtr != &FilenameBuffer[PreAppendSize])
998 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Chris Lattner141e71f2008-03-09 01:54:53 +00001000 // Resize FilenameBuffer to the correct size.
1001 if (CurTok.getLength() != ActualLen)
1002 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Chris Lattner141e71f2008-03-09 01:54:53 +00001004 // If we found the '>' marker, return success.
1005 if (CurTok.is(tok::greater))
1006 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001007
John Thompsona28cc092009-10-30 13:49:06 +00001008 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001009 }
1010
1011 // If we hit the eom marker, emit an error and return true so that the caller
1012 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001013 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001014 return true;
1015}
1016
1017/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1018/// file to be included from the lexer, then include it! This is a common
1019/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001020/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001021/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001022void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1023 const DirectoryLookup *LookupFrom,
1024 bool isImport) {
1025
1026 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001027 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Chris Lattner141e71f2008-03-09 01:54:53 +00001029 // Reserve a buffer to get the spelling.
1030 llvm::SmallVector<char, 128> FilenameBuffer;
1031 const char *FilenameStart, *FilenameEnd;
1032
1033 switch (FilenameTok.getKind()) {
1034 case tok::eom:
1035 // If the token kind is EOM, the error has already been diagnosed.
1036 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Chris Lattner141e71f2008-03-09 01:54:53 +00001038 case tok::angle_string_literal:
1039 case tok::string_literal: {
1040 FilenameBuffer.resize(FilenameTok.getLength());
1041 FilenameStart = &FilenameBuffer[0];
1042 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1043 FilenameEnd = FilenameStart+Len;
1044 break;
1045 }
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Chris Lattner141e71f2008-03-09 01:54:53 +00001047 case tok::less:
1048 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1049 // case, glue the tokens together into FilenameBuffer and interpret those.
1050 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001051 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001052 return; // Found <eom> but no ">"? Diagnostic already emitted.
Jay Foadbeaaccd2009-05-21 09:52:38 +00001053 FilenameStart = FilenameBuffer.data();
1054 FilenameEnd = FilenameStart + FilenameBuffer.size();
Chris Lattner141e71f2008-03-09 01:54:53 +00001055 break;
1056 default:
1057 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1058 DiscardUntilEndOfDirective();
1059 return;
1060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Chris Lattner141e71f2008-03-09 01:54:53 +00001062 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
1063 FilenameStart, FilenameEnd);
1064 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1065 // error.
1066 if (FilenameStart == 0) {
1067 DiscardUntilEndOfDirective();
1068 return;
1069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001071 // Verify that there is nothing after the filename, other than EOM. Note that
1072 // we allow macros that expand to nothing after the filename, because this
1073 // falls into the category of "#include pp-tokens new-line" specified in
1074 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001075 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001076
1077 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001078 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1079 Diag(FilenameTok, diag::err_pp_include_too_deep);
1080 return;
1081 }
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Chris Lattner141e71f2008-03-09 01:54:53 +00001083 // Search include directories.
1084 const DirectoryLookup *CurDir;
1085 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1086 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001087 if (File == 0) {
1088 Diag(FilenameTok, diag::err_pp_file_not_found)
1089 << std::string(FilenameStart, FilenameEnd);
1090 return;
1091 }
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Chris Lattner72181832008-09-26 20:12:23 +00001093 // Ask HeaderInfo if we should enter this #include file. If not, #including
1094 // this file will have no effect.
1095 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001096 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Chris Lattner72181832008-09-26 20:12:23 +00001098 // The #included file will be considered to be a system header if either it is
1099 // in a system include directory, or if the #includer is a system include
1100 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001101 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001102 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001103 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Chris Lattner141e71f2008-03-09 01:54:53 +00001105 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001106 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1107 FileCharacter);
1108 if (FID.isInvalid()) {
Chris Lattner56b05c82008-11-18 08:02:48 +00001109 Diag(FilenameTok, diag::err_pp_file_not_found)
1110 << std::string(FilenameStart, FilenameEnd);
1111 return;
1112 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001113
1114 // Finally, if all is good, enter the new file!
Chris Lattner39d98412009-12-01 22:52:33 +00001115 std::string ErrorStr;
Daniel Dunbar63ceaa32009-12-06 09:19:12 +00001116 if (EnterSourceFile(FID, CurDir, ErrorStr))
Chris Lattner6e290142009-11-30 04:18:44 +00001117 Diag(FilenameTok, diag::err_pp_error_opening_file)
Chris Lattner39d98412009-12-01 22:52:33 +00001118 << std::string(SourceMgr.getFileEntryForID(FID)->getName()) << ErrorStr;
Chris Lattner141e71f2008-03-09 01:54:53 +00001119}
1120
1121/// HandleIncludeNextDirective - Implements #include_next.
1122///
1123void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1124 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Chris Lattner141e71f2008-03-09 01:54:53 +00001126 // #include_next is like #include, except that we start searching after
1127 // the current found directory. If we can't do this, issue a
1128 // diagnostic.
1129 const DirectoryLookup *Lookup = CurDirLookup;
1130 if (isInPrimaryFile()) {
1131 Lookup = 0;
1132 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1133 } else if (Lookup == 0) {
1134 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1135 } else {
1136 // Start looking up in the next directory.
1137 ++Lookup;
1138 }
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Chris Lattner141e71f2008-03-09 01:54:53 +00001140 return HandleIncludeDirective(IncludeNextTok, Lookup);
1141}
1142
1143/// HandleImportDirective - Implements #import.
1144///
1145void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001146 if (!Features.ObjC1) // #import is standard for ObjC.
1147 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Chris Lattner141e71f2008-03-09 01:54:53 +00001149 return HandleIncludeDirective(ImportTok, 0, true);
1150}
1151
Chris Lattnerde076652009-04-08 18:46:40 +00001152/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1153/// pseudo directive in the predefines buffer. This handles it by sucking all
1154/// tokens through the preprocessor and discarding them (only keeping the side
1155/// effects on the preprocessor).
1156void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1157 // This directive should only occur in the predefines buffer. If not, emit an
1158 // error and reject it.
1159 SourceLocation Loc = IncludeMacrosTok.getLocation();
1160 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1161 Diag(IncludeMacrosTok.getLocation(),
1162 diag::pp_include_macros_out_of_predefines);
1163 DiscardUntilEndOfDirective();
1164 return;
1165 }
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Chris Lattnerfd105112009-04-08 20:53:24 +00001167 // Treat this as a normal #include for checking purposes. If this is
1168 // successful, it will push a new lexer onto the include stack.
1169 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Chris Lattnerfd105112009-04-08 20:53:24 +00001171 Token TmpTok;
1172 do {
1173 Lex(TmpTok);
1174 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1175 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001176}
1177
Chris Lattner141e71f2008-03-09 01:54:53 +00001178//===----------------------------------------------------------------------===//
1179// Preprocessor Macro Directive Handling.
1180//===----------------------------------------------------------------------===//
1181
1182/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1183/// definition has just been read. Lex the rest of the arguments and the
1184/// closing ), updating MI with what we learn. Return true if an error occurs
1185/// parsing the arg list.
1186bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1187 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Chris Lattner141e71f2008-03-09 01:54:53 +00001189 Token Tok;
1190 while (1) {
1191 LexUnexpandedToken(Tok);
1192 switch (Tok.getKind()) {
1193 case tok::r_paren:
1194 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001195 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001196 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001197 // Otherwise we have #define FOO(A,)
1198 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1199 return true;
1200 case tok::ellipsis: // #define X(... -> C99 varargs
1201 // Warn if use of C99 feature in non-C99 mode.
1202 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1203
1204 // Lex the token after the identifier.
1205 LexUnexpandedToken(Tok);
1206 if (Tok.isNot(tok::r_paren)) {
1207 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1208 return true;
1209 }
1210 // Add the __VA_ARGS__ identifier as an argument.
1211 Arguments.push_back(Ident__VA_ARGS__);
1212 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001213 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001214 return false;
1215 case tok::eom: // #define X(
1216 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1217 return true;
1218 default:
1219 // Handle keywords and identifiers here to accept things like
1220 // #define Foo(for) for.
1221 IdentifierInfo *II = Tok.getIdentifierInfo();
1222 if (II == 0) {
1223 // #define X(1
1224 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1225 return true;
1226 }
1227
1228 // If this is already used as an argument, it is used multiple times (e.g.
1229 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001230 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001231 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001232 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001233 return true;
1234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Chris Lattner141e71f2008-03-09 01:54:53 +00001236 // Add the argument to the macro info.
1237 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Chris Lattner141e71f2008-03-09 01:54:53 +00001239 // Lex the token after the identifier.
1240 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Chris Lattner141e71f2008-03-09 01:54:53 +00001242 switch (Tok.getKind()) {
1243 default: // #define X(A B
1244 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1245 return true;
1246 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001247 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001248 return false;
1249 case tok::comma: // #define X(A,
1250 break;
1251 case tok::ellipsis: // #define X(A... -> GCC extension
1252 // Diagnose extension.
1253 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Chris Lattner141e71f2008-03-09 01:54:53 +00001255 // Lex the token after the identifier.
1256 LexUnexpandedToken(Tok);
1257 if (Tok.isNot(tok::r_paren)) {
1258 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1259 return true;
1260 }
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Chris Lattner141e71f2008-03-09 01:54:53 +00001262 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001263 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001264 return false;
1265 }
1266 }
1267 }
1268}
1269
1270/// HandleDefineDirective - Implements #define. This consumes the entire macro
1271/// line then lets the caller lex the next real token.
1272void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1273 ++NumDefined;
1274
1275 Token MacroNameTok;
1276 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Chris Lattner141e71f2008-03-09 01:54:53 +00001278 // Error reading macro name? If so, diagnostic already issued.
1279 if (MacroNameTok.is(tok::eom))
1280 return;
1281
Chris Lattner2451b522009-04-21 04:46:33 +00001282 Token LastTok = MacroNameTok;
1283
Chris Lattner141e71f2008-03-09 01:54:53 +00001284 // If we are supposed to keep comments in #defines, reenable comment saving
1285 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001286 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Chris Lattner141e71f2008-03-09 01:54:53 +00001288 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001289 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Chris Lattner141e71f2008-03-09 01:54:53 +00001291 Token Tok;
1292 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Chris Lattner141e71f2008-03-09 01:54:53 +00001294 // If this is a function-like macro definition, parse the argument list,
1295 // marking each of the identifiers as being used as macro arguments. Also,
1296 // check other constraints on the first token of the macro body.
1297 if (Tok.is(tok::eom)) {
1298 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001299 } else if (Tok.hasLeadingSpace()) {
1300 // This is a normal token with leading space. Clear the leading space
1301 // marker on the first token to get proper expansion.
1302 Tok.clearFlag(Token::LeadingSpace);
1303 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001304 // This is a function-like macro definition. Read the argument list.
1305 MI->setIsFunctionLike();
1306 if (ReadMacroDefinitionArgList(MI)) {
1307 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001308 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001309 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001310 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001311 DiscardUntilEndOfDirective();
1312 return;
1313 }
1314
Chris Lattner8fde5972009-04-19 18:26:34 +00001315 // If this is a definition of a variadic C99 function-like macro, not using
1316 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Chris Lattner8fde5972009-04-19 18:26:34 +00001318 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1319 // This gets unpoisoned where it is allowed.
1320 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1321 if (MI->isC99Varargs())
1322 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Chris Lattner141e71f2008-03-09 01:54:53 +00001324 // Read the first token after the arg list for down below.
1325 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001326 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001327 // C99 requires whitespace between the macro definition and the body. Emit
1328 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001329 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001330 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001331 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1332 // first character of a replacement list is not a character required by
1333 // subclause 5.2.1, then there shall be white-space separation between the
1334 // identifier and the replacement list.". 5.2.1 lists this set:
1335 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1336 // is irrelevant here.
1337 bool isInvalid = false;
1338 if (Tok.is(tok::at)) // @ is not in the list above.
1339 isInvalid = true;
1340 else if (Tok.is(tok::unknown)) {
1341 // If we have an unknown token, it is something strange like "`". Since
1342 // all of valid characters would have lexed into a single character
1343 // token of some sort, we know this is not a valid case.
1344 isInvalid = true;
1345 }
1346 if (isInvalid)
1347 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1348 else
1349 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001350 }
Chris Lattner2451b522009-04-21 04:46:33 +00001351
1352 if (!Tok.is(tok::eom))
1353 LastTok = Tok;
1354
Chris Lattner141e71f2008-03-09 01:54:53 +00001355 // Read the rest of the macro body.
1356 if (MI->isObjectLike()) {
1357 // Object-like macros are very simple, just read their body.
1358 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001359 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001360 MI->AddTokenToBody(Tok);
1361 // Get the next token of the macro.
1362 LexUnexpandedToken(Tok);
1363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Chris Lattner141e71f2008-03-09 01:54:53 +00001365 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001366 // Otherwise, read the body of a function-like macro. While we are at it,
1367 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1368 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001369 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001370 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001371
Chris Lattner141e71f2008-03-09 01:54:53 +00001372 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001373 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Chris Lattner141e71f2008-03-09 01:54:53 +00001375 // Get the next token of the macro.
1376 LexUnexpandedToken(Tok);
1377 continue;
1378 }
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Chris Lattner141e71f2008-03-09 01:54:53 +00001380 // Get the next token of the macro.
1381 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Chris Lattner32404692009-05-25 17:16:10 +00001383 // Check for a valid macro arg identifier.
1384 if (Tok.getIdentifierInfo() == 0 ||
1385 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1386
1387 // If this is assembler-with-cpp mode, we accept random gibberish after
1388 // the '#' because '#' is often a comment character. However, change
1389 // the kind of the token to tok::unknown so that the preprocessor isn't
1390 // confused.
1391 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1392 LastTok.setKind(tok::unknown);
1393 } else {
1394 Diag(Tok, diag::err_pp_stringize_not_parameter);
1395 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Chris Lattner32404692009-05-25 17:16:10 +00001397 // Disable __VA_ARGS__ again.
1398 Ident__VA_ARGS__->setIsPoisoned(true);
1399 return;
1400 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001401 }
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Chris Lattner32404692009-05-25 17:16:10 +00001403 // Things look ok, add the '#' and param name tokens to the macro.
1404 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001405 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001406 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Chris Lattner141e71f2008-03-09 01:54:53 +00001408 // Get the next token of the macro.
1409 LexUnexpandedToken(Tok);
1410 }
1411 }
Mike Stump1eb44332009-09-09 15:08:12 +00001412
1413
Chris Lattner141e71f2008-03-09 01:54:53 +00001414 // Disable __VA_ARGS__ again.
1415 Ident__VA_ARGS__->setIsPoisoned(true);
1416
1417 // Check that there is no paste (##) operator at the begining or end of the
1418 // replacement list.
1419 unsigned NumTokens = MI->getNumTokens();
1420 if (NumTokens != 0) {
1421 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1422 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001423 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001424 return;
1425 }
1426 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1427 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001428 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001429 return;
1430 }
1431 }
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Chris Lattner141e71f2008-03-09 01:54:53 +00001433 // If this is the primary source file, remember that this macro hasn't been
1434 // used yet.
1435 if (isInPrimaryFile())
1436 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001437
1438 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Chris Lattner141e71f2008-03-09 01:54:53 +00001440 // Finally, if this identifier already had a macro defined for it, verify that
1441 // the macro bodies are identical and free the old definition.
1442 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001443 // It is very common for system headers to have tons of macro redefinitions
1444 // and for warnings to be disabled in system headers. If this is the case,
1445 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001446 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001447 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1448 if (!OtherMI->isUsed())
1449 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001450
Chris Lattner41c3ae12009-01-16 19:50:11 +00001451 // Macros must be identical. This means all tokes and whitespace
1452 // separation must be the same. C99 6.10.3.2.
1453 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1454 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1455 << MacroNameTok.getIdentifierInfo();
1456 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1457 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001458 }
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Ted Kremenek0ea76722008-12-15 19:56:42 +00001460 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001461 }
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Chris Lattner141e71f2008-03-09 01:54:53 +00001463 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001465 // If the callbacks want to know, tell them about the macro definition.
1466 if (Callbacks)
1467 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001468}
1469
1470/// HandleUndefDirective - Implements #undef.
1471///
1472void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1473 ++NumUndefined;
1474
1475 Token MacroNameTok;
1476 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Chris Lattner141e71f2008-03-09 01:54:53 +00001478 // Error reading macro name? If so, diagnostic already issued.
1479 if (MacroNameTok.is(tok::eom))
1480 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Chris Lattner141e71f2008-03-09 01:54:53 +00001482 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001483 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Chris Lattner141e71f2008-03-09 01:54:53 +00001485 // Okay, we finally have a valid identifier to undef.
1486 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Chris Lattner141e71f2008-03-09 01:54:53 +00001488 // If the macro is not defined, this is a noop undef, just return.
1489 if (MI == 0) return;
1490
1491 if (!MI->isUsed())
1492 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001493
1494 // If the callbacks want to know, tell them about the macro #undef.
1495 if (Callbacks)
1496 Callbacks->MacroUndefined(MacroNameTok.getIdentifierInfo(), MI);
1497
Chris Lattner141e71f2008-03-09 01:54:53 +00001498 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001499 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001500 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1501}
1502
1503
1504//===----------------------------------------------------------------------===//
1505// Preprocessor Conditional Directive Handling.
1506//===----------------------------------------------------------------------===//
1507
1508/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1509/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1510/// if any tokens have been returned or pp-directives activated before this
1511/// #ifndef has been lexed.
1512///
1513void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1514 bool ReadAnyTokensBeforeDirective) {
1515 ++NumIf;
1516 Token DirectiveTok = Result;
1517
1518 Token MacroNameTok;
1519 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Chris Lattner141e71f2008-03-09 01:54:53 +00001521 // Error reading macro name? If so, diagnostic already issued.
1522 if (MacroNameTok.is(tok::eom)) {
1523 // Skip code until we get to #endif. This helps with recovery by not
1524 // emitting an error when the #endif is reached.
1525 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1526 /*Foundnonskip*/false, /*FoundElse*/false);
1527 return;
1528 }
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Chris Lattner141e71f2008-03-09 01:54:53 +00001530 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001531 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001532
Ted Kremenek60e45d42008-11-18 00:34:22 +00001533 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001534 // If the start of a top-level #ifdef, inform MIOpt.
1535 if (!ReadAnyTokensBeforeDirective) {
1536 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001537 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001538 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001539 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001540 }
1541
1542 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1543 MacroInfo *MI = getMacroInfo(MII);
1544
1545 // If there is a macro, process it.
1546 if (MI) // Mark it used.
1547 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Chris Lattner141e71f2008-03-09 01:54:53 +00001549 // Should we include the stuff contained by this directive?
1550 if (!MI == isIfndef) {
1551 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001552 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1553 /*wasskip*/false, /*foundnonskip*/true,
1554 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001555 } else {
1556 // No, skip the contents of this block and return the first token after it.
1557 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001558 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001559 /*FoundElse*/false);
1560 }
1561}
1562
1563/// HandleIfDirective - Implements the #if directive.
1564///
1565void Preprocessor::HandleIfDirective(Token &IfToken,
1566 bool ReadAnyTokensBeforeDirective) {
1567 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Chris Lattner141e71f2008-03-09 01:54:53 +00001569 // Parse and evaluation the conditional expression.
1570 IdentifierInfo *IfNDefMacro = 0;
1571 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Nuno Lopes0049db62008-06-01 18:31:24 +00001573
1574 // If this condition is equivalent to #ifndef X, and if this is the first
1575 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001576 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001577 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001578 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001579 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001580 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001581 }
1582
Chris Lattner141e71f2008-03-09 01:54:53 +00001583 // Should we include the stuff contained by this directive?
1584 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001585 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001586 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001587 /*foundnonskip*/true, /*foundelse*/false);
1588 } else {
1589 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001590 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001591 /*FoundElse*/false);
1592 }
1593}
1594
1595/// HandleEndifDirective - Implements the #endif directive.
1596///
1597void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1598 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Chris Lattner141e71f2008-03-09 01:54:53 +00001600 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001601 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Chris Lattner141e71f2008-03-09 01:54:53 +00001603 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001604 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001605 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001606 Diag(EndifToken, diag::err_pp_endif_without_if);
1607 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001608 }
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Chris Lattner141e71f2008-03-09 01:54:53 +00001610 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001611 if (CurPPLexer->getConditionalStackDepth() == 0)
1612 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Ted Kremenek60e45d42008-11-18 00:34:22 +00001614 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001615 "This code should only be reachable in the non-skipping case!");
1616}
1617
1618
1619void Preprocessor::HandleElseDirective(Token &Result) {
1620 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Chris Lattner141e71f2008-03-09 01:54:53 +00001622 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001623 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Chris Lattner141e71f2008-03-09 01:54:53 +00001625 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001626 if (CurPPLexer->popConditionalLevel(CI)) {
1627 Diag(Result, diag::pp_err_else_without_if);
1628 return;
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Chris Lattner141e71f2008-03-09 01:54:53 +00001631 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001632 if (CurPPLexer->getConditionalStackDepth() == 0)
1633 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001634
1635 // If this is a #else with a #else before it, report the error.
1636 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Chris Lattner141e71f2008-03-09 01:54:53 +00001638 // Finally, skip the rest of the contents of this block and return the first
1639 // token after it.
1640 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1641 /*FoundElse*/true);
1642}
1643
1644void Preprocessor::HandleElifDirective(Token &ElifToken) {
1645 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Chris Lattner141e71f2008-03-09 01:54:53 +00001647 // #elif directive in a non-skipping conditional... start skipping.
1648 // We don't care what the condition is, because we will always skip it (since
1649 // the block immediately before it was included).
1650 DiscardUntilEndOfDirective();
1651
1652 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001653 if (CurPPLexer->popConditionalLevel(CI)) {
1654 Diag(ElifToken, diag::pp_err_elif_without_if);
1655 return;
1656 }
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Chris Lattner141e71f2008-03-09 01:54:53 +00001658 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001659 if (CurPPLexer->getConditionalStackDepth() == 0)
1660 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Chris Lattner141e71f2008-03-09 01:54:53 +00001662 // If this is a #elif with a #else before it, report the error.
1663 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1664
1665 // Finally, skip the rest of the contents of this block and return the first
1666 // token after it.
1667 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1668 /*FoundElse*/CI.FoundElse);
1669}
1670