blob: 9e3d283d888613a6088b09f1486d5a9449930fe6 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Chris Lattner359cc442009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Chris Lattner6e290142009-11-30 04:18:44 +000019#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000021#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000022using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// Utility Methods for Preprocessor Directive Handling.
26//===----------------------------------------------------------------------===//
27
Chris Lattner0301b3f2009-02-20 22:19:20 +000028MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
Ted Kremenek0ea76722008-12-15 19:56:42 +000029 MacroInfo *MI;
Mike Stump1eb44332009-09-09 15:08:12 +000030
Ted Kremenek0ea76722008-12-15 19:56:42 +000031 if (!MICache.empty()) {
32 MI = MICache.back();
33 MICache.pop_back();
Chris Lattner0301b3f2009-02-20 22:19:20 +000034 } else
35 MI = (MacroInfo*) BP.Allocate<MacroInfo>();
Ted Kremenek0ea76722008-12-15 19:56:42 +000036 new (MI) MacroInfo(L);
37 return MI;
38}
39
Chris Lattner0301b3f2009-02-20 22:19:20 +000040/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
41/// be reused for allocating new MacroInfo objects.
42void Preprocessor::ReleaseMacroInfo(MacroInfo* MI) {
43 MICache.push_back(MI);
Chris Lattner685befe2009-02-20 22:46:43 +000044 MI->FreeArgumentList(BP);
Chris Lattner0301b3f2009-02-20 22:19:20 +000045}
46
47
Chris Lattner141e71f2008-03-09 01:54:53 +000048/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
49/// current line until the tok::eom token is found.
50void Preprocessor::DiscardUntilEndOfDirective() {
51 Token Tmp;
52 do {
53 LexUnexpandedToken(Tmp);
54 } while (Tmp.isNot(tok::eom));
55}
56
Chris Lattner141e71f2008-03-09 01:54:53 +000057/// ReadMacroName - Lex and validate a macro name, which occurs after a
58/// #define or #undef. This sets the token kind to eom and discards the rest
59/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
60/// this is due to a a #define, 2 if #undef directive, 0 if it is something
61/// else (e.g. #ifdef).
62void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
63 // Read the token, don't allow macro expansion on it.
64 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner141e71f2008-03-09 01:54:53 +000066 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000067 if (MacroNameTok.is(tok::eom)) {
68 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
69 return;
70 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner141e71f2008-03-09 01:54:53 +000072 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
73 if (II == 0) {
74 std::string Spelling = getSpelling(MacroNameTok);
Chris Lattner9485d232008-12-13 20:12:40 +000075 const IdentifierInfo &Info = Identifiers.get(Spelling);
76 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +000077 // C++ 2.5p2: Alternative tokens behave the same as its primary token
78 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +000079 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000080 else
81 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
82 // Fall through on error.
83 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
84 // Error if defining "defined": C99 6.10.8.4.
85 Diag(MacroNameTok, diag::err_defined_macro_name);
86 } else if (isDefineUndef && II->hasMacroDefinition() &&
87 getMacroInfo(II)->isBuiltinMacro()) {
88 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
89 if (isDefineUndef == 1)
90 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
91 else
92 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
93 } else {
94 // Okay, we got a good identifier node. Return it.
95 return;
96 }
Mike Stump1eb44332009-09-09 15:08:12 +000097
Chris Lattner141e71f2008-03-09 01:54:53 +000098 // Invalid macro name, read and discard the rest of the line. Then set the
99 // token kind to tok::eom.
100 MacroNameTok.setKind(tok::eom);
101 return DiscardUntilEndOfDirective();
102}
103
104/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattnerab82f412009-04-17 23:30:53 +0000105/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
106/// true, then we consider macros that expand to zero tokens as being ok.
107void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000108 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000109 // Lex unexpanded tokens for most directives: macros might expand to zero
110 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
111 // #line) allow empty macros.
112 if (EnableMacros)
113 Lex(Tmp);
114 else
115 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Chris Lattner141e71f2008-03-09 01:54:53 +0000117 // There should be no tokens after the directive, but we allow them as an
118 // extension.
119 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
120 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattner141e71f2008-03-09 01:54:53 +0000122 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000123 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
124 // because it is more trouble than it is worth to insert /**/ and check that
125 // there is no /**/ in the range also.
126 CodeModificationHint FixItHint;
127 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
128 FixItHint = CodeModificationHint::CreateInsertion(Tmp.getLocation(),"//");
129 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << FixItHint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000130 DiscardUntilEndOfDirective();
131 }
132}
133
134
135
136/// SkipExcludedConditionalBlock - We just read a #if or related directive and
137/// decided that the subsequent tokens are in the #if'd out portion of the
138/// file. Lex the rest of the file, until we see an #endif. If
139/// FoundNonSkipPortion is true, then we have already emitted code for part of
140/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
141/// is true, then #else directives are ok, if not, then we have already seen one
142/// so a #else directive is a duplicate. When this returns, the caller can lex
143/// the first valid token.
144void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
145 bool FoundNonSkipPortion,
146 bool FoundElse) {
147 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000148 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000149
Ted Kremenek60e45d42008-11-18 00:34:22 +0000150 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000151 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Ted Kremenek268ee702008-12-12 18:34:08 +0000153 if (CurPTHLexer) {
154 PTHSkipExcludedConditionalBlock();
155 return;
156 }
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Chris Lattner141e71f2008-03-09 01:54:53 +0000158 // Enter raw mode to disable identifier lookup (and thus macro expansion),
159 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000160 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000161 Token Tok;
162 while (1) {
Ted Kremenekf6452c52008-11-18 01:04:47 +0000163 if (CurLexer)
164 CurLexer->Lex(Tok);
165 else
166 CurPTHLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattner141e71f2008-03-09 01:54:53 +0000168 // If this is the end of the buffer, we have an error.
169 if (Tok.is(tok::eof)) {
170 // Emit errors for each unterminated conditional on the stack, including
171 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000172 while (!CurPPLexer->ConditionalStack.empty()) {
173 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000174 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000175 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000176 }
177
Chris Lattner141e71f2008-03-09 01:54:53 +0000178 // Just return and let the caller lex after this #include.
179 break;
180 }
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattner141e71f2008-03-09 01:54:53 +0000182 // If this token is not a preprocessor directive, just skip it.
183 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
184 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattner141e71f2008-03-09 01:54:53 +0000186 // We just parsed a # character at the start of a line, so we're in
187 // directive mode. Tell the lexer this so any newlines we see will be
188 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000189 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000190 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000191
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner141e71f2008-03-09 01:54:53 +0000193 // Read the next token, the directive flavor.
194 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner141e71f2008-03-09 01:54:53 +0000196 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
197 // something bogus), skip it.
198 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000199 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000200 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000201 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000202 continue;
203 }
204
205 // If the first letter isn't i or e, it isn't intesting to us. We know that
206 // this is safe in the face of spelling differences, because there is no way
207 // to spell an i/e in a strange way that is another letter. Skipping this
208 // allows us to avoid looking up the identifier info for #define/#undef and
209 // other common directives.
210 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
211 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000212 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000213 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000214 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000215 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000216 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000217 continue;
218 }
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattner141e71f2008-03-09 01:54:53 +0000220 // Get the identifier name without trigraphs or embedded newlines. Note
221 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
222 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000223 char DirectiveBuf[20];
224 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000225 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000226 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000227 } else {
228 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000229 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000230 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000231 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000232 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000233 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000234 continue;
235 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000236 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
237 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000238 }
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000240 if (Directive.startswith("if")) {
241 llvm::StringRef Sub = Directive.substr(2);
242 if (Sub.empty() || // "if"
243 Sub == "def" || // "ifdef"
244 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000245 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
246 // bother parsing the condition.
247 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000248 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000249 /*foundnonskip*/false,
250 /*fnddelse*/false);
251 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000252 } else if (Directive[0] == 'e') {
253 llvm::StringRef Sub = Directive.substr(1);
254 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000255 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000256 PPConditionalInfo CondInfo;
257 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000258 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000259 InCond = InCond; // Silence warning in no-asserts mode.
260 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Chris Lattner141e71f2008-03-09 01:54:53 +0000262 // If we popped the outermost skipping block, we're done skipping!
263 if (!CondInfo.WasSkipping)
264 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000265 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000266 // #else directive in a skipping conditional. If not in some other
267 // skipping conditional, and if #else hasn't already been seen, enter it
268 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000269 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000270 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Chris Lattner141e71f2008-03-09 01:54:53 +0000272 // If this is a #else with a #else before it, report the error.
273 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattner141e71f2008-03-09 01:54:53 +0000275 // Note that we've seen a #else in this conditional.
276 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattner141e71f2008-03-09 01:54:53 +0000278 // If the conditional is at the top level, and the #if block wasn't
279 // entered, enter the #else block now.
280 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
281 CondInfo.FoundNonSkip = true;
282 break;
283 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000284 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000285 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000286
287 bool ShouldEnter;
288 // If this is in a skipping block or if we're already handled this #if
289 // block, don't bother parsing the condition.
290 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
291 DiscardUntilEndOfDirective();
292 ShouldEnter = false;
293 } else {
294 // Restore the value of LexingRawMode so that identifiers are
295 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000296 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
297 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000298 IdentifierInfo *IfNDefMacro = 0;
299 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000300 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000301 }
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 // If this is a #elif with a #else before it, report the error.
304 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattner141e71f2008-03-09 01:54:53 +0000306 // If this condition is true, enter it!
307 if (ShouldEnter) {
308 CondInfo.FoundNonSkip = true;
309 break;
310 }
311 }
312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Ted Kremenek60e45d42008-11-18 00:34:22 +0000314 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000315 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000316 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000317 }
318
319 // Finally, if we are out of the conditional (saw an #endif or ran off the end
320 // of the file, just stop skipping and return to lexing whatever came after
321 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000322 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000323}
324
Ted Kremenek268ee702008-12-12 18:34:08 +0000325void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000326
327 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000328 assert(CurPTHLexer);
329 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Ted Kremenek268ee702008-12-12 18:34:08 +0000331 // Skip to the next '#else', '#elif', or #endif.
332 if (CurPTHLexer->SkipBlock()) {
333 // We have reached an #endif. Both the '#' and 'endif' tokens
334 // have been consumed by the PTHLexer. Just pop off the condition level.
335 PPConditionalInfo CondInfo;
336 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
337 InCond = InCond; // Silence warning in no-asserts mode.
338 assert(!InCond && "Can't be skipping if not in a conditional!");
339 break;
340 }
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Ted Kremenek268ee702008-12-12 18:34:08 +0000342 // We have reached a '#else' or '#elif'. Lex the next token to get
343 // the directive flavor.
344 Token Tok;
345 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Ted Kremenek268ee702008-12-12 18:34:08 +0000347 // We can actually look up the IdentifierInfo here since we aren't in
348 // raw mode.
349 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
350
351 if (K == tok::pp_else) {
352 // #else: Enter the else condition. We aren't in a nested condition
353 // since we skip those. We're always in the one matching the last
354 // blocked we skipped.
355 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
356 // Note that we've seen a #else in this conditional.
357 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Ted Kremenek268ee702008-12-12 18:34:08 +0000359 // If the #if block wasn't entered then enter the #else block now.
360 if (!CondInfo.FoundNonSkip) {
361 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000363 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000364 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000365 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000366 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Ted Kremenek268ee702008-12-12 18:34:08 +0000368 break;
369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Ted Kremenek268ee702008-12-12 18:34:08 +0000371 // Otherwise skip this block.
372 continue;
373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Ted Kremenek268ee702008-12-12 18:34:08 +0000375 assert(K == tok::pp_elif);
376 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
377
378 // If this is a #elif with a #else before it, report the error.
379 if (CondInfo.FoundElse)
380 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Ted Kremenek268ee702008-12-12 18:34:08 +0000382 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000383 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000384 if (CondInfo.FoundNonSkip)
385 continue;
386
387 // Evaluate the condition of the #elif.
388 IdentifierInfo *IfNDefMacro = 0;
389 CurPTHLexer->ParsingPreprocessorDirective = true;
390 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
391 CurPTHLexer->ParsingPreprocessorDirective = false;
392
393 // If this condition is true, enter it!
394 if (ShouldEnter) {
395 CondInfo.FoundNonSkip = true;
396 break;
397 }
398
399 // Otherwise, skip this block and go to the next one.
400 continue;
401 }
402}
403
Chris Lattner10725092008-03-09 04:17:44 +0000404/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
405/// return null on failure. isAngled indicates whether the file reference is
406/// for system #include's or not (i.e. using <> instead of "").
407const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
408 const char *FilenameEnd,
409 bool isAngled,
410 const DirectoryLookup *FromDir,
411 const DirectoryLookup *&CurDir) {
412 // If the header lookup mechanism may be relative to the current file, pass in
413 // info about where the current file is.
414 const FileEntry *CurFileEnt = 0;
415 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000416 FileID FID = getCurrentFileLexer()->getFileID();
417 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000419 // If there is no file entry associated with this file, it must be the
420 // predefines buffer. Any other file is not lexed with a normal lexer, so
421 // it won't be scanned for preprocessor directives. If we have the
422 // predefines buffer, resolve #include references (which come from the
423 // -include command line argument) as if they came from the main file, this
424 // affects file lookup etc.
425 if (CurFileEnt == 0) {
426 FID = SourceMgr.getMainFileID();
427 CurFileEnt = SourceMgr.getFileEntryForID(FID);
428 }
Chris Lattner10725092008-03-09 04:17:44 +0000429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Chris Lattner10725092008-03-09 04:17:44 +0000431 // Do a standard file entry lookup.
432 CurDir = CurDirLookup;
433 const FileEntry *FE =
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000434 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
435 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner10725092008-03-09 04:17: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 Lattner10725092008-03-09 04:17:44 +0000443 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
444 CurFileEnt)))
445 return FE;
446 }
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattner10725092008-03-09 04:17:44 +0000448 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
449 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000450 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000451 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000452 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000453 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
454 FilenameEnd, CurFileEnt)))
455 return FE;
456 }
457 }
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Chris Lattner10725092008-03-09 04:17:44 +0000459 // Otherwise, we really couldn't find the file.
460 return 0;
461}
462
Chris Lattner141e71f2008-03-09 01:54:53 +0000463
464//===----------------------------------------------------------------------===//
465// Preprocessor Directive Handling.
466//===----------------------------------------------------------------------===//
467
468/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000469/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000470/// lexer/preprocessor state, and advances the lexer(s) so that the next token
471/// read is the correct one.
472void Preprocessor::HandleDirective(Token &Result) {
473 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Chris Lattner141e71f2008-03-09 01:54:53 +0000475 // We just parsed a # character at the start of a line, so we're in directive
476 // mode. Tell the lexer this so any newlines we see will be converted into an
477 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000478 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner141e71f2008-03-09 01:54:53 +0000480 ++NumDirectives;
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000481
Chris Lattner141e71f2008-03-09 01:54:53 +0000482 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000483 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000484 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000485 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Chris Lattner42aa16c2009-03-18 21:00:25 +0000487 // Save the '#' token in case we need to return it later.
488 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Chris Lattner141e71f2008-03-09 01:54:53 +0000490 // Read the next token, the directive flavor. This isn't expanded due to
491 // C99 6.10.3p8.
492 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Chris Lattner141e71f2008-03-09 01:54:53 +0000494 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
495 // #define A(x) #x
496 // A(abc
497 // #warning blah
498 // def)
499 // If so, the user is relying on non-portable behavior, emit a diagnostic.
500 if (InMacroArgs)
501 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Chris Lattner141e71f2008-03-09 01:54:53 +0000503TryAgain:
504 switch (Result.getKind()) {
505 case tok::eom:
506 return; // null directive.
507 case tok::comment:
508 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
509 LexUnexpandedToken(Result);
510 goto TryAgain;
511
Chris Lattner478a18e2009-01-26 06:19:46 +0000512 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000513 if (getLangOptions().AsmPreprocessor)
514 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000515 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000516 default:
517 IdentifierInfo *II = Result.getIdentifierInfo();
518 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Chris Lattner141e71f2008-03-09 01:54:53 +0000520 // Ask what the preprocessor keyword ID is.
521 switch (II->getPPKeywordID()) {
522 default: break;
523 // C99 6.10.1 - Conditional Inclusion.
524 case tok::pp_if:
525 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
526 case tok::pp_ifdef:
527 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
528 case tok::pp_ifndef:
529 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
530 case tok::pp_elif:
531 return HandleElifDirective(Result);
532 case tok::pp_else:
533 return HandleElseDirective(Result);
534 case tok::pp_endif:
535 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner141e71f2008-03-09 01:54:53 +0000537 // C99 6.10.2 - Source File Inclusion.
538 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000539 return HandleIncludeDirective(Result); // Handle #include.
540 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000541 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Chris Lattner141e71f2008-03-09 01:54:53 +0000543 // C99 6.10.3 - Macro Replacement.
544 case tok::pp_define:
545 return HandleDefineDirective(Result);
546 case tok::pp_undef:
547 return HandleUndefDirective(Result);
548
549 // C99 6.10.4 - Line Control.
550 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000551 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Chris Lattner141e71f2008-03-09 01:54:53 +0000553 // C99 6.10.5 - Error Directive.
554 case tok::pp_error:
555 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Chris Lattner141e71f2008-03-09 01:54:53 +0000557 // C99 6.10.6 - Pragma Directive.
558 case tok::pp_pragma:
559 return HandlePragmaDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Chris Lattner141e71f2008-03-09 01:54:53 +0000561 // GNU Extensions.
562 case tok::pp_import:
563 return HandleImportDirective(Result);
564 case tok::pp_include_next:
565 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Chris Lattner141e71f2008-03-09 01:54:53 +0000567 case tok::pp_warning:
568 Diag(Result, diag::ext_pp_warning_directive);
569 return HandleUserDiagnosticDirective(Result, true);
570 case tok::pp_ident:
571 return HandleIdentSCCSDirective(Result);
572 case tok::pp_sccs:
573 return HandleIdentSCCSDirective(Result);
574 case tok::pp_assert:
575 //isExtension = true; // FIXME: implement #assert
576 break;
577 case tok::pp_unassert:
578 //isExtension = true; // FIXME: implement #unassert
579 break;
580 }
581 break;
582 }
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattner42aa16c2009-03-18 21:00:25 +0000584 // If this is a .S file, treat unknown # directives as non-preprocessor
585 // directives. This is important because # may be a comment or introduce
586 // various pseudo-ops. Just return the # token and push back the following
587 // token to be lexed next time.
588 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000589 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000590 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000591 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000592 Toks[1] = Result;
593 // Enter this token stream so that we re-lex the tokens. Make sure to
594 // enable macro expansion, in case the token after the # is an identifier
595 // that is expanded.
596 EnterTokenStream(Toks, 2, false, true);
597 return;
598 }
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Chris Lattner141e71f2008-03-09 01:54:53 +0000600 // If we reached here, the preprocessing token is not valid!
601 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Chris Lattner141e71f2008-03-09 01:54:53 +0000603 // Read the rest of the PP line.
604 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Chris Lattner141e71f2008-03-09 01:54:53 +0000606 // Okay, we're done parsing the directive.
607}
608
Chris Lattner478a18e2009-01-26 06:19:46 +0000609/// GetLineValue - Convert a numeric token into an unsigned value, emitting
610/// Diagnostic DiagID if it is invalid, and returning the value in Val.
611static bool GetLineValue(Token &DigitTok, unsigned &Val,
612 unsigned DiagID, Preprocessor &PP) {
613 if (DigitTok.isNot(tok::numeric_constant)) {
614 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Chris Lattner478a18e2009-01-26 06:19:46 +0000616 if (DigitTok.isNot(tok::eom))
617 PP.DiscardUntilEndOfDirective();
618 return true;
619 }
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattner478a18e2009-01-26 06:19:46 +0000621 llvm::SmallString<64> IntegerBuffer;
622 IntegerBuffer.resize(DigitTok.getLength());
623 const char *DigitTokBegin = &IntegerBuffer[0];
624 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000626 // Verify that we have a simple digit-sequence, and compute the value. This
627 // is always a simple digit string computed in decimal, so we do this manually
628 // here.
629 Val = 0;
630 for (unsigned i = 0; i != ActualLength; ++i) {
631 if (!isdigit(DigitTokBegin[i])) {
632 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
633 diag::err_pp_line_digit_sequence);
634 PP.DiscardUntilEndOfDirective();
635 return true;
636 }
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000638 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
639 if (NextVal < Val) { // overflow.
640 PP.Diag(DigitTok, DiagID);
641 PP.DiscardUntilEndOfDirective();
642 return true;
643 }
644 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
647 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000648 if (Val == 0) {
649 PP.Diag(DigitTok, DiagID);
650 PP.DiscardUntilEndOfDirective();
651 return true;
652 }
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000654 if (DigitTokBegin[0] == '0')
655 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Chris Lattner478a18e2009-01-26 06:19:46 +0000657 return false;
658}
659
Mike Stump1eb44332009-09-09 15:08:12 +0000660/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000661/// acceptable forms are:
662/// # line digit-sequence
663/// # line digit-sequence "s-char-sequence"
664void Preprocessor::HandleLineDirective(Token &Tok) {
665 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
666 // expanded.
667 Token DigitTok;
668 Lex(DigitTok);
669
Chris Lattner359cc442009-01-26 05:29:08 +0000670 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000671 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000672 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000673 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000674
Chris Lattner478a18e2009-01-26 06:19:46 +0000675 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
676 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000677 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
678 if (LineNo >= LineLimit)
679 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Chris Lattner5b9a5042009-01-26 07:57:50 +0000681 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000682 Token StrTok;
683 Lex(StrTok);
684
685 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
686 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000687 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000688 ; // ok
689 else if (StrTok.isNot(tok::string_literal)) {
690 Diag(StrTok, diag::err_pp_line_invalid_filename);
691 DiscardUntilEndOfDirective();
692 return;
693 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000694 // Parse and validate the string, converting it into a unique ID.
695 StringLiteralParser Literal(&StrTok, 1, *this);
696 assert(!Literal.AnyWide && "Didn't allow wide strings in");
697 if (Literal.hadError)
698 return DiscardUntilEndOfDirective();
699 if (Literal.Pascal) {
700 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
701 return DiscardUntilEndOfDirective();
702 }
703 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
704 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Chris Lattnerab82f412009-04-17 23:30:53 +0000706 // Verify that there is nothing after the string, other than EOM. Because
707 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
708 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000709 }
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Chris Lattner4c4ea172009-02-03 21:52:55 +0000711 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Chris Lattner16629382009-03-27 17:13:49 +0000713 if (Callbacks)
714 Callbacks->FileChanged(DigitTok.getLocation(), PPCallbacks::RenameFile,
715 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000716}
717
Chris Lattner478a18e2009-01-26 06:19:46 +0000718/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
719/// marker directive.
720static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
721 bool &IsSystemHeader, bool &IsExternCHeader,
722 Preprocessor &PP) {
723 unsigned FlagVal;
724 Token FlagTok;
725 PP.Lex(FlagTok);
726 if (FlagTok.is(tok::eom)) return false;
727 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
728 return true;
729
730 if (FlagVal == 1) {
731 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Chris Lattner478a18e2009-01-26 06:19:46 +0000733 PP.Lex(FlagTok);
734 if (FlagTok.is(tok::eom)) return false;
735 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
736 return true;
737 } else if (FlagVal == 2) {
738 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattner137b6a62009-02-04 06:25:26 +0000740 SourceManager &SM = PP.getSourceManager();
741 // If we are leaving the current presumed file, check to make sure the
742 // presumed include stack isn't empty!
743 FileID CurFileID =
744 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
745 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Chris Lattner137b6a62009-02-04 06:25:26 +0000747 // If there is no include loc (main file) or if the include loc is in a
748 // different physical file, then we aren't in a "1" line marker flag region.
749 SourceLocation IncLoc = PLoc.getIncludeLoc();
750 if (IncLoc.isInvalid() ||
751 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
752 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
753 PP.DiscardUntilEndOfDirective();
754 return true;
755 }
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Chris Lattner478a18e2009-01-26 06:19:46 +0000757 PP.Lex(FlagTok);
758 if (FlagTok.is(tok::eom)) return false;
759 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
760 return true;
761 }
762
763 // We must have 3 if there are still flags.
764 if (FlagVal != 3) {
765 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000766 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000767 return true;
768 }
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattner478a18e2009-01-26 06:19:46 +0000770 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Chris Lattner478a18e2009-01-26 06:19:46 +0000772 PP.Lex(FlagTok);
773 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000774 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000775 return true;
776
777 // We must have 4 if there is yet another flag.
778 if (FlagVal != 4) {
779 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000780 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000781 return true;
782 }
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Chris Lattner478a18e2009-01-26 06:19:46 +0000784 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Chris Lattner478a18e2009-01-26 06:19:46 +0000786 PP.Lex(FlagTok);
787 if (FlagTok.is(tok::eom)) return false;
788
789 // There are no more valid flags here.
790 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000791 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000792 return true;
793}
794
795/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
796/// one of the following forms:
797///
798/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000799/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000800/// # 42 "file" ('1' | '2')? '3' '4'?
801///
802void Preprocessor::HandleDigitDirective(Token &DigitTok) {
803 // Validate the number and convert it to an unsigned. GNU does not have a
804 // line # limit other than it fit in 32-bits.
805 unsigned LineNo;
806 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
807 *this))
808 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Chris Lattner478a18e2009-01-26 06:19:46 +0000810 Token StrTok;
811 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Chris Lattner478a18e2009-01-26 06:19:46 +0000813 bool IsFileEntry = false, IsFileExit = false;
814 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000815 int FilenameID = -1;
816
Chris Lattner478a18e2009-01-26 06:19:46 +0000817 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
818 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000819 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000820 ; // ok
821 else if (StrTok.isNot(tok::string_literal)) {
822 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000823 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000824 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000825 // Parse and validate the string, converting it into a unique ID.
826 StringLiteralParser Literal(&StrTok, 1, *this);
827 assert(!Literal.AnyWide && "Didn't allow wide strings in");
828 if (Literal.hadError)
829 return DiscardUntilEndOfDirective();
830 if (Literal.Pascal) {
831 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
832 return DiscardUntilEndOfDirective();
833 }
834 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
835 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Chris Lattner478a18e2009-01-26 06:19:46 +0000837 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000838 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000839 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000840 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000841 }
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Chris Lattner9d79eba2009-02-04 05:21:58 +0000843 // Create a line note with this information.
844 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000845 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000846 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Chris Lattner16629382009-03-27 17:13:49 +0000848 // If the preprocessor has callbacks installed, notify them of the #line
849 // change. This is used so that the line marker comes out in -E mode for
850 // example.
851 if (Callbacks) {
852 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
853 if (IsFileEntry)
854 Reason = PPCallbacks::EnterFile;
855 else if (IsFileExit)
856 Reason = PPCallbacks::ExitFile;
857 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
858 if (IsExternCHeader)
859 FileKind = SrcMgr::C_ExternCSystem;
860 else if (IsSystemHeader)
861 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Chris Lattner16629382009-03-27 17:13:49 +0000863 Callbacks->FileChanged(DigitTok.getLocation(), Reason, FileKind);
864 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000865}
866
867
Chris Lattner099dd052009-01-26 05:30:54 +0000868/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
869///
Mike Stump1eb44332009-09-09 15:08:12 +0000870void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000871 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000872 // PTH doesn't emit #warning or #error directives.
873 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000874 return CurPTHLexer->DiscardToEndOfLine();
875
Chris Lattner141e71f2008-03-09 01:54:53 +0000876 // Read the rest of the line raw. We do this because we don't want macros
877 // to be expanded and we don't require that the tokens be valid preprocessing
878 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
879 // collapse multiple consequtive white space between tokens, but this isn't
880 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000881 std::string Message = CurLexer->ReadToEndOfLine();
882 if (isWarning)
883 Diag(Tok, diag::pp_hash_warning) << Message;
884 else
885 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000886}
887
888/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
889///
890void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
891 // Yes, this directive is an extension.
892 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Chris Lattner141e71f2008-03-09 01:54:53 +0000894 // Read the string argument.
895 Token StrTok;
896 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Chris Lattner141e71f2008-03-09 01:54:53 +0000898 // If the token kind isn't a string, it's a malformed directive.
899 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000900 StrTok.isNot(tok::wide_string_literal)) {
901 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000902 if (StrTok.isNot(tok::eom))
903 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000904 return;
905 }
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Chris Lattner141e71f2008-03-09 01:54:53 +0000907 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000908 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000909
910 if (Callbacks)
911 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
912}
913
914//===----------------------------------------------------------------------===//
915// Preprocessor Include Directive Handling.
916//===----------------------------------------------------------------------===//
917
918/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
919/// checked and spelled filename, e.g. as an operand of #include. This returns
920/// true if the input filename was in <>'s or false if it were in ""'s. The
921/// caller is expected to provide a buffer that is large enough to hold the
922/// spelling of the filename, but is also expected to handle the case when
923/// this method decides to use a different buffer.
924bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
925 const char *&BufStart,
926 const char *&BufEnd) {
927 // Get the text form of the filename.
928 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Chris Lattner141e71f2008-03-09 01:54:53 +0000930 // Make sure the filename is <x> or "x".
931 bool isAngled;
932 if (BufStart[0] == '<') {
933 if (BufEnd[-1] != '>') {
934 Diag(Loc, diag::err_pp_expects_filename);
935 BufStart = 0;
936 return true;
937 }
938 isAngled = true;
939 } else if (BufStart[0] == '"') {
940 if (BufEnd[-1] != '"') {
941 Diag(Loc, diag::err_pp_expects_filename);
942 BufStart = 0;
943 return true;
944 }
945 isAngled = false;
946 } else {
947 Diag(Loc, diag::err_pp_expects_filename);
948 BufStart = 0;
949 return true;
950 }
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Chris Lattner141e71f2008-03-09 01:54:53 +0000952 // Diagnose #include "" as invalid.
953 if (BufEnd-BufStart <= 2) {
954 Diag(Loc, diag::err_pp_empty_filename);
955 BufStart = 0;
956 return "";
957 }
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Chris Lattner141e71f2008-03-09 01:54:53 +0000959 // Skip the brackets.
960 ++BufStart;
961 --BufEnd;
962 return isAngled;
963}
964
965/// ConcatenateIncludeName - Handle cases where the #include name is expanded
966/// from a macro as multiple tokens, which need to be glued together. This
967/// occurs for code like:
968/// #define FOO <a/b.h>
969/// #include FOO
970/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
971///
972/// This code concatenates and consumes tokens up to the '>' token. It returns
973/// false if the > was found, otherwise it returns true if it finds and consumes
974/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +0000975bool Preprocessor::ConcatenateIncludeName(
976 llvm::SmallVector<char, 128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000977 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +0000978
John Thompsona28cc092009-10-30 13:49:06 +0000979 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000980 while (CurTok.isNot(tok::eom)) {
981 // Append the spelling of this token to the buffer. If there was a space
982 // before it, add it now.
983 if (CurTok.hasLeadingSpace())
984 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Chris Lattner141e71f2008-03-09 01:54:53 +0000986 // Get the spelling of the token, directly into FilenameBuffer if possible.
987 unsigned PreAppendSize = FilenameBuffer.size();
988 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Chris Lattner141e71f2008-03-09 01:54:53 +0000990 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +0000991 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Chris Lattner141e71f2008-03-09 01:54:53 +0000993 // If the token was spelled somewhere else, copy it into FilenameBuffer.
994 if (BufPtr != &FilenameBuffer[PreAppendSize])
995 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Chris Lattner141e71f2008-03-09 01:54:53 +0000997 // Resize FilenameBuffer to the correct size.
998 if (CurTok.getLength() != ActualLen)
999 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattner141e71f2008-03-09 01:54:53 +00001001 // If we found the '>' marker, return success.
1002 if (CurTok.is(tok::greater))
1003 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001004
John Thompsona28cc092009-10-30 13:49:06 +00001005 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001006 }
1007
1008 // If we hit the eom marker, emit an error and return true so that the caller
1009 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001010 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001011 return true;
1012}
1013
1014/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1015/// file to be included from the lexer, then include it! This is a common
1016/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001017/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001018/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001019void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1020 const DirectoryLookup *LookupFrom,
1021 bool isImport) {
1022
1023 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001024 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattner141e71f2008-03-09 01:54:53 +00001026 // Reserve a buffer to get the spelling.
1027 llvm::SmallVector<char, 128> FilenameBuffer;
1028 const char *FilenameStart, *FilenameEnd;
1029
1030 switch (FilenameTok.getKind()) {
1031 case tok::eom:
1032 // If the token kind is EOM, the error has already been diagnosed.
1033 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Chris Lattner141e71f2008-03-09 01:54:53 +00001035 case tok::angle_string_literal:
1036 case tok::string_literal: {
1037 FilenameBuffer.resize(FilenameTok.getLength());
1038 FilenameStart = &FilenameBuffer[0];
1039 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1040 FilenameEnd = FilenameStart+Len;
1041 break;
1042 }
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Chris Lattner141e71f2008-03-09 01:54:53 +00001044 case tok::less:
1045 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1046 // case, glue the tokens together into FilenameBuffer and interpret those.
1047 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001048 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001049 return; // Found <eom> but no ">"? Diagnostic already emitted.
Jay Foadbeaaccd2009-05-21 09:52:38 +00001050 FilenameStart = FilenameBuffer.data();
1051 FilenameEnd = FilenameStart + FilenameBuffer.size();
Chris Lattner141e71f2008-03-09 01:54:53 +00001052 break;
1053 default:
1054 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1055 DiscardUntilEndOfDirective();
1056 return;
1057 }
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Chris Lattner141e71f2008-03-09 01:54:53 +00001059 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
1060 FilenameStart, FilenameEnd);
1061 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1062 // error.
1063 if (FilenameStart == 0) {
1064 DiscardUntilEndOfDirective();
1065 return;
1066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001068 // Verify that there is nothing after the filename, other than EOM. Note that
1069 // we allow macros that expand to nothing after the filename, because this
1070 // falls into the category of "#include pp-tokens new-line" specified in
1071 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001072 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001073
1074 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001075 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1076 Diag(FilenameTok, diag::err_pp_include_too_deep);
1077 return;
1078 }
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Chris Lattner141e71f2008-03-09 01:54:53 +00001080 // Search include directories.
1081 const DirectoryLookup *CurDir;
1082 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1083 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001084 if (File == 0) {
1085 Diag(FilenameTok, diag::err_pp_file_not_found)
1086 << std::string(FilenameStart, FilenameEnd);
1087 return;
1088 }
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Chris Lattner72181832008-09-26 20:12:23 +00001090 // Ask HeaderInfo if we should enter this #include file. If not, #including
1091 // this file will have no effect.
1092 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001093 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Chris Lattner72181832008-09-26 20:12:23 +00001095 // The #included file will be considered to be a system header if either it is
1096 // in a system include directory, or if the #includer is a system include
1097 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001098 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001099 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001100 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Chris Lattner141e71f2008-03-09 01:54:53 +00001102 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001103 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1104 FileCharacter);
1105 if (FID.isInvalid()) {
Chris Lattner56b05c82008-11-18 08:02:48 +00001106 Diag(FilenameTok, diag::err_pp_file_not_found)
1107 << std::string(FilenameStart, FilenameEnd);
1108 return;
1109 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001110
1111 // Finally, if all is good, enter the new file!
Chris Lattner39d98412009-12-01 22:52:33 +00001112 std::string ErrorStr;
Daniel Dunbar63ceaa32009-12-06 09:19:12 +00001113 if (EnterSourceFile(FID, CurDir, ErrorStr))
Chris Lattner6e290142009-11-30 04:18:44 +00001114 Diag(FilenameTok, diag::err_pp_error_opening_file)
Chris Lattner39d98412009-12-01 22:52:33 +00001115 << std::string(SourceMgr.getFileEntryForID(FID)->getName()) << ErrorStr;
Chris Lattner141e71f2008-03-09 01:54:53 +00001116}
1117
1118/// HandleIncludeNextDirective - Implements #include_next.
1119///
1120void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1121 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Chris Lattner141e71f2008-03-09 01:54:53 +00001123 // #include_next is like #include, except that we start searching after
1124 // the current found directory. If we can't do this, issue a
1125 // diagnostic.
1126 const DirectoryLookup *Lookup = CurDirLookup;
1127 if (isInPrimaryFile()) {
1128 Lookup = 0;
1129 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1130 } else if (Lookup == 0) {
1131 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1132 } else {
1133 // Start looking up in the next directory.
1134 ++Lookup;
1135 }
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattner141e71f2008-03-09 01:54:53 +00001137 return HandleIncludeDirective(IncludeNextTok, Lookup);
1138}
1139
1140/// HandleImportDirective - Implements #import.
1141///
1142void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001143 if (!Features.ObjC1) // #import is standard for ObjC.
1144 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Chris Lattner141e71f2008-03-09 01:54:53 +00001146 return HandleIncludeDirective(ImportTok, 0, true);
1147}
1148
Chris Lattnerde076652009-04-08 18:46:40 +00001149/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1150/// pseudo directive in the predefines buffer. This handles it by sucking all
1151/// tokens through the preprocessor and discarding them (only keeping the side
1152/// effects on the preprocessor).
1153void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1154 // This directive should only occur in the predefines buffer. If not, emit an
1155 // error and reject it.
1156 SourceLocation Loc = IncludeMacrosTok.getLocation();
1157 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1158 Diag(IncludeMacrosTok.getLocation(),
1159 diag::pp_include_macros_out_of_predefines);
1160 DiscardUntilEndOfDirective();
1161 return;
1162 }
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Chris Lattnerfd105112009-04-08 20:53:24 +00001164 // Treat this as a normal #include for checking purposes. If this is
1165 // successful, it will push a new lexer onto the include stack.
1166 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Chris Lattnerfd105112009-04-08 20:53:24 +00001168 Token TmpTok;
1169 do {
1170 Lex(TmpTok);
1171 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1172 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001173}
1174
Chris Lattner141e71f2008-03-09 01:54:53 +00001175//===----------------------------------------------------------------------===//
1176// Preprocessor Macro Directive Handling.
1177//===----------------------------------------------------------------------===//
1178
1179/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1180/// definition has just been read. Lex the rest of the arguments and the
1181/// closing ), updating MI with what we learn. Return true if an error occurs
1182/// parsing the arg list.
1183bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1184 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Chris Lattner141e71f2008-03-09 01:54:53 +00001186 Token Tok;
1187 while (1) {
1188 LexUnexpandedToken(Tok);
1189 switch (Tok.getKind()) {
1190 case tok::r_paren:
1191 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001192 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001193 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001194 // Otherwise we have #define FOO(A,)
1195 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1196 return true;
1197 case tok::ellipsis: // #define X(... -> C99 varargs
1198 // Warn if use of C99 feature in non-C99 mode.
1199 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1200
1201 // Lex the token after the identifier.
1202 LexUnexpandedToken(Tok);
1203 if (Tok.isNot(tok::r_paren)) {
1204 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1205 return true;
1206 }
1207 // Add the __VA_ARGS__ identifier as an argument.
1208 Arguments.push_back(Ident__VA_ARGS__);
1209 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001210 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001211 return false;
1212 case tok::eom: // #define X(
1213 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1214 return true;
1215 default:
1216 // Handle keywords and identifiers here to accept things like
1217 // #define Foo(for) for.
1218 IdentifierInfo *II = Tok.getIdentifierInfo();
1219 if (II == 0) {
1220 // #define X(1
1221 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1222 return true;
1223 }
1224
1225 // If this is already used as an argument, it is used multiple times (e.g.
1226 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001227 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001228 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001229 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001230 return true;
1231 }
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Chris Lattner141e71f2008-03-09 01:54:53 +00001233 // Add the argument to the macro info.
1234 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Chris Lattner141e71f2008-03-09 01:54:53 +00001236 // Lex the token after the identifier.
1237 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Chris Lattner141e71f2008-03-09 01:54:53 +00001239 switch (Tok.getKind()) {
1240 default: // #define X(A B
1241 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1242 return true;
1243 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001244 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001245 return false;
1246 case tok::comma: // #define X(A,
1247 break;
1248 case tok::ellipsis: // #define X(A... -> GCC extension
1249 // Diagnose extension.
1250 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Chris Lattner141e71f2008-03-09 01:54:53 +00001252 // Lex the token after the identifier.
1253 LexUnexpandedToken(Tok);
1254 if (Tok.isNot(tok::r_paren)) {
1255 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1256 return true;
1257 }
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Chris Lattner141e71f2008-03-09 01:54:53 +00001259 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001260 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001261 return false;
1262 }
1263 }
1264 }
1265}
1266
1267/// HandleDefineDirective - Implements #define. This consumes the entire macro
1268/// line then lets the caller lex the next real token.
1269void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1270 ++NumDefined;
1271
1272 Token MacroNameTok;
1273 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Chris Lattner141e71f2008-03-09 01:54:53 +00001275 // Error reading macro name? If so, diagnostic already issued.
1276 if (MacroNameTok.is(tok::eom))
1277 return;
1278
Chris Lattner2451b522009-04-21 04:46:33 +00001279 Token LastTok = MacroNameTok;
1280
Chris Lattner141e71f2008-03-09 01:54:53 +00001281 // If we are supposed to keep comments in #defines, reenable comment saving
1282 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001283 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Chris Lattner141e71f2008-03-09 01:54:53 +00001285 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001286 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Chris Lattner141e71f2008-03-09 01:54:53 +00001288 Token Tok;
1289 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Chris Lattner141e71f2008-03-09 01:54:53 +00001291 // If this is a function-like macro definition, parse the argument list,
1292 // marking each of the identifiers as being used as macro arguments. Also,
1293 // check other constraints on the first token of the macro body.
1294 if (Tok.is(tok::eom)) {
1295 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001296 } else if (Tok.hasLeadingSpace()) {
1297 // This is a normal token with leading space. Clear the leading space
1298 // marker on the first token to get proper expansion.
1299 Tok.clearFlag(Token::LeadingSpace);
1300 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001301 // This is a function-like macro definition. Read the argument list.
1302 MI->setIsFunctionLike();
1303 if (ReadMacroDefinitionArgList(MI)) {
1304 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001305 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001306 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001307 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001308 DiscardUntilEndOfDirective();
1309 return;
1310 }
1311
Chris Lattner8fde5972009-04-19 18:26:34 +00001312 // If this is a definition of a variadic C99 function-like macro, not using
1313 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Chris Lattner8fde5972009-04-19 18:26:34 +00001315 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1316 // This gets unpoisoned where it is allowed.
1317 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1318 if (MI->isC99Varargs())
1319 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Chris Lattner141e71f2008-03-09 01:54:53 +00001321 // Read the first token after the arg list for down below.
1322 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001323 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001324 // C99 requires whitespace between the macro definition and the body. Emit
1325 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001326 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001327 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001328 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1329 // first character of a replacement list is not a character required by
1330 // subclause 5.2.1, then there shall be white-space separation between the
1331 // identifier and the replacement list.". 5.2.1 lists this set:
1332 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1333 // is irrelevant here.
1334 bool isInvalid = false;
1335 if (Tok.is(tok::at)) // @ is not in the list above.
1336 isInvalid = true;
1337 else if (Tok.is(tok::unknown)) {
1338 // If we have an unknown token, it is something strange like "`". Since
1339 // all of valid characters would have lexed into a single character
1340 // token of some sort, we know this is not a valid case.
1341 isInvalid = true;
1342 }
1343 if (isInvalid)
1344 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1345 else
1346 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001347 }
Chris Lattner2451b522009-04-21 04:46:33 +00001348
1349 if (!Tok.is(tok::eom))
1350 LastTok = Tok;
1351
Chris Lattner141e71f2008-03-09 01:54:53 +00001352 // Read the rest of the macro body.
1353 if (MI->isObjectLike()) {
1354 // Object-like macros are very simple, just read their body.
1355 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001356 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001357 MI->AddTokenToBody(Tok);
1358 // Get the next token of the macro.
1359 LexUnexpandedToken(Tok);
1360 }
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Chris Lattner141e71f2008-03-09 01:54:53 +00001362 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001363 // Otherwise, read the body of a function-like macro. While we are at it,
1364 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1365 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001366 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001367 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001368
Chris Lattner141e71f2008-03-09 01:54:53 +00001369 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001370 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Chris Lattner141e71f2008-03-09 01:54:53 +00001372 // Get the next token of the macro.
1373 LexUnexpandedToken(Tok);
1374 continue;
1375 }
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Chris Lattner141e71f2008-03-09 01:54:53 +00001377 // Get the next token of the macro.
1378 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Chris Lattner32404692009-05-25 17:16:10 +00001380 // Check for a valid macro arg identifier.
1381 if (Tok.getIdentifierInfo() == 0 ||
1382 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1383
1384 // If this is assembler-with-cpp mode, we accept random gibberish after
1385 // the '#' because '#' is often a comment character. However, change
1386 // the kind of the token to tok::unknown so that the preprocessor isn't
1387 // confused.
1388 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1389 LastTok.setKind(tok::unknown);
1390 } else {
1391 Diag(Tok, diag::err_pp_stringize_not_parameter);
1392 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Chris Lattner32404692009-05-25 17:16:10 +00001394 // Disable __VA_ARGS__ again.
1395 Ident__VA_ARGS__->setIsPoisoned(true);
1396 return;
1397 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001398 }
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Chris Lattner32404692009-05-25 17:16:10 +00001400 // Things look ok, add the '#' and param name tokens to the macro.
1401 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001402 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001403 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Chris Lattner141e71f2008-03-09 01:54:53 +00001405 // Get the next token of the macro.
1406 LexUnexpandedToken(Tok);
1407 }
1408 }
Mike Stump1eb44332009-09-09 15:08:12 +00001409
1410
Chris Lattner141e71f2008-03-09 01:54:53 +00001411 // Disable __VA_ARGS__ again.
1412 Ident__VA_ARGS__->setIsPoisoned(true);
1413
1414 // Check that there is no paste (##) operator at the begining or end of the
1415 // replacement list.
1416 unsigned NumTokens = MI->getNumTokens();
1417 if (NumTokens != 0) {
1418 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1419 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001420 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001421 return;
1422 }
1423 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1424 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001425 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001426 return;
1427 }
1428 }
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Chris Lattner141e71f2008-03-09 01:54:53 +00001430 // If this is the primary source file, remember that this macro hasn't been
1431 // used yet.
1432 if (isInPrimaryFile())
1433 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001434
1435 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Chris Lattner141e71f2008-03-09 01:54:53 +00001437 // Finally, if this identifier already had a macro defined for it, verify that
1438 // the macro bodies are identical and free the old definition.
1439 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001440 // It is very common for system headers to have tons of macro redefinitions
1441 // and for warnings to be disabled in system headers. If this is the case,
1442 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001443 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001444 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1445 if (!OtherMI->isUsed())
1446 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001447
Chris Lattner41c3ae12009-01-16 19:50:11 +00001448 // Macros must be identical. This means all tokes and whitespace
1449 // separation must be the same. C99 6.10.3.2.
1450 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1451 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1452 << MacroNameTok.getIdentifierInfo();
1453 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1454 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001455 }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Ted Kremenek0ea76722008-12-15 19:56:42 +00001457 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001458 }
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Chris Lattner141e71f2008-03-09 01:54:53 +00001460 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001462 // If the callbacks want to know, tell them about the macro definition.
1463 if (Callbacks)
1464 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001465}
1466
1467/// HandleUndefDirective - Implements #undef.
1468///
1469void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1470 ++NumUndefined;
1471
1472 Token MacroNameTok;
1473 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Chris Lattner141e71f2008-03-09 01:54:53 +00001475 // Error reading macro name? If so, diagnostic already issued.
1476 if (MacroNameTok.is(tok::eom))
1477 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Chris Lattner141e71f2008-03-09 01:54:53 +00001479 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001480 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Chris Lattner141e71f2008-03-09 01:54:53 +00001482 // Okay, we finally have a valid identifier to undef.
1483 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Chris Lattner141e71f2008-03-09 01:54:53 +00001485 // If the macro is not defined, this is a noop undef, just return.
1486 if (MI == 0) return;
1487
1488 if (!MI->isUsed())
1489 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001490
1491 // If the callbacks want to know, tell them about the macro #undef.
1492 if (Callbacks)
1493 Callbacks->MacroUndefined(MacroNameTok.getIdentifierInfo(), MI);
1494
Chris Lattner141e71f2008-03-09 01:54:53 +00001495 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001496 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001497 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1498}
1499
1500
1501//===----------------------------------------------------------------------===//
1502// Preprocessor Conditional Directive Handling.
1503//===----------------------------------------------------------------------===//
1504
1505/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1506/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1507/// if any tokens have been returned or pp-directives activated before this
1508/// #ifndef has been lexed.
1509///
1510void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1511 bool ReadAnyTokensBeforeDirective) {
1512 ++NumIf;
1513 Token DirectiveTok = Result;
1514
1515 Token MacroNameTok;
1516 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Chris Lattner141e71f2008-03-09 01:54:53 +00001518 // Error reading macro name? If so, diagnostic already issued.
1519 if (MacroNameTok.is(tok::eom)) {
1520 // Skip code until we get to #endif. This helps with recovery by not
1521 // emitting an error when the #endif is reached.
1522 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1523 /*Foundnonskip*/false, /*FoundElse*/false);
1524 return;
1525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Chris Lattner141e71f2008-03-09 01:54:53 +00001527 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001528 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001529
Ted Kremenek60e45d42008-11-18 00:34:22 +00001530 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001531 // If the start of a top-level #ifdef, inform MIOpt.
1532 if (!ReadAnyTokensBeforeDirective) {
1533 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001534 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001535 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001536 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001537 }
1538
1539 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1540 MacroInfo *MI = getMacroInfo(MII);
1541
1542 // If there is a macro, process it.
1543 if (MI) // Mark it used.
1544 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Chris Lattner141e71f2008-03-09 01:54:53 +00001546 // Should we include the stuff contained by this directive?
1547 if (!MI == isIfndef) {
1548 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001549 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1550 /*wasskip*/false, /*foundnonskip*/true,
1551 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001552 } else {
1553 // No, skip the contents of this block and return the first token after it.
1554 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001555 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001556 /*FoundElse*/false);
1557 }
1558}
1559
1560/// HandleIfDirective - Implements the #if directive.
1561///
1562void Preprocessor::HandleIfDirective(Token &IfToken,
1563 bool ReadAnyTokensBeforeDirective) {
1564 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Chris Lattner141e71f2008-03-09 01:54:53 +00001566 // Parse and evaluation the conditional expression.
1567 IdentifierInfo *IfNDefMacro = 0;
1568 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Nuno Lopes0049db62008-06-01 18:31:24 +00001570
1571 // If this condition is equivalent to #ifndef X, and if this is the first
1572 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001573 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001574 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001575 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001576 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001577 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001578 }
1579
Chris Lattner141e71f2008-03-09 01:54:53 +00001580 // Should we include the stuff contained by this directive?
1581 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001582 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001583 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001584 /*foundnonskip*/true, /*foundelse*/false);
1585 } else {
1586 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001587 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001588 /*FoundElse*/false);
1589 }
1590}
1591
1592/// HandleEndifDirective - Implements the #endif directive.
1593///
1594void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1595 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Chris Lattner141e71f2008-03-09 01:54:53 +00001597 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001598 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Chris Lattner141e71f2008-03-09 01:54:53 +00001600 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001601 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001602 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001603 Diag(EndifToken, diag::err_pp_endif_without_if);
1604 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001605 }
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Chris Lattner141e71f2008-03-09 01:54:53 +00001607 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001608 if (CurPPLexer->getConditionalStackDepth() == 0)
1609 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Ted Kremenek60e45d42008-11-18 00:34:22 +00001611 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001612 "This code should only be reachable in the non-skipping case!");
1613}
1614
1615
1616void Preprocessor::HandleElseDirective(Token &Result) {
1617 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Chris Lattner141e71f2008-03-09 01:54:53 +00001619 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001620 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Chris Lattner141e71f2008-03-09 01:54:53 +00001622 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001623 if (CurPPLexer->popConditionalLevel(CI)) {
1624 Diag(Result, diag::pp_err_else_without_if);
1625 return;
1626 }
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Chris Lattner141e71f2008-03-09 01:54:53 +00001628 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001629 if (CurPPLexer->getConditionalStackDepth() == 0)
1630 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001631
1632 // If this is a #else with a #else before it, report the error.
1633 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Chris Lattner141e71f2008-03-09 01:54:53 +00001635 // Finally, skip the rest of the contents of this block and return the first
1636 // token after it.
1637 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1638 /*FoundElse*/true);
1639}
1640
1641void Preprocessor::HandleElifDirective(Token &ElifToken) {
1642 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Chris Lattner141e71f2008-03-09 01:54:53 +00001644 // #elif directive in a non-skipping conditional... start skipping.
1645 // We don't care what the condition is, because we will always skip it (since
1646 // the block immediately before it was included).
1647 DiscardUntilEndOfDirective();
1648
1649 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001650 if (CurPPLexer->popConditionalLevel(CI)) {
1651 Diag(ElifToken, diag::pp_err_elif_without_if);
1652 return;
1653 }
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Chris Lattner141e71f2008-03-09 01:54:53 +00001655 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001656 if (CurPPLexer->getConditionalStackDepth() == 0)
1657 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Chris Lattner141e71f2008-03-09 01:54:53 +00001659 // If this is a #elif with a #else before it, report the error.
1660 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1661
1662 // Finally, skip the rest of the contents of this block and return the first
1663 // token after it.
1664 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1665 /*FoundElse*/CI.FoundElse);
1666}
1667