blob: b0e784bcd96a1a311d84b3aa9818185d57ef044e [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) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000163 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattner141e71f2008-03-09 01:54:53 +0000165 // If this is the end of the buffer, we have an error.
166 if (Tok.is(tok::eof)) {
167 // Emit errors for each unterminated conditional on the stack, including
168 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000169 while (!CurPPLexer->ConditionalStack.empty()) {
170 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000171 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000172 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000173 }
174
Chris Lattner141e71f2008-03-09 01:54:53 +0000175 // Just return and let the caller lex after this #include.
176 break;
177 }
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Chris Lattner141e71f2008-03-09 01:54:53 +0000179 // If this token is not a preprocessor directive, just skip it.
180 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
181 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Chris Lattner141e71f2008-03-09 01:54:53 +0000183 // We just parsed a # character at the start of a line, so we're in
184 // directive mode. Tell the lexer this so any newlines we see will be
185 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000186 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000187 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000188
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Chris Lattner141e71f2008-03-09 01:54:53 +0000190 // Read the next token, the directive flavor.
191 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner141e71f2008-03-09 01:54:53 +0000193 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
194 // something bogus), skip it.
195 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000196 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000197 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000198 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000199 continue;
200 }
201
202 // If the first letter isn't i or e, it isn't intesting to us. We know that
203 // this is safe in the face of spelling differences, because there is no way
204 // to spell an i/e in a strange way that is another letter. Skipping this
205 // allows us to avoid looking up the identifier info for #define/#undef and
206 // other common directives.
207 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
208 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000209 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000210 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000211 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000212 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000213 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000214 continue;
215 }
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Chris Lattner141e71f2008-03-09 01:54:53 +0000217 // Get the identifier name without trigraphs or embedded newlines. Note
218 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
219 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000220 char DirectiveBuf[20];
221 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000222 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000223 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000224 } else {
225 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000226 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000227 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000228 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000229 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000230 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000231 continue;
232 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000233 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
234 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000235 }
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000237 if (Directive.startswith("if")) {
238 llvm::StringRef Sub = Directive.substr(2);
239 if (Sub.empty() || // "if"
240 Sub == "def" || // "ifdef"
241 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000242 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
243 // bother parsing the condition.
244 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000245 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000246 /*foundnonskip*/false,
247 /*fnddelse*/false);
248 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000249 } else if (Directive[0] == 'e') {
250 llvm::StringRef Sub = Directive.substr(1);
251 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000252 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000253 PPConditionalInfo CondInfo;
254 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000255 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000256 InCond = InCond; // Silence warning in no-asserts mode.
257 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Chris Lattner141e71f2008-03-09 01:54:53 +0000259 // If we popped the outermost skipping block, we're done skipping!
260 if (!CondInfo.WasSkipping)
261 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000262 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000263 // #else directive in a skipping conditional. If not in some other
264 // skipping conditional, and if #else hasn't already been seen, enter it
265 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000266 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000267 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Chris Lattner141e71f2008-03-09 01:54:53 +0000269 // If this is a #else with a #else before it, report the error.
270 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Chris Lattner141e71f2008-03-09 01:54:53 +0000272 // Note that we've seen a #else in this conditional.
273 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattner141e71f2008-03-09 01:54:53 +0000275 // If the conditional is at the top level, and the #if block wasn't
276 // entered, enter the #else block now.
277 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
278 CondInfo.FoundNonSkip = true;
279 break;
280 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000281 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000282 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000283
284 bool ShouldEnter;
285 // If this is in a skipping block or if we're already handled this #if
286 // block, don't bother parsing the condition.
287 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
288 DiscardUntilEndOfDirective();
289 ShouldEnter = false;
290 } else {
291 // Restore the value of LexingRawMode so that identifiers are
292 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000293 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
294 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000295 IdentifierInfo *IfNDefMacro = 0;
296 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000297 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000298 }
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattner141e71f2008-03-09 01:54:53 +0000300 // If this is a #elif with a #else before it, report the error.
301 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 // If this condition is true, enter it!
304 if (ShouldEnter) {
305 CondInfo.FoundNonSkip = true;
306 break;
307 }
308 }
309 }
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Ted Kremenek60e45d42008-11-18 00:34:22 +0000311 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000312 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000313 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000314 }
315
316 // Finally, if we are out of the conditional (saw an #endif or ran off the end
317 // of the file, just stop skipping and return to lexing whatever came after
318 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000319 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000320}
321
Ted Kremenek268ee702008-12-12 18:34:08 +0000322void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000323
324 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000325 assert(CurPTHLexer);
326 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Ted Kremenek268ee702008-12-12 18:34:08 +0000328 // Skip to the next '#else', '#elif', or #endif.
329 if (CurPTHLexer->SkipBlock()) {
330 // We have reached an #endif. Both the '#' and 'endif' tokens
331 // have been consumed by the PTHLexer. Just pop off the condition level.
332 PPConditionalInfo CondInfo;
333 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
334 InCond = InCond; // Silence warning in no-asserts mode.
335 assert(!InCond && "Can't be skipping if not in a conditional!");
336 break;
337 }
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Ted Kremenek268ee702008-12-12 18:34:08 +0000339 // We have reached a '#else' or '#elif'. Lex the next token to get
340 // the directive flavor.
341 Token Tok;
342 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Ted Kremenek268ee702008-12-12 18:34:08 +0000344 // We can actually look up the IdentifierInfo here since we aren't in
345 // raw mode.
346 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
347
348 if (K == tok::pp_else) {
349 // #else: Enter the else condition. We aren't in a nested condition
350 // since we skip those. We're always in the one matching the last
351 // blocked we skipped.
352 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
353 // Note that we've seen a #else in this conditional.
354 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Ted Kremenek268ee702008-12-12 18:34:08 +0000356 // If the #if block wasn't entered then enter the #else block now.
357 if (!CondInfo.FoundNonSkip) {
358 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000360 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000361 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000362 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000363 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Ted Kremenek268ee702008-12-12 18:34:08 +0000365 break;
366 }
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Ted Kremenek268ee702008-12-12 18:34:08 +0000368 // Otherwise skip this block.
369 continue;
370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Ted Kremenek268ee702008-12-12 18:34:08 +0000372 assert(K == tok::pp_elif);
373 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
374
375 // If this is a #elif with a #else before it, report the error.
376 if (CondInfo.FoundElse)
377 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Ted Kremenek268ee702008-12-12 18:34:08 +0000379 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000380 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000381 if (CondInfo.FoundNonSkip)
382 continue;
383
384 // Evaluate the condition of the #elif.
385 IdentifierInfo *IfNDefMacro = 0;
386 CurPTHLexer->ParsingPreprocessorDirective = true;
387 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
388 CurPTHLexer->ParsingPreprocessorDirective = false;
389
390 // If this condition is true, enter it!
391 if (ShouldEnter) {
392 CondInfo.FoundNonSkip = true;
393 break;
394 }
395
396 // Otherwise, skip this block and go to the next one.
397 continue;
398 }
399}
400
Chris Lattner10725092008-03-09 04:17:44 +0000401/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
402/// return null on failure. isAngled indicates whether the file reference is
403/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnera1394812010-01-10 01:35:12 +0000404const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattner10725092008-03-09 04:17:44 +0000405 bool isAngled,
406 const DirectoryLookup *FromDir,
407 const DirectoryLookup *&CurDir) {
408 // If the header lookup mechanism may be relative to the current file, pass in
409 // info about where the current file is.
410 const FileEntry *CurFileEnt = 0;
411 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000412 FileID FID = getCurrentFileLexer()->getFileID();
413 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000415 // If there is no file entry associated with this file, it must be the
416 // predefines buffer. Any other file is not lexed with a normal lexer, so
417 // it won't be scanned for preprocessor directives. If we have the
418 // predefines buffer, resolve #include references (which come from the
419 // -include command line argument) as if they came from the main file, this
420 // affects file lookup etc.
421 if (CurFileEnt == 0) {
422 FID = SourceMgr.getMainFileID();
423 CurFileEnt = SourceMgr.getFileEntryForID(FID);
424 }
Chris Lattner10725092008-03-09 04:17:44 +0000425 }
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Chris Lattner10725092008-03-09 04:17:44 +0000427 // Do a standard file entry lookup.
428 CurDir = CurDirLookup;
429 const FileEntry *FE =
Chris Lattnera1394812010-01-10 01:35:12 +0000430 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000431 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Chris Lattner10725092008-03-09 04:17:44 +0000433 // Otherwise, see if this is a subframework header. If so, this is relative
434 // to one of the headers on the #include stack. Walk the list of the current
435 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000436 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000437 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000438 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000439 return FE;
440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner10725092008-03-09 04:17:44 +0000442 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
443 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000444 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000445 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000446 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000447 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000448 return FE;
449 }
450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Chris Lattner10725092008-03-09 04:17:44 +0000452 // Otherwise, we really couldn't find the file.
453 return 0;
454}
455
Chris Lattner141e71f2008-03-09 01:54:53 +0000456
457//===----------------------------------------------------------------------===//
458// Preprocessor Directive Handling.
459//===----------------------------------------------------------------------===//
460
461/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000462/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000463/// lexer/preprocessor state, and advances the lexer(s) so that the next token
464/// read is the correct one.
465void Preprocessor::HandleDirective(Token &Result) {
466 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Chris Lattner141e71f2008-03-09 01:54:53 +0000468 // We just parsed a # character at the start of a line, so we're in directive
469 // mode. Tell the lexer this so any newlines we see will be converted into an
470 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000471 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Chris Lattner141e71f2008-03-09 01:54:53 +0000473 ++NumDirectives;
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000474
Chris Lattner141e71f2008-03-09 01:54:53 +0000475 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000476 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000477 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000478 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner42aa16c2009-03-18 21:00:25 +0000480 // Save the '#' token in case we need to return it later.
481 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Chris Lattner141e71f2008-03-09 01:54:53 +0000483 // Read the next token, the directive flavor. This isn't expanded due to
484 // C99 6.10.3p8.
485 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Chris Lattner141e71f2008-03-09 01:54:53 +0000487 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
488 // #define A(x) #x
489 // A(abc
490 // #warning blah
491 // def)
492 // If so, the user is relying on non-portable behavior, emit a diagnostic.
493 if (InMacroArgs)
494 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Chris Lattner141e71f2008-03-09 01:54:53 +0000496TryAgain:
497 switch (Result.getKind()) {
498 case tok::eom:
499 return; // null directive.
500 case tok::comment:
501 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
502 LexUnexpandedToken(Result);
503 goto TryAgain;
504
Chris Lattner478a18e2009-01-26 06:19:46 +0000505 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000506 if (getLangOptions().AsmPreprocessor)
507 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000508 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000509 default:
510 IdentifierInfo *II = Result.getIdentifierInfo();
511 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattner141e71f2008-03-09 01:54:53 +0000513 // Ask what the preprocessor keyword ID is.
514 switch (II->getPPKeywordID()) {
515 default: break;
516 // C99 6.10.1 - Conditional Inclusion.
517 case tok::pp_if:
518 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
519 case tok::pp_ifdef:
520 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
521 case tok::pp_ifndef:
522 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
523 case tok::pp_elif:
524 return HandleElifDirective(Result);
525 case tok::pp_else:
526 return HandleElseDirective(Result);
527 case tok::pp_endif:
528 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Chris Lattner141e71f2008-03-09 01:54:53 +0000530 // C99 6.10.2 - Source File Inclusion.
531 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000532 return HandleIncludeDirective(Result); // Handle #include.
533 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000534 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Chris Lattner141e71f2008-03-09 01:54:53 +0000536 // C99 6.10.3 - Macro Replacement.
537 case tok::pp_define:
538 return HandleDefineDirective(Result);
539 case tok::pp_undef:
540 return HandleUndefDirective(Result);
541
542 // C99 6.10.4 - Line Control.
543 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000544 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattner141e71f2008-03-09 01:54:53 +0000546 // C99 6.10.5 - Error Directive.
547 case tok::pp_error:
548 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Chris Lattner141e71f2008-03-09 01:54:53 +0000550 // C99 6.10.6 - Pragma Directive.
551 case tok::pp_pragma:
552 return HandlePragmaDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Chris Lattner141e71f2008-03-09 01:54:53 +0000554 // GNU Extensions.
555 case tok::pp_import:
556 return HandleImportDirective(Result);
557 case tok::pp_include_next:
558 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner141e71f2008-03-09 01:54:53 +0000560 case tok::pp_warning:
561 Diag(Result, diag::ext_pp_warning_directive);
562 return HandleUserDiagnosticDirective(Result, true);
563 case tok::pp_ident:
564 return HandleIdentSCCSDirective(Result);
565 case tok::pp_sccs:
566 return HandleIdentSCCSDirective(Result);
567 case tok::pp_assert:
568 //isExtension = true; // FIXME: implement #assert
569 break;
570 case tok::pp_unassert:
571 //isExtension = true; // FIXME: implement #unassert
572 break;
573 }
574 break;
575 }
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattner42aa16c2009-03-18 21:00:25 +0000577 // If this is a .S file, treat unknown # directives as non-preprocessor
578 // directives. This is important because # may be a comment or introduce
579 // various pseudo-ops. Just return the # token and push back the following
580 // token to be lexed next time.
581 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000582 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000583 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000584 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000585 Toks[1] = Result;
586 // Enter this token stream so that we re-lex the tokens. Make sure to
587 // enable macro expansion, in case the token after the # is an identifier
588 // that is expanded.
589 EnterTokenStream(Toks, 2, false, true);
590 return;
591 }
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Chris Lattner141e71f2008-03-09 01:54:53 +0000593 // If we reached here, the preprocessing token is not valid!
594 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chris Lattner141e71f2008-03-09 01:54:53 +0000596 // Read the rest of the PP line.
597 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Chris Lattner141e71f2008-03-09 01:54:53 +0000599 // Okay, we're done parsing the directive.
600}
601
Chris Lattner478a18e2009-01-26 06:19:46 +0000602/// GetLineValue - Convert a numeric token into an unsigned value, emitting
603/// Diagnostic DiagID if it is invalid, and returning the value in Val.
604static bool GetLineValue(Token &DigitTok, unsigned &Val,
605 unsigned DiagID, Preprocessor &PP) {
606 if (DigitTok.isNot(tok::numeric_constant)) {
607 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattner478a18e2009-01-26 06:19:46 +0000609 if (DigitTok.isNot(tok::eom))
610 PP.DiscardUntilEndOfDirective();
611 return true;
612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Chris Lattner478a18e2009-01-26 06:19:46 +0000614 llvm::SmallString<64> IntegerBuffer;
615 IntegerBuffer.resize(DigitTok.getLength());
616 const char *DigitTokBegin = &IntegerBuffer[0];
617 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000619 // Verify that we have a simple digit-sequence, and compute the value. This
620 // is always a simple digit string computed in decimal, so we do this manually
621 // here.
622 Val = 0;
623 for (unsigned i = 0; i != ActualLength; ++i) {
624 if (!isdigit(DigitTokBegin[i])) {
625 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
626 diag::err_pp_line_digit_sequence);
627 PP.DiscardUntilEndOfDirective();
628 return true;
629 }
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000631 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
632 if (NextVal < Val) { // overflow.
633 PP.Diag(DigitTok, DiagID);
634 PP.DiscardUntilEndOfDirective();
635 return true;
636 }
637 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000638 }
Mike Stump1eb44332009-09-09 15:08:12 +0000639
640 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000641 if (Val == 0) {
642 PP.Diag(DigitTok, DiagID);
643 PP.DiscardUntilEndOfDirective();
644 return true;
645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000647 if (DigitTokBegin[0] == '0')
648 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Chris Lattner478a18e2009-01-26 06:19:46 +0000650 return false;
651}
652
Mike Stump1eb44332009-09-09 15:08:12 +0000653/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000654/// acceptable forms are:
655/// # line digit-sequence
656/// # line digit-sequence "s-char-sequence"
657void Preprocessor::HandleLineDirective(Token &Tok) {
658 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
659 // expanded.
660 Token DigitTok;
661 Lex(DigitTok);
662
Chris Lattner359cc442009-01-26 05:29:08 +0000663 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000664 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000665 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000666 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000667
Chris Lattner478a18e2009-01-26 06:19:46 +0000668 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
669 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000670 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
671 if (LineNo >= LineLimit)
672 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Chris Lattner5b9a5042009-01-26 07:57:50 +0000674 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000675 Token StrTok;
676 Lex(StrTok);
677
678 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
679 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000680 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000681 ; // ok
682 else if (StrTok.isNot(tok::string_literal)) {
683 Diag(StrTok, diag::err_pp_line_invalid_filename);
684 DiscardUntilEndOfDirective();
685 return;
686 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000687 // Parse and validate the string, converting it into a unique ID.
688 StringLiteralParser Literal(&StrTok, 1, *this);
689 assert(!Literal.AnyWide && "Didn't allow wide strings in");
690 if (Literal.hadError)
691 return DiscardUntilEndOfDirective();
692 if (Literal.Pascal) {
693 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
694 return DiscardUntilEndOfDirective();
695 }
696 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
697 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Chris Lattnerab82f412009-04-17 23:30:53 +0000699 // Verify that there is nothing after the string, other than EOM. Because
700 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
701 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000702 }
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Chris Lattner4c4ea172009-02-03 21:52:55 +0000704 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Chris Lattner16629382009-03-27 17:13:49 +0000706 if (Callbacks)
707 Callbacks->FileChanged(DigitTok.getLocation(), PPCallbacks::RenameFile,
708 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000709}
710
Chris Lattner478a18e2009-01-26 06:19:46 +0000711/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
712/// marker directive.
713static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
714 bool &IsSystemHeader, bool &IsExternCHeader,
715 Preprocessor &PP) {
716 unsigned FlagVal;
717 Token FlagTok;
718 PP.Lex(FlagTok);
719 if (FlagTok.is(tok::eom)) return false;
720 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
721 return true;
722
723 if (FlagVal == 1) {
724 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Chris Lattner478a18e2009-01-26 06:19:46 +0000726 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 } else if (FlagVal == 2) {
731 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Chris Lattner137b6a62009-02-04 06:25:26 +0000733 SourceManager &SM = PP.getSourceManager();
734 // If we are leaving the current presumed file, check to make sure the
735 // presumed include stack isn't empty!
736 FileID CurFileID =
737 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
738 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattner137b6a62009-02-04 06:25:26 +0000740 // If there is no include loc (main file) or if the include loc is in a
741 // different physical file, then we aren't in a "1" line marker flag region.
742 SourceLocation IncLoc = PLoc.getIncludeLoc();
743 if (IncLoc.isInvalid() ||
744 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
745 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
746 PP.DiscardUntilEndOfDirective();
747 return true;
748 }
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Chris Lattner478a18e2009-01-26 06:19:46 +0000750 PP.Lex(FlagTok);
751 if (FlagTok.is(tok::eom)) return false;
752 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
753 return true;
754 }
755
756 // We must have 3 if there are still flags.
757 if (FlagVal != 3) {
758 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000759 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000760 return true;
761 }
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Chris Lattner478a18e2009-01-26 06:19:46 +0000763 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner478a18e2009-01-26 06:19:46 +0000765 PP.Lex(FlagTok);
766 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000767 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000768 return true;
769
770 // We must have 4 if there is yet another flag.
771 if (FlagVal != 4) {
772 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000773 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000774 return true;
775 }
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Chris Lattner478a18e2009-01-26 06:19:46 +0000777 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Chris Lattner478a18e2009-01-26 06:19:46 +0000779 PP.Lex(FlagTok);
780 if (FlagTok.is(tok::eom)) return false;
781
782 // There are no more valid flags here.
783 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000784 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000785 return true;
786}
787
788/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
789/// one of the following forms:
790///
791/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000792/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000793/// # 42 "file" ('1' | '2')? '3' '4'?
794///
795void Preprocessor::HandleDigitDirective(Token &DigitTok) {
796 // Validate the number and convert it to an unsigned. GNU does not have a
797 // line # limit other than it fit in 32-bits.
798 unsigned LineNo;
799 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
800 *this))
801 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Chris Lattner478a18e2009-01-26 06:19:46 +0000803 Token StrTok;
804 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Chris Lattner478a18e2009-01-26 06:19:46 +0000806 bool IsFileEntry = false, IsFileExit = false;
807 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000808 int FilenameID = -1;
809
Chris Lattner478a18e2009-01-26 06:19:46 +0000810 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
811 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000812 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000813 ; // ok
814 else if (StrTok.isNot(tok::string_literal)) {
815 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000816 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000817 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000818 // Parse and validate the string, converting it into a unique ID.
819 StringLiteralParser Literal(&StrTok, 1, *this);
820 assert(!Literal.AnyWide && "Didn't allow wide strings in");
821 if (Literal.hadError)
822 return DiscardUntilEndOfDirective();
823 if (Literal.Pascal) {
824 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
825 return DiscardUntilEndOfDirective();
826 }
827 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
828 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Chris Lattner478a18e2009-01-26 06:19:46 +0000830 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000831 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000832 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000833 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000834 }
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Chris Lattner9d79eba2009-02-04 05:21:58 +0000836 // Create a line note with this information.
837 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000838 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000839 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Chris Lattner16629382009-03-27 17:13:49 +0000841 // If the preprocessor has callbacks installed, notify them of the #line
842 // change. This is used so that the line marker comes out in -E mode for
843 // example.
844 if (Callbacks) {
845 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
846 if (IsFileEntry)
847 Reason = PPCallbacks::EnterFile;
848 else if (IsFileExit)
849 Reason = PPCallbacks::ExitFile;
850 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
851 if (IsExternCHeader)
852 FileKind = SrcMgr::C_ExternCSystem;
853 else if (IsSystemHeader)
854 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Chris Lattner16629382009-03-27 17:13:49 +0000856 Callbacks->FileChanged(DigitTok.getLocation(), Reason, FileKind);
857 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000858}
859
860
Chris Lattner099dd052009-01-26 05:30:54 +0000861/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
862///
Mike Stump1eb44332009-09-09 15:08:12 +0000863void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000864 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000865 // PTH doesn't emit #warning or #error directives.
866 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000867 return CurPTHLexer->DiscardToEndOfLine();
868
Chris Lattner141e71f2008-03-09 01:54:53 +0000869 // Read the rest of the line raw. We do this because we don't want macros
870 // to be expanded and we don't require that the tokens be valid preprocessing
871 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
872 // collapse multiple consequtive white space between tokens, but this isn't
873 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000874 std::string Message = CurLexer->ReadToEndOfLine();
875 if (isWarning)
876 Diag(Tok, diag::pp_hash_warning) << Message;
877 else
878 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000879}
880
881/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
882///
883void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
884 // Yes, this directive is an extension.
885 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Chris Lattner141e71f2008-03-09 01:54:53 +0000887 // Read the string argument.
888 Token StrTok;
889 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Chris Lattner141e71f2008-03-09 01:54:53 +0000891 // If the token kind isn't a string, it's a malformed directive.
892 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000893 StrTok.isNot(tok::wide_string_literal)) {
894 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000895 if (StrTok.isNot(tok::eom))
896 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000897 return;
898 }
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner141e71f2008-03-09 01:54:53 +0000900 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000901 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000902
903 if (Callbacks)
904 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
905}
906
907//===----------------------------------------------------------------------===//
908// Preprocessor Include Directive Handling.
909//===----------------------------------------------------------------------===//
910
911/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
912/// checked and spelled filename, e.g. as an operand of #include. This returns
913/// true if the input filename was in <>'s or false if it were in ""'s. The
914/// caller is expected to provide a buffer that is large enough to hold the
915/// spelling of the filename, but is also expected to handle the case when
916/// this method decides to use a different buffer.
917bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000918 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000919 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000920 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Chris Lattner141e71f2008-03-09 01:54:53 +0000922 // Make sure the filename is <x> or "x".
923 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000924 if (Buffer[0] == '<') {
925 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000926 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000927 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000928 return true;
929 }
930 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +0000931 } else if (Buffer[0] == '"') {
932 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000933 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000934 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000935 return true;
936 }
937 isAngled = false;
938 } else {
939 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000940 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000941 return true;
942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Chris Lattner141e71f2008-03-09 01:54:53 +0000944 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +0000945 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000946 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000947 Buffer = llvm::StringRef();
948 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000949 }
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattner141e71f2008-03-09 01:54:53 +0000951 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +0000952 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +0000953 return isAngled;
954}
955
956/// ConcatenateIncludeName - Handle cases where the #include name is expanded
957/// from a macro as multiple tokens, which need to be glued together. This
958/// occurs for code like:
959/// #define FOO <a/b.h>
960/// #include FOO
961/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
962///
963/// This code concatenates and consumes tokens up to the '>' token. It returns
964/// false if the > was found, otherwise it returns true if it finds and consumes
965/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +0000966bool Preprocessor::ConcatenateIncludeName(
967 llvm::SmallVector<char, 128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000968 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +0000969
John Thompsona28cc092009-10-30 13:49:06 +0000970 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000971 while (CurTok.isNot(tok::eom)) {
972 // Append the spelling of this token to the buffer. If there was a space
973 // before it, add it now.
974 if (CurTok.hasLeadingSpace())
975 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Chris Lattner141e71f2008-03-09 01:54:53 +0000977 // Get the spelling of the token, directly into FilenameBuffer if possible.
978 unsigned PreAppendSize = FilenameBuffer.size();
979 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Chris Lattner141e71f2008-03-09 01:54:53 +0000981 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +0000982 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Chris Lattner141e71f2008-03-09 01:54:53 +0000984 // If the token was spelled somewhere else, copy it into FilenameBuffer.
985 if (BufPtr != &FilenameBuffer[PreAppendSize])
986 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Chris Lattner141e71f2008-03-09 01:54:53 +0000988 // Resize FilenameBuffer to the correct size.
989 if (CurTok.getLength() != ActualLen)
990 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner141e71f2008-03-09 01:54:53 +0000992 // If we found the '>' marker, return success.
993 if (CurTok.is(tok::greater))
994 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000995
John Thompsona28cc092009-10-30 13:49:06 +0000996 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000997 }
998
999 // If we hit the eom marker, emit an error and return true so that the caller
1000 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001001 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001002 return true;
1003}
1004
1005/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1006/// file to be included from the lexer, then include it! This is a common
1007/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001008/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001009/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001010void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1011 const DirectoryLookup *LookupFrom,
1012 bool isImport) {
1013
1014 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001015 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattner141e71f2008-03-09 01:54:53 +00001017 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001018 llvm::SmallString<128> FilenameBuffer;
1019 llvm::StringRef Filename;
Chris Lattner141e71f2008-03-09 01:54:53 +00001020
1021 switch (FilenameTok.getKind()) {
1022 case tok::eom:
1023 // If the token kind is EOM, the error has already been diagnosed.
1024 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattner141e71f2008-03-09 01:54:53 +00001026 case tok::angle_string_literal:
1027 case tok::string_literal: {
1028 FilenameBuffer.resize(FilenameTok.getLength());
Chris Lattnera1394812010-01-10 01:35:12 +00001029 const char *FilenameStart = &FilenameBuffer[0];
Chris Lattner141e71f2008-03-09 01:54:53 +00001030 unsigned Len = getSpelling(FilenameTok, FilenameStart);
Chris Lattnera1394812010-01-10 01:35:12 +00001031 Filename = llvm::StringRef(FilenameStart, Len);
Chris Lattner141e71f2008-03-09 01:54:53 +00001032 break;
1033 }
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Chris Lattner141e71f2008-03-09 01:54:53 +00001035 case tok::less:
1036 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1037 // case, glue the tokens together into FilenameBuffer and interpret those.
1038 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001039 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001040 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001041 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001042 break;
1043 default:
1044 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1045 DiscardUntilEndOfDirective();
1046 return;
1047 }
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Chris Lattnera1394812010-01-10 01:35:12 +00001049 bool isAngled =
1050 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001051 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1052 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001053 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001054 DiscardUntilEndOfDirective();
1055 return;
1056 }
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001058 // Verify that there is nothing after the filename, other than EOM. Note that
1059 // we allow macros that expand to nothing after the filename, because this
1060 // falls into the category of "#include pp-tokens new-line" specified in
1061 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001062 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001063
1064 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001065 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1066 Diag(FilenameTok, diag::err_pp_include_too_deep);
1067 return;
1068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Chris Lattner141e71f2008-03-09 01:54:53 +00001070 // Search include directories.
1071 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +00001072 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001073 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001074 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001075 return;
1076 }
Chris Lattner804f6522010-01-10 00:24:58 +00001077
Chris Lattner72181832008-09-26 20:12:23 +00001078 // Ask HeaderInfo if we should enter this #include file. If not, #including
1079 // this file will have no effect.
1080 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001081 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Chris Lattner72181832008-09-26 20:12:23 +00001083 // The #included file will be considered to be a system header if either it is
1084 // in a system include directory, or if the #includer is a system include
1085 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001086 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001087 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001088 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Chris Lattner141e71f2008-03-09 01:54:53 +00001090 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001091 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1092 FileCharacter);
1093 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001094 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001095 return;
1096 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001097
1098 // Finally, if all is good, enter the new file!
Chris Lattner39d98412009-12-01 22:52:33 +00001099 std::string ErrorStr;
Daniel Dunbar63ceaa32009-12-06 09:19:12 +00001100 if (EnterSourceFile(FID, CurDir, ErrorStr))
Chris Lattner6e290142009-11-30 04:18:44 +00001101 Diag(FilenameTok, diag::err_pp_error_opening_file)
Chris Lattner39d98412009-12-01 22:52:33 +00001102 << std::string(SourceMgr.getFileEntryForID(FID)->getName()) << ErrorStr;
Chris Lattner141e71f2008-03-09 01:54:53 +00001103}
1104
1105/// HandleIncludeNextDirective - Implements #include_next.
1106///
1107void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1108 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Chris Lattner141e71f2008-03-09 01:54:53 +00001110 // #include_next is like #include, except that we start searching after
1111 // the current found directory. If we can't do this, issue a
1112 // diagnostic.
1113 const DirectoryLookup *Lookup = CurDirLookup;
1114 if (isInPrimaryFile()) {
1115 Lookup = 0;
1116 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1117 } else if (Lookup == 0) {
1118 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1119 } else {
1120 // Start looking up in the next directory.
1121 ++Lookup;
1122 }
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner141e71f2008-03-09 01:54:53 +00001124 return HandleIncludeDirective(IncludeNextTok, Lookup);
1125}
1126
1127/// HandleImportDirective - Implements #import.
1128///
1129void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001130 if (!Features.ObjC1) // #import is standard for ObjC.
1131 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Chris Lattner141e71f2008-03-09 01:54:53 +00001133 return HandleIncludeDirective(ImportTok, 0, true);
1134}
1135
Chris Lattnerde076652009-04-08 18:46:40 +00001136/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1137/// pseudo directive in the predefines buffer. This handles it by sucking all
1138/// tokens through the preprocessor and discarding them (only keeping the side
1139/// effects on the preprocessor).
1140void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1141 // This directive should only occur in the predefines buffer. If not, emit an
1142 // error and reject it.
1143 SourceLocation Loc = IncludeMacrosTok.getLocation();
1144 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1145 Diag(IncludeMacrosTok.getLocation(),
1146 diag::pp_include_macros_out_of_predefines);
1147 DiscardUntilEndOfDirective();
1148 return;
1149 }
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Chris Lattnerfd105112009-04-08 20:53:24 +00001151 // Treat this as a normal #include for checking purposes. If this is
1152 // successful, it will push a new lexer onto the include stack.
1153 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Chris Lattnerfd105112009-04-08 20:53:24 +00001155 Token TmpTok;
1156 do {
1157 Lex(TmpTok);
1158 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1159 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001160}
1161
Chris Lattner141e71f2008-03-09 01:54:53 +00001162//===----------------------------------------------------------------------===//
1163// Preprocessor Macro Directive Handling.
1164//===----------------------------------------------------------------------===//
1165
1166/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1167/// definition has just been read. Lex the rest of the arguments and the
1168/// closing ), updating MI with what we learn. Return true if an error occurs
1169/// parsing the arg list.
1170bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1171 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Chris Lattner141e71f2008-03-09 01:54:53 +00001173 Token Tok;
1174 while (1) {
1175 LexUnexpandedToken(Tok);
1176 switch (Tok.getKind()) {
1177 case tok::r_paren:
1178 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001179 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001180 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001181 // Otherwise we have #define FOO(A,)
1182 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1183 return true;
1184 case tok::ellipsis: // #define X(... -> C99 varargs
1185 // Warn if use of C99 feature in non-C99 mode.
1186 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1187
1188 // Lex the token after the identifier.
1189 LexUnexpandedToken(Tok);
1190 if (Tok.isNot(tok::r_paren)) {
1191 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1192 return true;
1193 }
1194 // Add the __VA_ARGS__ identifier as an argument.
1195 Arguments.push_back(Ident__VA_ARGS__);
1196 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001197 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001198 return false;
1199 case tok::eom: // #define X(
1200 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1201 return true;
1202 default:
1203 // Handle keywords and identifiers here to accept things like
1204 // #define Foo(for) for.
1205 IdentifierInfo *II = Tok.getIdentifierInfo();
1206 if (II == 0) {
1207 // #define X(1
1208 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1209 return true;
1210 }
1211
1212 // If this is already used as an argument, it is used multiple times (e.g.
1213 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001214 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001215 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001216 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001217 return true;
1218 }
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Chris Lattner141e71f2008-03-09 01:54:53 +00001220 // Add the argument to the macro info.
1221 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Chris Lattner141e71f2008-03-09 01:54:53 +00001223 // Lex the token after the identifier.
1224 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Chris Lattner141e71f2008-03-09 01:54:53 +00001226 switch (Tok.getKind()) {
1227 default: // #define X(A B
1228 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1229 return true;
1230 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001231 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001232 return false;
1233 case tok::comma: // #define X(A,
1234 break;
1235 case tok::ellipsis: // #define X(A... -> GCC extension
1236 // Diagnose extension.
1237 Diag(Tok, diag::ext_named_variadic_macro);
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);
1241 if (Tok.isNot(tok::r_paren)) {
1242 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1243 return true;
1244 }
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Chris Lattner141e71f2008-03-09 01:54:53 +00001246 MI->setIsGNUVarargs();
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 }
1250 }
1251 }
1252}
1253
1254/// HandleDefineDirective - Implements #define. This consumes the entire macro
1255/// line then lets the caller lex the next real token.
1256void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1257 ++NumDefined;
1258
1259 Token MacroNameTok;
1260 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Chris Lattner141e71f2008-03-09 01:54:53 +00001262 // Error reading macro name? If so, diagnostic already issued.
1263 if (MacroNameTok.is(tok::eom))
1264 return;
1265
Chris Lattner2451b522009-04-21 04:46:33 +00001266 Token LastTok = MacroNameTok;
1267
Chris Lattner141e71f2008-03-09 01:54:53 +00001268 // If we are supposed to keep comments in #defines, reenable comment saving
1269 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001270 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Chris Lattner141e71f2008-03-09 01:54:53 +00001272 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001273 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Chris Lattner141e71f2008-03-09 01:54:53 +00001275 Token Tok;
1276 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Chris Lattner141e71f2008-03-09 01:54:53 +00001278 // If this is a function-like macro definition, parse the argument list,
1279 // marking each of the identifiers as being used as macro arguments. Also,
1280 // check other constraints on the first token of the macro body.
1281 if (Tok.is(tok::eom)) {
1282 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001283 } else if (Tok.hasLeadingSpace()) {
1284 // This is a normal token with leading space. Clear the leading space
1285 // marker on the first token to get proper expansion.
1286 Tok.clearFlag(Token::LeadingSpace);
1287 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001288 // This is a function-like macro definition. Read the argument list.
1289 MI->setIsFunctionLike();
1290 if (ReadMacroDefinitionArgList(MI)) {
1291 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001292 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001293 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001294 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001295 DiscardUntilEndOfDirective();
1296 return;
1297 }
1298
Chris Lattner8fde5972009-04-19 18:26:34 +00001299 // If this is a definition of a variadic C99 function-like macro, not using
1300 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Chris Lattner8fde5972009-04-19 18:26:34 +00001302 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1303 // This gets unpoisoned where it is allowed.
1304 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1305 if (MI->isC99Varargs())
1306 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001307
Chris Lattner141e71f2008-03-09 01:54:53 +00001308 // 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 }
Chris Lattner2451b522009-04-21 04:46:33 +00001335
1336 if (!Tok.is(tok::eom))
1337 LastTok = Tok;
1338
Chris Lattner141e71f2008-03-09 01:54:53 +00001339 // Read the rest of the macro body.
1340 if (MI->isObjectLike()) {
1341 // Object-like macros are very simple, just read their body.
1342 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001343 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001344 MI->AddTokenToBody(Tok);
1345 // Get the next token of the macro.
1346 LexUnexpandedToken(Tok);
1347 }
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Chris Lattner141e71f2008-03-09 01:54:53 +00001349 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001350 // Otherwise, read the body of a function-like macro. While we are at it,
1351 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1352 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001353 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001354 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001355
Chris Lattner141e71f2008-03-09 01:54:53 +00001356 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001357 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Chris Lattner141e71f2008-03-09 01:54:53 +00001359 // Get the next token of the macro.
1360 LexUnexpandedToken(Tok);
1361 continue;
1362 }
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Chris Lattner141e71f2008-03-09 01:54:53 +00001364 // Get the next token of the macro.
1365 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Chris Lattner32404692009-05-25 17:16:10 +00001367 // Check for a valid macro arg identifier.
1368 if (Tok.getIdentifierInfo() == 0 ||
1369 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1370
1371 // If this is assembler-with-cpp mode, we accept random gibberish after
1372 // the '#' because '#' is often a comment character. However, change
1373 // the kind of the token to tok::unknown so that the preprocessor isn't
1374 // confused.
1375 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1376 LastTok.setKind(tok::unknown);
1377 } else {
1378 Diag(Tok, diag::err_pp_stringize_not_parameter);
1379 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Chris Lattner32404692009-05-25 17:16:10 +00001381 // Disable __VA_ARGS__ again.
1382 Ident__VA_ARGS__->setIsPoisoned(true);
1383 return;
1384 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001385 }
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Chris Lattner32404692009-05-25 17:16:10 +00001387 // Things look ok, add the '#' and param name tokens to the macro.
1388 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001389 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001390 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Chris Lattner141e71f2008-03-09 01:54:53 +00001392 // Get the next token of the macro.
1393 LexUnexpandedToken(Tok);
1394 }
1395 }
Mike Stump1eb44332009-09-09 15:08:12 +00001396
1397
Chris Lattner141e71f2008-03-09 01:54:53 +00001398 // Disable __VA_ARGS__ again.
1399 Ident__VA_ARGS__->setIsPoisoned(true);
1400
1401 // Check that there is no paste (##) operator at the begining or end of the
1402 // replacement list.
1403 unsigned NumTokens = MI->getNumTokens();
1404 if (NumTokens != 0) {
1405 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1406 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001407 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001408 return;
1409 }
1410 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1411 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001412 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001413 return;
1414 }
1415 }
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Chris Lattner141e71f2008-03-09 01:54:53 +00001417 // If this is the primary source file, remember that this macro hasn't been
1418 // used yet.
1419 if (isInPrimaryFile())
1420 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001421
1422 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Chris Lattner141e71f2008-03-09 01:54:53 +00001424 // Finally, if this identifier already had a macro defined for it, verify that
1425 // the macro bodies are identical and free the old definition.
1426 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001427 // It is very common for system headers to have tons of macro redefinitions
1428 // and for warnings to be disabled in system headers. If this is the case,
1429 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001430 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001431 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1432 if (!OtherMI->isUsed())
1433 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001434
Chris Lattner41c3ae12009-01-16 19:50:11 +00001435 // Macros must be identical. This means all tokes and whitespace
1436 // separation must be the same. C99 6.10.3.2.
1437 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1438 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1439 << MacroNameTok.getIdentifierInfo();
1440 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1441 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001442 }
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Ted Kremenek0ea76722008-12-15 19:56:42 +00001444 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001445 }
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Chris Lattner141e71f2008-03-09 01:54:53 +00001447 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001449 // If the callbacks want to know, tell them about the macro definition.
1450 if (Callbacks)
1451 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001452}
1453
1454/// HandleUndefDirective - Implements #undef.
1455///
1456void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1457 ++NumUndefined;
1458
1459 Token MacroNameTok;
1460 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Chris Lattner141e71f2008-03-09 01:54:53 +00001462 // Error reading macro name? If so, diagnostic already issued.
1463 if (MacroNameTok.is(tok::eom))
1464 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Chris Lattner141e71f2008-03-09 01:54:53 +00001466 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001467 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Chris Lattner141e71f2008-03-09 01:54:53 +00001469 // Okay, we finally have a valid identifier to undef.
1470 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Chris Lattner141e71f2008-03-09 01:54:53 +00001472 // If the macro is not defined, this is a noop undef, just return.
1473 if (MI == 0) return;
1474
1475 if (!MI->isUsed())
1476 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001477
1478 // If the callbacks want to know, tell them about the macro #undef.
1479 if (Callbacks)
1480 Callbacks->MacroUndefined(MacroNameTok.getIdentifierInfo(), MI);
1481
Chris Lattner141e71f2008-03-09 01:54:53 +00001482 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001483 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001484 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1485}
1486
1487
1488//===----------------------------------------------------------------------===//
1489// Preprocessor Conditional Directive Handling.
1490//===----------------------------------------------------------------------===//
1491
1492/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1493/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1494/// if any tokens have been returned or pp-directives activated before this
1495/// #ifndef has been lexed.
1496///
1497void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1498 bool ReadAnyTokensBeforeDirective) {
1499 ++NumIf;
1500 Token DirectiveTok = Result;
1501
1502 Token MacroNameTok;
1503 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Chris Lattner141e71f2008-03-09 01:54:53 +00001505 // Error reading macro name? If so, diagnostic already issued.
1506 if (MacroNameTok.is(tok::eom)) {
1507 // Skip code until we get to #endif. This helps with recovery by not
1508 // emitting an error when the #endif is reached.
1509 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1510 /*Foundnonskip*/false, /*FoundElse*/false);
1511 return;
1512 }
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Chris Lattner141e71f2008-03-09 01:54:53 +00001514 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001515 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001516
Ted Kremenek60e45d42008-11-18 00:34:22 +00001517 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001518 // If the start of a top-level #ifdef, inform MIOpt.
1519 if (!ReadAnyTokensBeforeDirective) {
1520 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001521 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001522 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001523 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001524 }
1525
1526 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1527 MacroInfo *MI = getMacroInfo(MII);
1528
1529 // If there is a macro, process it.
1530 if (MI) // Mark it used.
1531 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Chris Lattner141e71f2008-03-09 01:54:53 +00001533 // Should we include the stuff contained by this directive?
1534 if (!MI == isIfndef) {
1535 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001536 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1537 /*wasskip*/false, /*foundnonskip*/true,
1538 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001539 } else {
1540 // No, skip the contents of this block and return the first token after it.
1541 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001542 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001543 /*FoundElse*/false);
1544 }
1545}
1546
1547/// HandleIfDirective - Implements the #if directive.
1548///
1549void Preprocessor::HandleIfDirective(Token &IfToken,
1550 bool ReadAnyTokensBeforeDirective) {
1551 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Chris Lattner141e71f2008-03-09 01:54:53 +00001553 // Parse and evaluation the conditional expression.
1554 IdentifierInfo *IfNDefMacro = 0;
1555 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Nuno Lopes0049db62008-06-01 18:31:24 +00001557
1558 // If this condition is equivalent to #ifndef X, and if this is the first
1559 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001560 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001561 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001562 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001563 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001564 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001565 }
1566
Chris Lattner141e71f2008-03-09 01:54:53 +00001567 // Should we include the stuff contained by this directive?
1568 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001569 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001570 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001571 /*foundnonskip*/true, /*foundelse*/false);
1572 } else {
1573 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001574 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001575 /*FoundElse*/false);
1576 }
1577}
1578
1579/// HandleEndifDirective - Implements the #endif directive.
1580///
1581void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1582 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Chris Lattner141e71f2008-03-09 01:54:53 +00001584 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001585 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Chris Lattner141e71f2008-03-09 01:54:53 +00001587 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001588 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001589 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001590 Diag(EndifToken, diag::err_pp_endif_without_if);
1591 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001592 }
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Chris Lattner141e71f2008-03-09 01:54:53 +00001594 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001595 if (CurPPLexer->getConditionalStackDepth() == 0)
1596 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Ted Kremenek60e45d42008-11-18 00:34:22 +00001598 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001599 "This code should only be reachable in the non-skipping case!");
1600}
1601
1602
1603void Preprocessor::HandleElseDirective(Token &Result) {
1604 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Chris Lattner141e71f2008-03-09 01:54:53 +00001606 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001607 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Chris Lattner141e71f2008-03-09 01:54:53 +00001609 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001610 if (CurPPLexer->popConditionalLevel(CI)) {
1611 Diag(Result, diag::pp_err_else_without_if);
1612 return;
1613 }
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Chris Lattner141e71f2008-03-09 01:54:53 +00001615 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001616 if (CurPPLexer->getConditionalStackDepth() == 0)
1617 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001618
1619 // If this is a #else with a #else before it, report the error.
1620 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Chris Lattner141e71f2008-03-09 01:54:53 +00001622 // Finally, skip the rest of the contents of this block and return the first
1623 // token after it.
1624 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1625 /*FoundElse*/true);
1626}
1627
1628void Preprocessor::HandleElifDirective(Token &ElifToken) {
1629 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Chris Lattner141e71f2008-03-09 01:54:53 +00001631 // #elif directive in a non-skipping conditional... start skipping.
1632 // We don't care what the condition is, because we will always skip it (since
1633 // the block immediately before it was included).
1634 DiscardUntilEndOfDirective();
1635
1636 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001637 if (CurPPLexer->popConditionalLevel(CI)) {
1638 Diag(ElifToken, diag::pp_err_elif_without_if);
1639 return;
1640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Chris Lattner141e71f2008-03-09 01:54:53 +00001642 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001643 if (CurPPLexer->getConditionalStackDepth() == 0)
1644 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Chris Lattner141e71f2008-03-09 01:54:53 +00001646 // If this is a #elif with a #else before it, report the error.
1647 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1648
1649 // Finally, skip the rest of the contents of this block and return the first
1650 // token after it.
1651 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1652 /*FoundElse*/CI.FoundElse);
1653}
1654