blob: 3bf3fc4af9173f9b8decdb4dbf80182a7d18751a [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.
Douglas Gregora5430162010-03-16 20:46:42 +0000207 bool Invalid = false;
208 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation(),
209 &Invalid);
210 if (Invalid)
211 return;
212
Chris Lattner141e71f2008-03-09 01:54:53 +0000213 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000214 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000215 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000216 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000217 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000218 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000219 continue;
220 }
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Chris Lattner141e71f2008-03-09 01:54:53 +0000222 // Get the identifier name without trigraphs or embedded newlines. Note
223 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
224 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000225 char DirectiveBuf[20];
226 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000227 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000228 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000229 } else {
230 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000231 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000232 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000233 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000234 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000235 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000236 continue;
237 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000238 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
239 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000240 }
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000242 if (Directive.startswith("if")) {
243 llvm::StringRef Sub = Directive.substr(2);
244 if (Sub.empty() || // "if"
245 Sub == "def" || // "ifdef"
246 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000247 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
248 // bother parsing the condition.
249 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000250 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000251 /*foundnonskip*/false,
252 /*fnddelse*/false);
253 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000254 } else if (Directive[0] == 'e') {
255 llvm::StringRef Sub = Directive.substr(1);
256 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000257 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000258 PPConditionalInfo CondInfo;
259 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000260 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000261 InCond = InCond; // Silence warning in no-asserts mode.
262 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattner141e71f2008-03-09 01:54:53 +0000264 // If we popped the outermost skipping block, we're done skipping!
265 if (!CondInfo.WasSkipping)
266 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000267 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000268 // #else directive in a skipping conditional. If not in some other
269 // skipping conditional, and if #else hasn't already been seen, enter it
270 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000271 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000272 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattner141e71f2008-03-09 01:54:53 +0000274 // If this is a #else with a #else before it, report the error.
275 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Chris Lattner141e71f2008-03-09 01:54:53 +0000277 // Note that we've seen a #else in this conditional.
278 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattner141e71f2008-03-09 01:54:53 +0000280 // If the conditional is at the top level, and the #if block wasn't
281 // entered, enter the #else block now.
282 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
283 CondInfo.FoundNonSkip = true;
284 break;
285 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000286 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000287 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000288
289 bool ShouldEnter;
290 // If this is in a skipping block or if we're already handled this #if
291 // block, don't bother parsing the condition.
292 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
293 DiscardUntilEndOfDirective();
294 ShouldEnter = false;
295 } else {
296 // Restore the value of LexingRawMode so that identifiers are
297 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000298 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
299 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000300 IdentifierInfo *IfNDefMacro = 0;
301 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000302 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 }
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Chris Lattner141e71f2008-03-09 01:54:53 +0000305 // If this is a #elif with a #else before it, report the error.
306 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Chris Lattner141e71f2008-03-09 01:54:53 +0000308 // If this condition is true, enter it!
309 if (ShouldEnter) {
310 CondInfo.FoundNonSkip = true;
311 break;
312 }
313 }
314 }
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Ted Kremenek60e45d42008-11-18 00:34:22 +0000316 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000317 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000318 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000319 }
320
321 // Finally, if we are out of the conditional (saw an #endif or ran off the end
322 // of the file, just stop skipping and return to lexing whatever came after
323 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000324 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000325}
326
Ted Kremenek268ee702008-12-12 18:34:08 +0000327void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000328
329 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000330 assert(CurPTHLexer);
331 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Ted Kremenek268ee702008-12-12 18:34:08 +0000333 // Skip to the next '#else', '#elif', or #endif.
334 if (CurPTHLexer->SkipBlock()) {
335 // We have reached an #endif. Both the '#' and 'endif' tokens
336 // have been consumed by the PTHLexer. Just pop off the condition level.
337 PPConditionalInfo CondInfo;
338 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
339 InCond = InCond; // Silence warning in no-asserts mode.
340 assert(!InCond && "Can't be skipping if not in a conditional!");
341 break;
342 }
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Ted Kremenek268ee702008-12-12 18:34:08 +0000344 // We have reached a '#else' or '#elif'. Lex the next token to get
345 // the directive flavor.
346 Token Tok;
347 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Ted Kremenek268ee702008-12-12 18:34:08 +0000349 // We can actually look up the IdentifierInfo here since we aren't in
350 // raw mode.
351 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
352
353 if (K == tok::pp_else) {
354 // #else: Enter the else condition. We aren't in a nested condition
355 // since we skip those. We're always in the one matching the last
356 // blocked we skipped.
357 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
358 // Note that we've seen a #else in this conditional.
359 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Ted Kremenek268ee702008-12-12 18:34:08 +0000361 // If the #if block wasn't entered then enter the #else block now.
362 if (!CondInfo.FoundNonSkip) {
363 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000365 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000366 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000367 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000368 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Ted Kremenek268ee702008-12-12 18:34:08 +0000370 break;
371 }
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Ted Kremenek268ee702008-12-12 18:34:08 +0000373 // Otherwise skip this block.
374 continue;
375 }
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Ted Kremenek268ee702008-12-12 18:34:08 +0000377 assert(K == tok::pp_elif);
378 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
379
380 // If this is a #elif with a #else before it, report the error.
381 if (CondInfo.FoundElse)
382 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Ted Kremenek268ee702008-12-12 18:34:08 +0000384 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000385 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000386 if (CondInfo.FoundNonSkip)
387 continue;
388
389 // Evaluate the condition of the #elif.
390 IdentifierInfo *IfNDefMacro = 0;
391 CurPTHLexer->ParsingPreprocessorDirective = true;
392 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
393 CurPTHLexer->ParsingPreprocessorDirective = false;
394
395 // If this condition is true, enter it!
396 if (ShouldEnter) {
397 CondInfo.FoundNonSkip = true;
398 break;
399 }
400
401 // Otherwise, skip this block and go to the next one.
402 continue;
403 }
404}
405
Chris Lattner10725092008-03-09 04:17:44 +0000406/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
407/// return null on failure. isAngled indicates whether the file reference is
408/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnera1394812010-01-10 01:35:12 +0000409const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattner10725092008-03-09 04:17:44 +0000410 bool isAngled,
411 const DirectoryLookup *FromDir,
412 const DirectoryLookup *&CurDir) {
413 // If the header lookup mechanism may be relative to the current file, pass in
414 // info about where the current file is.
415 const FileEntry *CurFileEnt = 0;
416 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000417 FileID FID = getCurrentFileLexer()->getFileID();
418 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000420 // If there is no file entry associated with this file, it must be the
421 // predefines buffer. Any other file is not lexed with a normal lexer, so
422 // it won't be scanned for preprocessor directives. If we have the
423 // predefines buffer, resolve #include references (which come from the
424 // -include command line argument) as if they came from the main file, this
425 // affects file lookup etc.
426 if (CurFileEnt == 0) {
427 FID = SourceMgr.getMainFileID();
428 CurFileEnt = SourceMgr.getFileEntryForID(FID);
429 }
Chris Lattner10725092008-03-09 04:17:44 +0000430 }
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Chris Lattner10725092008-03-09 04:17:44 +0000432 // Do a standard file entry lookup.
433 CurDir = CurDirLookup;
434 const FileEntry *FE =
Chris Lattnera1394812010-01-10 01:35:12 +0000435 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000436 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattner10725092008-03-09 04:17:44 +0000438 // Otherwise, see if this is a subframework header. If so, this is relative
439 // to one of the headers on the #include stack. Walk the list of the current
440 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000441 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000442 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000443 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000444 return FE;
445 }
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Chris Lattner10725092008-03-09 04:17:44 +0000447 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
448 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000449 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000450 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000451 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000452 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000453 return FE;
454 }
455 }
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Chris Lattner10725092008-03-09 04:17:44 +0000457 // Otherwise, we really couldn't find the file.
458 return 0;
459}
460
Chris Lattner141e71f2008-03-09 01:54:53 +0000461
462//===----------------------------------------------------------------------===//
463// Preprocessor Directive Handling.
464//===----------------------------------------------------------------------===//
465
466/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000467/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000468/// lexer/preprocessor state, and advances the lexer(s) so that the next token
469/// read is the correct one.
470void Preprocessor::HandleDirective(Token &Result) {
471 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Chris Lattner141e71f2008-03-09 01:54:53 +0000473 // We just parsed a # character at the start of a line, so we're in directive
474 // mode. Tell the lexer this so any newlines we see will be converted into an
475 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000476 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Chris Lattner141e71f2008-03-09 01:54:53 +0000478 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000479
Chris Lattner141e71f2008-03-09 01:54:53 +0000480 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000481 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000482 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000483 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattner42aa16c2009-03-18 21:00:25 +0000485 // Save the '#' token in case we need to return it later.
486 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Chris Lattner141e71f2008-03-09 01:54:53 +0000488 // Read the next token, the directive flavor. This isn't expanded due to
489 // C99 6.10.3p8.
490 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Chris Lattner141e71f2008-03-09 01:54:53 +0000492 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
493 // #define A(x) #x
494 // A(abc
495 // #warning blah
496 // def)
497 // If so, the user is relying on non-portable behavior, emit a diagnostic.
498 if (InMacroArgs)
499 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Chris Lattner141e71f2008-03-09 01:54:53 +0000501TryAgain:
502 switch (Result.getKind()) {
503 case tok::eom:
504 return; // null directive.
505 case tok::comment:
506 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
507 LexUnexpandedToken(Result);
508 goto TryAgain;
509
Chris Lattner478a18e2009-01-26 06:19:46 +0000510 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000511 if (getLangOptions().AsmPreprocessor)
512 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000513 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000514 default:
515 IdentifierInfo *II = Result.getIdentifierInfo();
516 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Chris Lattner141e71f2008-03-09 01:54:53 +0000518 // Ask what the preprocessor keyword ID is.
519 switch (II->getPPKeywordID()) {
520 default: break;
521 // C99 6.10.1 - Conditional Inclusion.
522 case tok::pp_if:
523 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
524 case tok::pp_ifdef:
525 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
526 case tok::pp_ifndef:
527 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
528 case tok::pp_elif:
529 return HandleElifDirective(Result);
530 case tok::pp_else:
531 return HandleElseDirective(Result);
532 case tok::pp_endif:
533 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Chris Lattner141e71f2008-03-09 01:54:53 +0000535 // C99 6.10.2 - Source File Inclusion.
536 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000537 return HandleIncludeDirective(Result); // Handle #include.
538 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000539 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Chris Lattner141e71f2008-03-09 01:54:53 +0000541 // C99 6.10.3 - Macro Replacement.
542 case tok::pp_define:
543 return HandleDefineDirective(Result);
544 case tok::pp_undef:
545 return HandleUndefDirective(Result);
546
547 // C99 6.10.4 - Line Control.
548 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000549 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Chris Lattner141e71f2008-03-09 01:54:53 +0000551 // C99 6.10.5 - Error Directive.
552 case tok::pp_error:
553 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Chris Lattner141e71f2008-03-09 01:54:53 +0000555 // C99 6.10.6 - Pragma Directive.
556 case tok::pp_pragma:
557 return HandlePragmaDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattner141e71f2008-03-09 01:54:53 +0000559 // GNU Extensions.
560 case tok::pp_import:
561 return HandleImportDirective(Result);
562 case tok::pp_include_next:
563 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Chris Lattner141e71f2008-03-09 01:54:53 +0000565 case tok::pp_warning:
566 Diag(Result, diag::ext_pp_warning_directive);
567 return HandleUserDiagnosticDirective(Result, true);
568 case tok::pp_ident:
569 return HandleIdentSCCSDirective(Result);
570 case tok::pp_sccs:
571 return HandleIdentSCCSDirective(Result);
572 case tok::pp_assert:
573 //isExtension = true; // FIXME: implement #assert
574 break;
575 case tok::pp_unassert:
576 //isExtension = true; // FIXME: implement #unassert
577 break;
578 }
579 break;
580 }
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Chris Lattner42aa16c2009-03-18 21:00:25 +0000582 // If this is a .S file, treat unknown # directives as non-preprocessor
583 // directives. This is important because # may be a comment or introduce
584 // various pseudo-ops. Just return the # token and push back the following
585 // token to be lexed next time.
586 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000587 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000588 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000589 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000590 Toks[1] = Result;
591 // Enter this token stream so that we re-lex the tokens. Make sure to
592 // enable macro expansion, in case the token after the # is an identifier
593 // that is expanded.
594 EnterTokenStream(Toks, 2, false, true);
595 return;
596 }
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Chris Lattner141e71f2008-03-09 01:54:53 +0000598 // If we reached here, the preprocessing token is not valid!
599 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Chris Lattner141e71f2008-03-09 01:54:53 +0000601 // Read the rest of the PP line.
602 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Chris Lattner141e71f2008-03-09 01:54:53 +0000604 // Okay, we're done parsing the directive.
605}
606
Chris Lattner478a18e2009-01-26 06:19:46 +0000607/// GetLineValue - Convert a numeric token into an unsigned value, emitting
608/// Diagnostic DiagID if it is invalid, and returning the value in Val.
609static bool GetLineValue(Token &DigitTok, unsigned &Val,
610 unsigned DiagID, Preprocessor &PP) {
611 if (DigitTok.isNot(tok::numeric_constant)) {
612 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Chris Lattner478a18e2009-01-26 06:19:46 +0000614 if (DigitTok.isNot(tok::eom))
615 PP.DiscardUntilEndOfDirective();
616 return true;
617 }
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Chris Lattner478a18e2009-01-26 06:19:46 +0000619 llvm::SmallString<64> IntegerBuffer;
620 IntegerBuffer.resize(DigitTok.getLength());
621 const char *DigitTokBegin = &IntegerBuffer[0];
622 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000624 // Verify that we have a simple digit-sequence, and compute the value. This
625 // is always a simple digit string computed in decimal, so we do this manually
626 // here.
627 Val = 0;
628 for (unsigned i = 0; i != ActualLength; ++i) {
629 if (!isdigit(DigitTokBegin[i])) {
630 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
631 diag::err_pp_line_digit_sequence);
632 PP.DiscardUntilEndOfDirective();
633 return true;
634 }
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000636 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
637 if (NextVal < Val) { // overflow.
638 PP.Diag(DigitTok, DiagID);
639 PP.DiscardUntilEndOfDirective();
640 return true;
641 }
642 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000643 }
Mike Stump1eb44332009-09-09 15:08:12 +0000644
645 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000646 if (Val == 0) {
647 PP.Diag(DigitTok, DiagID);
648 PP.DiscardUntilEndOfDirective();
649 return true;
650 }
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000652 if (DigitTokBegin[0] == '0')
653 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Chris Lattner478a18e2009-01-26 06:19:46 +0000655 return false;
656}
657
Mike Stump1eb44332009-09-09 15:08:12 +0000658/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000659/// acceptable forms are:
660/// # line digit-sequence
661/// # line digit-sequence "s-char-sequence"
662void Preprocessor::HandleLineDirective(Token &Tok) {
663 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
664 // expanded.
665 Token DigitTok;
666 Lex(DigitTok);
667
Chris Lattner359cc442009-01-26 05:29:08 +0000668 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000669 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000670 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000671 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000672
Chris Lattner478a18e2009-01-26 06:19:46 +0000673 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
674 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000675 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
676 if (LineNo >= LineLimit)
677 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Chris Lattner5b9a5042009-01-26 07:57:50 +0000679 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000680 Token StrTok;
681 Lex(StrTok);
682
683 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
684 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000685 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000686 ; // ok
687 else if (StrTok.isNot(tok::string_literal)) {
688 Diag(StrTok, diag::err_pp_line_invalid_filename);
689 DiscardUntilEndOfDirective();
690 return;
691 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000692 // Parse and validate the string, converting it into a unique ID.
693 StringLiteralParser Literal(&StrTok, 1, *this);
694 assert(!Literal.AnyWide && "Didn't allow wide strings in");
695 if (Literal.hadError)
696 return DiscardUntilEndOfDirective();
697 if (Literal.Pascal) {
698 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
699 return DiscardUntilEndOfDirective();
700 }
701 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
702 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Chris Lattnerab82f412009-04-17 23:30:53 +0000704 // Verify that there is nothing after the string, other than EOM. Because
705 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
706 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000707 }
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattner4c4ea172009-02-03 21:52:55 +0000709 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Chris Lattner16629382009-03-27 17:13:49 +0000711 if (Callbacks)
712 Callbacks->FileChanged(DigitTok.getLocation(), PPCallbacks::RenameFile,
713 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000714}
715
Chris Lattner478a18e2009-01-26 06:19:46 +0000716/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
717/// marker directive.
718static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
719 bool &IsSystemHeader, bool &IsExternCHeader,
720 Preprocessor &PP) {
721 unsigned FlagVal;
722 Token FlagTok;
723 PP.Lex(FlagTok);
724 if (FlagTok.is(tok::eom)) return false;
725 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
726 return true;
727
728 if (FlagVal == 1) {
729 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Chris Lattner478a18e2009-01-26 06:19:46 +0000731 PP.Lex(FlagTok);
732 if (FlagTok.is(tok::eom)) return false;
733 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
734 return true;
735 } else if (FlagVal == 2) {
736 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattner137b6a62009-02-04 06:25:26 +0000738 SourceManager &SM = PP.getSourceManager();
739 // If we are leaving the current presumed file, check to make sure the
740 // presumed include stack isn't empty!
741 FileID CurFileID =
742 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
743 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Chris Lattner137b6a62009-02-04 06:25:26 +0000745 // If there is no include loc (main file) or if the include loc is in a
746 // different physical file, then we aren't in a "1" line marker flag region.
747 SourceLocation IncLoc = PLoc.getIncludeLoc();
748 if (IncLoc.isInvalid() ||
749 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
750 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
751 PP.DiscardUntilEndOfDirective();
752 return true;
753 }
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Chris Lattner478a18e2009-01-26 06:19:46 +0000755 PP.Lex(FlagTok);
756 if (FlagTok.is(tok::eom)) return false;
757 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
758 return true;
759 }
760
761 // We must have 3 if there are still flags.
762 if (FlagVal != 3) {
763 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000764 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000765 return true;
766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Chris Lattner478a18e2009-01-26 06:19:46 +0000768 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattner478a18e2009-01-26 06:19:46 +0000770 PP.Lex(FlagTok);
771 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000772 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000773 return true;
774
775 // We must have 4 if there is yet another flag.
776 if (FlagVal != 4) {
777 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000778 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000779 return true;
780 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Chris Lattner478a18e2009-01-26 06:19:46 +0000782 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Chris Lattner478a18e2009-01-26 06:19:46 +0000784 PP.Lex(FlagTok);
785 if (FlagTok.is(tok::eom)) return false;
786
787 // There are no more valid flags here.
788 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000789 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000790 return true;
791}
792
793/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
794/// one of the following forms:
795///
796/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000797/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000798/// # 42 "file" ('1' | '2')? '3' '4'?
799///
800void Preprocessor::HandleDigitDirective(Token &DigitTok) {
801 // Validate the number and convert it to an unsigned. GNU does not have a
802 // line # limit other than it fit in 32-bits.
803 unsigned LineNo;
804 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
805 *this))
806 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Chris Lattner478a18e2009-01-26 06:19:46 +0000808 Token StrTok;
809 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Chris Lattner478a18e2009-01-26 06:19:46 +0000811 bool IsFileEntry = false, IsFileExit = false;
812 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000813 int FilenameID = -1;
814
Chris Lattner478a18e2009-01-26 06:19:46 +0000815 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
816 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000817 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000818 ; // ok
819 else if (StrTok.isNot(tok::string_literal)) {
820 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000821 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000822 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000823 // Parse and validate the string, converting it into a unique ID.
824 StringLiteralParser Literal(&StrTok, 1, *this);
825 assert(!Literal.AnyWide && "Didn't allow wide strings in");
826 if (Literal.hadError)
827 return DiscardUntilEndOfDirective();
828 if (Literal.Pascal) {
829 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
830 return DiscardUntilEndOfDirective();
831 }
832 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
833 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Chris Lattner478a18e2009-01-26 06:19:46 +0000835 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000836 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000837 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000838 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000839 }
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Chris Lattner9d79eba2009-02-04 05:21:58 +0000841 // Create a line note with this information.
842 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000843 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000844 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Chris Lattner16629382009-03-27 17:13:49 +0000846 // If the preprocessor has callbacks installed, notify them of the #line
847 // change. This is used so that the line marker comes out in -E mode for
848 // example.
849 if (Callbacks) {
850 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
851 if (IsFileEntry)
852 Reason = PPCallbacks::EnterFile;
853 else if (IsFileExit)
854 Reason = PPCallbacks::ExitFile;
855 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
856 if (IsExternCHeader)
857 FileKind = SrcMgr::C_ExternCSystem;
858 else if (IsSystemHeader)
859 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Chris Lattner16629382009-03-27 17:13:49 +0000861 Callbacks->FileChanged(DigitTok.getLocation(), Reason, FileKind);
862 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000863}
864
865
Chris Lattner099dd052009-01-26 05:30:54 +0000866/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
867///
Mike Stump1eb44332009-09-09 15:08:12 +0000868void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000869 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000870 // PTH doesn't emit #warning or #error directives.
871 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000872 return CurPTHLexer->DiscardToEndOfLine();
873
Chris Lattner141e71f2008-03-09 01:54:53 +0000874 // Read the rest of the line raw. We do this because we don't want macros
875 // to be expanded and we don't require that the tokens be valid preprocessing
876 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
877 // collapse multiple consequtive white space between tokens, but this isn't
878 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000879 std::string Message = CurLexer->ReadToEndOfLine();
880 if (isWarning)
881 Diag(Tok, diag::pp_hash_warning) << Message;
882 else
883 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000884}
885
886/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
887///
888void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
889 // Yes, this directive is an extension.
890 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Chris Lattner141e71f2008-03-09 01:54:53 +0000892 // Read the string argument.
893 Token StrTok;
894 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner141e71f2008-03-09 01:54:53 +0000896 // If the token kind isn't a string, it's a malformed directive.
897 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000898 StrTok.isNot(tok::wide_string_literal)) {
899 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000900 if (StrTok.isNot(tok::eom))
901 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000902 return;
903 }
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Chris Lattner141e71f2008-03-09 01:54:53 +0000905 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000906 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000907
908 if (Callbacks)
909 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
910}
911
912//===----------------------------------------------------------------------===//
913// Preprocessor Include Directive Handling.
914//===----------------------------------------------------------------------===//
915
916/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
917/// checked and spelled filename, e.g. as an operand of #include. This returns
918/// true if the input filename was in <>'s or false if it were in ""'s. The
919/// caller is expected to provide a buffer that is large enough to hold the
920/// spelling of the filename, but is also expected to handle the case when
921/// this method decides to use a different buffer.
922bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000923 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000924 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000925 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Chris Lattner141e71f2008-03-09 01:54:53 +0000927 // Make sure the filename is <x> or "x".
928 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000929 if (Buffer[0] == '<') {
930 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000931 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000932 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000933 return true;
934 }
935 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +0000936 } else if (Buffer[0] == '"') {
937 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000938 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000939 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000940 return true;
941 }
942 isAngled = false;
943 } else {
944 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000945 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000946 return true;
947 }
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Chris Lattner141e71f2008-03-09 01:54:53 +0000949 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +0000950 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000951 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000952 Buffer = llvm::StringRef();
953 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000954 }
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Chris Lattner141e71f2008-03-09 01:54:53 +0000956 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +0000957 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +0000958 return isAngled;
959}
960
961/// ConcatenateIncludeName - Handle cases where the #include name is expanded
962/// from a macro as multiple tokens, which need to be glued together. This
963/// occurs for code like:
964/// #define FOO <a/b.h>
965/// #include FOO
966/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
967///
968/// This code concatenates and consumes tokens up to the '>' token. It returns
969/// false if the > was found, otherwise it returns true if it finds and consumes
970/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +0000971bool Preprocessor::ConcatenateIncludeName(
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000972 llvm::SmallString<128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000973 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +0000974
John Thompsona28cc092009-10-30 13:49:06 +0000975 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000976 while (CurTok.isNot(tok::eom)) {
977 // Append the spelling of this token to the buffer. If there was a space
978 // before it, add it now.
979 if (CurTok.hasLeadingSpace())
980 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Chris Lattner141e71f2008-03-09 01:54:53 +0000982 // Get the spelling of the token, directly into FilenameBuffer if possible.
983 unsigned PreAppendSize = FilenameBuffer.size();
984 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Chris Lattner141e71f2008-03-09 01:54:53 +0000986 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +0000987 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Chris Lattner141e71f2008-03-09 01:54:53 +0000989 // If the token was spelled somewhere else, copy it into FilenameBuffer.
990 if (BufPtr != &FilenameBuffer[PreAppendSize])
991 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Chris Lattner141e71f2008-03-09 01:54:53 +0000993 // Resize FilenameBuffer to the correct size.
994 if (CurTok.getLength() != ActualLen)
995 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Chris Lattner141e71f2008-03-09 01:54:53 +0000997 // If we found the '>' marker, return success.
998 if (CurTok.is(tok::greater))
999 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001000
John Thompsona28cc092009-10-30 13:49:06 +00001001 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001002 }
1003
1004 // If we hit the eom marker, emit an error and return true so that the caller
1005 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001006 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001007 return true;
1008}
1009
1010/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1011/// file to be included from the lexer, then include it! This is a common
1012/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001013/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001014/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001015void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1016 const DirectoryLookup *LookupFrom,
1017 bool isImport) {
1018
1019 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001020 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Chris Lattner141e71f2008-03-09 01:54:53 +00001022 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001023 llvm::SmallString<128> FilenameBuffer;
1024 llvm::StringRef Filename;
Chris Lattner141e71f2008-03-09 01:54:53 +00001025
1026 switch (FilenameTok.getKind()) {
1027 case tok::eom:
1028 // If the token kind is EOM, the error has already been diagnosed.
1029 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Chris Lattner141e71f2008-03-09 01:54:53 +00001031 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001032 case tok::string_literal:
1033 Filename = getSpelling(FilenameTok, FilenameBuffer);
Chris Lattner141e71f2008-03-09 01:54:53 +00001034 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Chris Lattner141e71f2008-03-09 01:54:53 +00001036 case tok::less:
1037 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1038 // case, glue the tokens together into FilenameBuffer and interpret those.
1039 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001040 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001041 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001042 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001043 break;
1044 default:
1045 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1046 DiscardUntilEndOfDirective();
1047 return;
1048 }
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001050 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001051 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001052 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1053 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001054 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001055 DiscardUntilEndOfDirective();
1056 return;
1057 }
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001059 // Verify that there is nothing after the filename, other than EOM. Note that
1060 // we allow macros that expand to nothing after the filename, because this
1061 // falls into the category of "#include pp-tokens new-line" specified in
1062 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001063 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001064
1065 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001066 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1067 Diag(FilenameTok, diag::err_pp_include_too_deep);
1068 return;
1069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattner141e71f2008-03-09 01:54:53 +00001071 // Search include directories.
1072 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +00001073 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001074 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001075 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001076 return;
1077 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001078
Chris Lattner72181832008-09-26 20:12:23 +00001079 // Ask HeaderInfo if we should enter this #include file. If not, #including
1080 // this file will have no effect.
1081 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001082 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Chris Lattner72181832008-09-26 20:12:23 +00001084 // The #included file will be considered to be a system header if either it is
1085 // in a system include directory, or if the #includer is a system include
1086 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001087 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001088 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001089 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Chris Lattner141e71f2008-03-09 01:54:53 +00001091 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001092 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1093 FileCharacter);
1094 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001095 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001096 return;
1097 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001098
1099 // Finally, if all is good, enter the new file!
Chris Lattner39d98412009-12-01 22:52:33 +00001100 std::string ErrorStr;
Daniel Dunbar63ceaa32009-12-06 09:19:12 +00001101 if (EnterSourceFile(FID, CurDir, ErrorStr))
Chris Lattner6e290142009-11-30 04:18:44 +00001102 Diag(FilenameTok, diag::err_pp_error_opening_file)
Chris Lattner39d98412009-12-01 22:52:33 +00001103 << std::string(SourceMgr.getFileEntryForID(FID)->getName()) << ErrorStr;
Chris Lattner141e71f2008-03-09 01:54:53 +00001104}
1105
1106/// HandleIncludeNextDirective - Implements #include_next.
1107///
1108void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1109 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Chris Lattner141e71f2008-03-09 01:54:53 +00001111 // #include_next is like #include, except that we start searching after
1112 // the current found directory. If we can't do this, issue a
1113 // diagnostic.
1114 const DirectoryLookup *Lookup = CurDirLookup;
1115 if (isInPrimaryFile()) {
1116 Lookup = 0;
1117 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1118 } else if (Lookup == 0) {
1119 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1120 } else {
1121 // Start looking up in the next directory.
1122 ++Lookup;
1123 }
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Chris Lattner141e71f2008-03-09 01:54:53 +00001125 return HandleIncludeDirective(IncludeNextTok, Lookup);
1126}
1127
1128/// HandleImportDirective - Implements #import.
1129///
1130void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001131 if (!Features.ObjC1) // #import is standard for ObjC.
1132 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Chris Lattner141e71f2008-03-09 01:54:53 +00001134 return HandleIncludeDirective(ImportTok, 0, true);
1135}
1136
Chris Lattnerde076652009-04-08 18:46:40 +00001137/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1138/// pseudo directive in the predefines buffer. This handles it by sucking all
1139/// tokens through the preprocessor and discarding them (only keeping the side
1140/// effects on the preprocessor).
1141void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1142 // This directive should only occur in the predefines buffer. If not, emit an
1143 // error and reject it.
1144 SourceLocation Loc = IncludeMacrosTok.getLocation();
1145 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1146 Diag(IncludeMacrosTok.getLocation(),
1147 diag::pp_include_macros_out_of_predefines);
1148 DiscardUntilEndOfDirective();
1149 return;
1150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Chris Lattnerfd105112009-04-08 20:53:24 +00001152 // Treat this as a normal #include for checking purposes. If this is
1153 // successful, it will push a new lexer onto the include stack.
1154 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Chris Lattnerfd105112009-04-08 20:53:24 +00001156 Token TmpTok;
1157 do {
1158 Lex(TmpTok);
1159 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1160 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001161}
1162
Chris Lattner141e71f2008-03-09 01:54:53 +00001163//===----------------------------------------------------------------------===//
1164// Preprocessor Macro Directive Handling.
1165//===----------------------------------------------------------------------===//
1166
1167/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1168/// definition has just been read. Lex the rest of the arguments and the
1169/// closing ), updating MI with what we learn. Return true if an error occurs
1170/// parsing the arg list.
1171bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1172 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Chris Lattner141e71f2008-03-09 01:54:53 +00001174 Token Tok;
1175 while (1) {
1176 LexUnexpandedToken(Tok);
1177 switch (Tok.getKind()) {
1178 case tok::r_paren:
1179 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001180 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001181 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001182 // Otherwise we have #define FOO(A,)
1183 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1184 return true;
1185 case tok::ellipsis: // #define X(... -> C99 varargs
1186 // Warn if use of C99 feature in non-C99 mode.
1187 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1188
1189 // Lex the token after the identifier.
1190 LexUnexpandedToken(Tok);
1191 if (Tok.isNot(tok::r_paren)) {
1192 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1193 return true;
1194 }
1195 // Add the __VA_ARGS__ identifier as an argument.
1196 Arguments.push_back(Ident__VA_ARGS__);
1197 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001198 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001199 return false;
1200 case tok::eom: // #define X(
1201 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1202 return true;
1203 default:
1204 // Handle keywords and identifiers here to accept things like
1205 // #define Foo(for) for.
1206 IdentifierInfo *II = Tok.getIdentifierInfo();
1207 if (II == 0) {
1208 // #define X(1
1209 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1210 return true;
1211 }
1212
1213 // If this is already used as an argument, it is used multiple times (e.g.
1214 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001215 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001216 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001217 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001218 return true;
1219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Chris Lattner141e71f2008-03-09 01:54:53 +00001221 // Add the argument to the macro info.
1222 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Chris Lattner141e71f2008-03-09 01:54:53 +00001224 // Lex the token after the identifier.
1225 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Chris Lattner141e71f2008-03-09 01:54:53 +00001227 switch (Tok.getKind()) {
1228 default: // #define X(A B
1229 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1230 return true;
1231 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001232 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001233 return false;
1234 case tok::comma: // #define X(A,
1235 break;
1236 case tok::ellipsis: // #define X(A... -> GCC extension
1237 // Diagnose extension.
1238 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Chris Lattner141e71f2008-03-09 01:54:53 +00001240 // Lex the token after the identifier.
1241 LexUnexpandedToken(Tok);
1242 if (Tok.isNot(tok::r_paren)) {
1243 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1244 return true;
1245 }
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Chris Lattner141e71f2008-03-09 01:54:53 +00001247 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001248 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001249 return false;
1250 }
1251 }
1252 }
1253}
1254
1255/// HandleDefineDirective - Implements #define. This consumes the entire macro
1256/// line then lets the caller lex the next real token.
1257void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1258 ++NumDefined;
1259
1260 Token MacroNameTok;
1261 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Chris Lattner141e71f2008-03-09 01:54:53 +00001263 // Error reading macro name? If so, diagnostic already issued.
1264 if (MacroNameTok.is(tok::eom))
1265 return;
1266
Chris Lattner2451b522009-04-21 04:46:33 +00001267 Token LastTok = MacroNameTok;
1268
Chris Lattner141e71f2008-03-09 01:54:53 +00001269 // If we are supposed to keep comments in #defines, reenable comment saving
1270 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001271 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Chris Lattner141e71f2008-03-09 01:54:53 +00001273 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001274 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Chris Lattner141e71f2008-03-09 01:54:53 +00001276 Token Tok;
1277 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Chris Lattner141e71f2008-03-09 01:54:53 +00001279 // If this is a function-like macro definition, parse the argument list,
1280 // marking each of the identifiers as being used as macro arguments. Also,
1281 // check other constraints on the first token of the macro body.
1282 if (Tok.is(tok::eom)) {
1283 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001284 } else if (Tok.hasLeadingSpace()) {
1285 // This is a normal token with leading space. Clear the leading space
1286 // marker on the first token to get proper expansion.
1287 Tok.clearFlag(Token::LeadingSpace);
1288 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001289 // This is a function-like macro definition. Read the argument list.
1290 MI->setIsFunctionLike();
1291 if (ReadMacroDefinitionArgList(MI)) {
1292 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001293 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001294 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001295 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001296 DiscardUntilEndOfDirective();
1297 return;
1298 }
1299
Chris Lattner8fde5972009-04-19 18:26:34 +00001300 // If this is a definition of a variadic C99 function-like macro, not using
1301 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Chris Lattner8fde5972009-04-19 18:26:34 +00001303 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1304 // This gets unpoisoned where it is allowed.
1305 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1306 if (MI->isC99Varargs())
1307 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Chris Lattner141e71f2008-03-09 01:54:53 +00001309 // Read the first token after the arg list for down below.
1310 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001311 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001312 // C99 requires whitespace between the macro definition and the body. Emit
1313 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001314 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001315 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001316 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1317 // first character of a replacement list is not a character required by
1318 // subclause 5.2.1, then there shall be white-space separation between the
1319 // identifier and the replacement list.". 5.2.1 lists this set:
1320 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1321 // is irrelevant here.
1322 bool isInvalid = false;
1323 if (Tok.is(tok::at)) // @ is not in the list above.
1324 isInvalid = true;
1325 else if (Tok.is(tok::unknown)) {
1326 // If we have an unknown token, it is something strange like "`". Since
1327 // all of valid characters would have lexed into a single character
1328 // token of some sort, we know this is not a valid case.
1329 isInvalid = true;
1330 }
1331 if (isInvalid)
1332 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1333 else
1334 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001335 }
Chris Lattner2451b522009-04-21 04:46:33 +00001336
1337 if (!Tok.is(tok::eom))
1338 LastTok = Tok;
1339
Chris Lattner141e71f2008-03-09 01:54:53 +00001340 // Read the rest of the macro body.
1341 if (MI->isObjectLike()) {
1342 // Object-like macros are very simple, just read their body.
1343 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001344 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001345 MI->AddTokenToBody(Tok);
1346 // Get the next token of the macro.
1347 LexUnexpandedToken(Tok);
1348 }
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Chris Lattner141e71f2008-03-09 01:54:53 +00001350 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001351 // Otherwise, read the body of a function-like macro. While we are at it,
1352 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1353 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001354 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001355 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001356
Chris Lattner141e71f2008-03-09 01:54:53 +00001357 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001358 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Chris Lattner141e71f2008-03-09 01:54:53 +00001360 // Get the next token of the macro.
1361 LexUnexpandedToken(Tok);
1362 continue;
1363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Chris Lattner141e71f2008-03-09 01:54:53 +00001365 // Get the next token of the macro.
1366 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Chris Lattner32404692009-05-25 17:16:10 +00001368 // Check for a valid macro arg identifier.
1369 if (Tok.getIdentifierInfo() == 0 ||
1370 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1371
1372 // If this is assembler-with-cpp mode, we accept random gibberish after
1373 // the '#' because '#' is often a comment character. However, change
1374 // the kind of the token to tok::unknown so that the preprocessor isn't
1375 // confused.
1376 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1377 LastTok.setKind(tok::unknown);
1378 } else {
1379 Diag(Tok, diag::err_pp_stringize_not_parameter);
1380 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Chris Lattner32404692009-05-25 17:16:10 +00001382 // Disable __VA_ARGS__ again.
1383 Ident__VA_ARGS__->setIsPoisoned(true);
1384 return;
1385 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001386 }
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Chris Lattner32404692009-05-25 17:16:10 +00001388 // Things look ok, add the '#' and param name tokens to the macro.
1389 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001390 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001391 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Chris Lattner141e71f2008-03-09 01:54:53 +00001393 // Get the next token of the macro.
1394 LexUnexpandedToken(Tok);
1395 }
1396 }
Mike Stump1eb44332009-09-09 15:08:12 +00001397
1398
Chris Lattner141e71f2008-03-09 01:54:53 +00001399 // Disable __VA_ARGS__ again.
1400 Ident__VA_ARGS__->setIsPoisoned(true);
1401
1402 // Check that there is no paste (##) operator at the begining or end of the
1403 // replacement list.
1404 unsigned NumTokens = MI->getNumTokens();
1405 if (NumTokens != 0) {
1406 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1407 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001408 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001409 return;
1410 }
1411 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1412 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001413 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001414 return;
1415 }
1416 }
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Chris Lattner141e71f2008-03-09 01:54:53 +00001418 // If this is the primary source file, remember that this macro hasn't been
1419 // used yet.
1420 if (isInPrimaryFile())
1421 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001422
1423 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Chris Lattner141e71f2008-03-09 01:54:53 +00001425 // Finally, if this identifier already had a macro defined for it, verify that
1426 // the macro bodies are identical and free the old definition.
1427 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001428 // It is very common for system headers to have tons of macro redefinitions
1429 // and for warnings to be disabled in system headers. If this is the case,
1430 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001431 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001432 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1433 if (!OtherMI->isUsed())
1434 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001435
Chris Lattner41c3ae12009-01-16 19:50:11 +00001436 // Macros must be identical. This means all tokes and whitespace
1437 // separation must be the same. C99 6.10.3.2.
1438 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1439 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1440 << MacroNameTok.getIdentifierInfo();
1441 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1442 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001443 }
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Ted Kremenek0ea76722008-12-15 19:56:42 +00001445 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Chris Lattner141e71f2008-03-09 01:54:53 +00001448 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001450 // If the callbacks want to know, tell them about the macro definition.
1451 if (Callbacks)
1452 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001453}
1454
1455/// HandleUndefDirective - Implements #undef.
1456///
1457void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1458 ++NumUndefined;
1459
1460 Token MacroNameTok;
1461 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Chris Lattner141e71f2008-03-09 01:54:53 +00001463 // Error reading macro name? If so, diagnostic already issued.
1464 if (MacroNameTok.is(tok::eom))
1465 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Chris Lattner141e71f2008-03-09 01:54:53 +00001467 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001468 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Chris Lattner141e71f2008-03-09 01:54:53 +00001470 // Okay, we finally have a valid identifier to undef.
1471 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Chris Lattner141e71f2008-03-09 01:54:53 +00001473 // If the macro is not defined, this is a noop undef, just return.
1474 if (MI == 0) return;
1475
1476 if (!MI->isUsed())
1477 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001478
1479 // If the callbacks want to know, tell them about the macro #undef.
1480 if (Callbacks)
1481 Callbacks->MacroUndefined(MacroNameTok.getIdentifierInfo(), MI);
1482
Chris Lattner141e71f2008-03-09 01:54:53 +00001483 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001484 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001485 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1486}
1487
1488
1489//===----------------------------------------------------------------------===//
1490// Preprocessor Conditional Directive Handling.
1491//===----------------------------------------------------------------------===//
1492
1493/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1494/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1495/// if any tokens have been returned or pp-directives activated before this
1496/// #ifndef has been lexed.
1497///
1498void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1499 bool ReadAnyTokensBeforeDirective) {
1500 ++NumIf;
1501 Token DirectiveTok = Result;
1502
1503 Token MacroNameTok;
1504 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Chris Lattner141e71f2008-03-09 01:54:53 +00001506 // Error reading macro name? If so, diagnostic already issued.
1507 if (MacroNameTok.is(tok::eom)) {
1508 // Skip code until we get to #endif. This helps with recovery by not
1509 // emitting an error when the #endif is reached.
1510 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1511 /*Foundnonskip*/false, /*FoundElse*/false);
1512 return;
1513 }
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Chris Lattner141e71f2008-03-09 01:54:53 +00001515 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001516 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001517
Chris Lattner13d283d2010-02-12 08:03:27 +00001518 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1519 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001520
Ted Kremenek60e45d42008-11-18 00:34:22 +00001521 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001522 // If the start of a top-level #ifdef and if the macro is not defined,
1523 // inform MIOpt that this might be the start of a proper include guard.
1524 // Otherwise it is some other form of unknown conditional which we can't
1525 // handle.
1526 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001527 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001528 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001529 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001530 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001531 }
1532
Chris Lattner141e71f2008-03-09 01:54:53 +00001533 // If there is a macro, process it.
1534 if (MI) // Mark it used.
1535 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Chris Lattner141e71f2008-03-09 01:54:53 +00001537 // Should we include the stuff contained by this directive?
1538 if (!MI == isIfndef) {
1539 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001540 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1541 /*wasskip*/false, /*foundnonskip*/true,
1542 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001543 } else {
1544 // No, skip the contents of this block and return the first token after it.
1545 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001546 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001547 /*FoundElse*/false);
1548 }
1549}
1550
1551/// HandleIfDirective - Implements the #if directive.
1552///
1553void Preprocessor::HandleIfDirective(Token &IfToken,
1554 bool ReadAnyTokensBeforeDirective) {
1555 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Chris Lattner141e71f2008-03-09 01:54:53 +00001557 // Parse and evaluation the conditional expression.
1558 IdentifierInfo *IfNDefMacro = 0;
1559 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Nuno Lopes0049db62008-06-01 18:31:24 +00001561
1562 // If this condition is equivalent to #ifndef X, and if this is the first
1563 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001564 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001565 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001566 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001567 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001568 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001569 }
1570
Chris Lattner141e71f2008-03-09 01:54:53 +00001571 // Should we include the stuff contained by this directive?
1572 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001573 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001574 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001575 /*foundnonskip*/true, /*foundelse*/false);
1576 } else {
1577 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001578 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001579 /*FoundElse*/false);
1580 }
1581}
1582
1583/// HandleEndifDirective - Implements the #endif directive.
1584///
1585void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1586 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Chris Lattner141e71f2008-03-09 01:54:53 +00001588 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001589 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Chris Lattner141e71f2008-03-09 01:54:53 +00001591 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001592 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001593 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001594 Diag(EndifToken, diag::err_pp_endif_without_if);
1595 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001596 }
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Chris Lattner141e71f2008-03-09 01:54:53 +00001598 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001599 if (CurPPLexer->getConditionalStackDepth() == 0)
1600 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Ted Kremenek60e45d42008-11-18 00:34:22 +00001602 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001603 "This code should only be reachable in the non-skipping case!");
1604}
1605
1606
1607void Preprocessor::HandleElseDirective(Token &Result) {
1608 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Chris Lattner141e71f2008-03-09 01:54:53 +00001610 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001611 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Chris Lattner141e71f2008-03-09 01:54:53 +00001613 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001614 if (CurPPLexer->popConditionalLevel(CI)) {
1615 Diag(Result, diag::pp_err_else_without_if);
1616 return;
1617 }
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Chris Lattner141e71f2008-03-09 01:54:53 +00001619 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001620 if (CurPPLexer->getConditionalStackDepth() == 0)
1621 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001622
1623 // If this is a #else with a #else before it, report the error.
1624 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Chris Lattner141e71f2008-03-09 01:54:53 +00001626 // Finally, skip the rest of the contents of this block and return the first
1627 // token after it.
1628 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1629 /*FoundElse*/true);
1630}
1631
1632void Preprocessor::HandleElifDirective(Token &ElifToken) {
1633 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Chris Lattner141e71f2008-03-09 01:54:53 +00001635 // #elif directive in a non-skipping conditional... start skipping.
1636 // We don't care what the condition is, because we will always skip it (since
1637 // the block immediately before it was included).
1638 DiscardUntilEndOfDirective();
1639
1640 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001641 if (CurPPLexer->popConditionalLevel(CI)) {
1642 Diag(ElifToken, diag::pp_err_elif_without_if);
1643 return;
1644 }
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Chris Lattner141e71f2008-03-09 01:54:53 +00001646 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001647 if (CurPPLexer->getConditionalStackDepth() == 0)
1648 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Chris Lattner141e71f2008-03-09 01:54:53 +00001650 // If this is a #elif with a #else before it, report the error.
1651 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1652
1653 // Finally, skip the rest of the contents of this block and return the first
1654 // token after it.
1655 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1656 /*FoundElse*/CI.FoundElse);
1657}
1658