blob: 9cab2d2bfc6e937fbb82574dacbfb00ce101f809 [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) {
Douglas Gregor453091c2010-03-16 22:30:13 +000074 bool Invalid = false;
75 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
76 if (Invalid)
77 return;
78
Chris Lattner9485d232008-12-13 20:12:40 +000079 const IdentifierInfo &Info = Identifiers.get(Spelling);
80 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +000081 // C++ 2.5p2: Alternative tokens behave the same as its primary token
82 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +000083 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000084 else
85 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
86 // Fall through on error.
87 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
88 // Error if defining "defined": C99 6.10.8.4.
89 Diag(MacroNameTok, diag::err_defined_macro_name);
90 } else if (isDefineUndef && II->hasMacroDefinition() &&
91 getMacroInfo(II)->isBuiltinMacro()) {
92 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
93 if (isDefineUndef == 1)
94 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
95 else
96 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
97 } else {
98 // Okay, we got a good identifier node. Return it.
99 return;
100 }
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Chris Lattner141e71f2008-03-09 01:54:53 +0000102 // Invalid macro name, read and discard the rest of the line. Then set the
103 // token kind to tok::eom.
104 MacroNameTok.setKind(tok::eom);
105 return DiscardUntilEndOfDirective();
106}
107
108/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattnerab82f412009-04-17 23:30:53 +0000109/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
110/// true, then we consider macros that expand to zero tokens as being ok.
111void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000112 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000113 // Lex unexpanded tokens for most directives: macros might expand to zero
114 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
115 // #line) allow empty macros.
116 if (EnableMacros)
117 Lex(Tmp);
118 else
119 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattner141e71f2008-03-09 01:54:53 +0000121 // There should be no tokens after the directive, but we allow them as an
122 // extension.
123 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
124 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Chris Lattner141e71f2008-03-09 01:54:53 +0000126 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000127 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
128 // because it is more trouble than it is worth to insert /**/ and check that
129 // there is no /**/ in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000130 FixItHint Hint;
Chris Lattner959875a2009-04-14 05:15:20 +0000131 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
Douglas Gregor849b2432010-03-31 17:46:05 +0000132 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
133 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000134 DiscardUntilEndOfDirective();
135 }
136}
137
138
139
140/// SkipExcludedConditionalBlock - We just read a #if or related directive and
141/// decided that the subsequent tokens are in the #if'd out portion of the
142/// file. Lex the rest of the file, until we see an #endif. If
143/// FoundNonSkipPortion is true, then we have already emitted code for part of
144/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
145/// is true, then #else directives are ok, if not, then we have already seen one
146/// so a #else directive is a duplicate. When this returns, the caller can lex
147/// the first valid token.
148void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
149 bool FoundNonSkipPortion,
150 bool FoundElse) {
151 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000152 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000153
Ted Kremenek60e45d42008-11-18 00:34:22 +0000154 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000155 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000156
Ted Kremenek268ee702008-12-12 18:34:08 +0000157 if (CurPTHLexer) {
158 PTHSkipExcludedConditionalBlock();
159 return;
160 }
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Chris Lattner141e71f2008-03-09 01:54:53 +0000162 // Enter raw mode to disable identifier lookup (and thus macro expansion),
163 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000164 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000165 Token Tok;
166 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000167 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Chris Lattner141e71f2008-03-09 01:54:53 +0000169 // If this is the end of the buffer, we have an error.
170 if (Tok.is(tok::eof)) {
171 // Emit errors for each unterminated conditional on the stack, including
172 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000173 while (!CurPPLexer->ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000174 if (!isCodeCompletionFile(Tok.getLocation()))
175 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
176 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000177 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000178 }
179
Chris Lattner141e71f2008-03-09 01:54:53 +0000180 // Just return and let the caller lex after this #include.
181 break;
182 }
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner141e71f2008-03-09 01:54:53 +0000184 // If this token is not a preprocessor directive, just skip it.
185 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
186 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattner141e71f2008-03-09 01:54:53 +0000188 // We just parsed a # character at the start of a line, so we're in
189 // directive mode. Tell the lexer this so any newlines we see will be
190 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000191 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000192 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000193
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattner141e71f2008-03-09 01:54:53 +0000195 // Read the next token, the directive flavor.
196 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner141e71f2008-03-09 01:54:53 +0000198 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
199 // something bogus), skip it.
200 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000201 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000202 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000203 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000204 continue;
205 }
206
207 // If the first letter isn't i or e, it isn't intesting to us. We know that
208 // this is safe in the face of spelling differences, because there is no way
209 // to spell an i/e in a strange way that is another letter. Skipping this
210 // allows us to avoid looking up the identifier info for #define/#undef and
211 // other common directives.
Douglas Gregora5430162010-03-16 20:46:42 +0000212 bool Invalid = false;
213 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation(),
214 &Invalid);
215 if (Invalid)
216 return;
217
Chris Lattner141e71f2008-03-09 01:54:53 +0000218 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000219 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000220 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000221 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000222 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000223 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000224 continue;
225 }
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattner141e71f2008-03-09 01:54:53 +0000227 // Get the identifier name without trigraphs or embedded newlines. Note
228 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
229 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000230 char DirectiveBuf[20];
231 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000232 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000233 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000234 } else {
235 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000236 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000237 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000238 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000239 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000240 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000241 continue;
242 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000243 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
244 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000247 if (Directive.startswith("if")) {
248 llvm::StringRef Sub = Directive.substr(2);
249 if (Sub.empty() || // "if"
250 Sub == "def" || // "ifdef"
251 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000252 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
253 // bother parsing the condition.
254 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000255 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000256 /*foundnonskip*/false,
257 /*fnddelse*/false);
258 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000259 } else if (Directive[0] == 'e') {
260 llvm::StringRef Sub = Directive.substr(1);
261 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000262 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000263 PPConditionalInfo CondInfo;
264 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000265 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000266 InCond = InCond; // Silence warning in no-asserts mode.
267 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Chris Lattner141e71f2008-03-09 01:54:53 +0000269 // If we popped the outermost skipping block, we're done skipping!
270 if (!CondInfo.WasSkipping)
271 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000272 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000273 // #else directive in a skipping conditional. If not in some other
274 // skipping conditional, and if #else hasn't already been seen, enter it
275 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000276 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000277 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Chris Lattner141e71f2008-03-09 01:54:53 +0000279 // If this is a #else with a #else before it, report the error.
280 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Chris Lattner141e71f2008-03-09 01:54:53 +0000282 // Note that we've seen a #else in this conditional.
283 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Chris Lattner141e71f2008-03-09 01:54:53 +0000285 // If the conditional is at the top level, and the #if block wasn't
286 // entered, enter the #else block now.
287 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
288 CondInfo.FoundNonSkip = true;
289 break;
290 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000291 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000292 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000293
294 bool ShouldEnter;
295 // If this is in a skipping block or if we're already handled this #if
296 // block, don't bother parsing the condition.
297 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
298 DiscardUntilEndOfDirective();
299 ShouldEnter = false;
300 } else {
301 // Restore the value of LexingRawMode so that identifiers are
302 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000303 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
304 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000305 IdentifierInfo *IfNDefMacro = 0;
306 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000307 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000308 }
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Chris Lattner141e71f2008-03-09 01:54:53 +0000310 // If this is a #elif with a #else before it, report the error.
311 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Chris Lattner141e71f2008-03-09 01:54:53 +0000313 // If this condition is true, enter it!
314 if (ShouldEnter) {
315 CondInfo.FoundNonSkip = true;
316 break;
317 }
318 }
319 }
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Ted Kremenek60e45d42008-11-18 00:34:22 +0000321 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000322 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000323 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000324 }
325
326 // Finally, if we are out of the conditional (saw an #endif or ran off the end
327 // of the file, just stop skipping and return to lexing whatever came after
328 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000329 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000330}
331
Ted Kremenek268ee702008-12-12 18:34:08 +0000332void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000333
334 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000335 assert(CurPTHLexer);
336 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Ted Kremenek268ee702008-12-12 18:34:08 +0000338 // Skip to the next '#else', '#elif', or #endif.
339 if (CurPTHLexer->SkipBlock()) {
340 // We have reached an #endif. Both the '#' and 'endif' tokens
341 // have been consumed by the PTHLexer. Just pop off the condition level.
342 PPConditionalInfo CondInfo;
343 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
344 InCond = InCond; // Silence warning in no-asserts mode.
345 assert(!InCond && "Can't be skipping if not in a conditional!");
346 break;
347 }
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Ted Kremenek268ee702008-12-12 18:34:08 +0000349 // We have reached a '#else' or '#elif'. Lex the next token to get
350 // the directive flavor.
351 Token Tok;
352 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Ted Kremenek268ee702008-12-12 18:34:08 +0000354 // We can actually look up the IdentifierInfo here since we aren't in
355 // raw mode.
356 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
357
358 if (K == tok::pp_else) {
359 // #else: Enter the else condition. We aren't in a nested condition
360 // since we skip those. We're always in the one matching the last
361 // blocked we skipped.
362 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
363 // Note that we've seen a #else in this conditional.
364 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Ted Kremenek268ee702008-12-12 18:34:08 +0000366 // If the #if block wasn't entered then enter the #else block now.
367 if (!CondInfo.FoundNonSkip) {
368 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000370 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000371 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000372 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000373 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Ted Kremenek268ee702008-12-12 18:34:08 +0000375 break;
376 }
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Ted Kremenek268ee702008-12-12 18:34:08 +0000378 // Otherwise skip this block.
379 continue;
380 }
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Ted Kremenek268ee702008-12-12 18:34:08 +0000382 assert(K == tok::pp_elif);
383 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
384
385 // If this is a #elif with a #else before it, report the error.
386 if (CondInfo.FoundElse)
387 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Ted Kremenek268ee702008-12-12 18:34:08 +0000389 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000390 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000391 if (CondInfo.FoundNonSkip)
392 continue;
393
394 // Evaluate the condition of the #elif.
395 IdentifierInfo *IfNDefMacro = 0;
396 CurPTHLexer->ParsingPreprocessorDirective = true;
397 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
398 CurPTHLexer->ParsingPreprocessorDirective = false;
399
400 // If this condition is true, enter it!
401 if (ShouldEnter) {
402 CondInfo.FoundNonSkip = true;
403 break;
404 }
405
406 // Otherwise, skip this block and go to the next one.
407 continue;
408 }
409}
410
Chris Lattner10725092008-03-09 04:17:44 +0000411/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
412/// return null on failure. isAngled indicates whether the file reference is
413/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnera1394812010-01-10 01:35:12 +0000414const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattner10725092008-03-09 04:17:44 +0000415 bool isAngled,
416 const DirectoryLookup *FromDir,
417 const DirectoryLookup *&CurDir) {
418 // If the header lookup mechanism may be relative to the current file, pass in
419 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000420 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000421 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000422 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000423 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000425 // If there is no file entry associated with this file, it must be the
426 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000427 // it won't be scanned for preprocessor directives. If we have the
428 // predefines buffer, resolve #include references (which come from the
429 // -include command line argument) as if they came from the main file, this
430 // affects file lookup etc.
431 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000432 FID = SourceMgr.getMainFileID();
433 CurFileEnt = SourceMgr.getFileEntryForID(FID);
434 }
Chris Lattner10725092008-03-09 04:17:44 +0000435 }
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Chris Lattner10725092008-03-09 04:17:44 +0000437 // Do a standard file entry lookup.
438 CurDir = CurDirLookup;
439 const FileEntry *FE =
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000440 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000441 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Chris Lattner10725092008-03-09 04:17:44 +0000443 // Otherwise, see if this is a subframework header. If so, this is relative
444 // to one of the headers on the #include stack. Walk the list of the current
445 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000446 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000447 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000448 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000449 return FE;
450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Chris Lattner10725092008-03-09 04:17:44 +0000452 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
453 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000454 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000455 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000456 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000457 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000458 return FE;
459 }
460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner10725092008-03-09 04:17:44 +0000462 // Otherwise, we really couldn't find the file.
463 return 0;
464}
465
Chris Lattner141e71f2008-03-09 01:54:53 +0000466
467//===----------------------------------------------------------------------===//
468// Preprocessor Directive Handling.
469//===----------------------------------------------------------------------===//
470
471/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000472/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000473/// lexer/preprocessor state, and advances the lexer(s) so that the next token
474/// read is the correct one.
475void Preprocessor::HandleDirective(Token &Result) {
476 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Chris Lattner141e71f2008-03-09 01:54:53 +0000478 // We just parsed a # character at the start of a line, so we're in directive
479 // mode. Tell the lexer this so any newlines we see will be converted into an
480 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000481 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Chris Lattner141e71f2008-03-09 01:54:53 +0000483 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000484
Chris Lattner141e71f2008-03-09 01:54:53 +0000485 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000486 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000487 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000488 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Chris Lattner42aa16c2009-03-18 21:00:25 +0000490 // Save the '#' token in case we need to return it later.
491 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Chris Lattner141e71f2008-03-09 01:54:53 +0000493 // Read the next token, the directive flavor. This isn't expanded due to
494 // C99 6.10.3p8.
495 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Chris Lattner141e71f2008-03-09 01:54:53 +0000497 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
498 // #define A(x) #x
499 // A(abc
500 // #warning blah
501 // def)
502 // If so, the user is relying on non-portable behavior, emit a diagnostic.
503 if (InMacroArgs)
504 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Chris Lattner141e71f2008-03-09 01:54:53 +0000506TryAgain:
507 switch (Result.getKind()) {
508 case tok::eom:
509 return; // null directive.
510 case tok::comment:
511 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
512 LexUnexpandedToken(Result);
513 goto TryAgain;
514
Chris Lattner478a18e2009-01-26 06:19:46 +0000515 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000516 if (getLangOptions().AsmPreprocessor)
517 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000518 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000519 default:
520 IdentifierInfo *II = Result.getIdentifierInfo();
521 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattner141e71f2008-03-09 01:54:53 +0000523 // Ask what the preprocessor keyword ID is.
524 switch (II->getPPKeywordID()) {
525 default: break;
526 // C99 6.10.1 - Conditional Inclusion.
527 case tok::pp_if:
528 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
529 case tok::pp_ifdef:
530 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
531 case tok::pp_ifndef:
532 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
533 case tok::pp_elif:
534 return HandleElifDirective(Result);
535 case tok::pp_else:
536 return HandleElseDirective(Result);
537 case tok::pp_endif:
538 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Chris Lattner141e71f2008-03-09 01:54:53 +0000540 // C99 6.10.2 - Source File Inclusion.
541 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000542 return HandleIncludeDirective(Result); // Handle #include.
543 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000544 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattner141e71f2008-03-09 01:54:53 +0000546 // C99 6.10.3 - Macro Replacement.
547 case tok::pp_define:
548 return HandleDefineDirective(Result);
549 case tok::pp_undef:
550 return HandleUndefDirective(Result);
551
552 // C99 6.10.4 - Line Control.
553 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000554 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Chris Lattner141e71f2008-03-09 01:54:53 +0000556 // C99 6.10.5 - Error Directive.
557 case tok::pp_error:
558 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner141e71f2008-03-09 01:54:53 +0000560 // C99 6.10.6 - Pragma Directive.
561 case tok::pp_pragma:
562 return HandlePragmaDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattner141e71f2008-03-09 01:54:53 +0000564 // GNU Extensions.
565 case tok::pp_import:
566 return HandleImportDirective(Result);
567 case tok::pp_include_next:
568 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattner141e71f2008-03-09 01:54:53 +0000570 case tok::pp_warning:
571 Diag(Result, diag::ext_pp_warning_directive);
572 return HandleUserDiagnosticDirective(Result, true);
573 case tok::pp_ident:
574 return HandleIdentSCCSDirective(Result);
575 case tok::pp_sccs:
576 return HandleIdentSCCSDirective(Result);
577 case tok::pp_assert:
578 //isExtension = true; // FIXME: implement #assert
579 break;
580 case tok::pp_unassert:
581 //isExtension = true; // FIXME: implement #unassert
582 break;
583 }
584 break;
585 }
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner42aa16c2009-03-18 21:00:25 +0000587 // If this is a .S file, treat unknown # directives as non-preprocessor
588 // directives. This is important because # may be a comment or introduce
589 // various pseudo-ops. Just return the # token and push back the following
590 // token to be lexed next time.
591 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000592 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000593 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000594 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000595 Toks[1] = Result;
596 // Enter this token stream so that we re-lex the tokens. Make sure to
597 // enable macro expansion, in case the token after the # is an identifier
598 // that is expanded.
599 EnterTokenStream(Toks, 2, false, true);
600 return;
601 }
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Chris Lattner141e71f2008-03-09 01:54:53 +0000603 // If we reached here, the preprocessing token is not valid!
604 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Chris Lattner141e71f2008-03-09 01:54:53 +0000606 // Read the rest of the PP line.
607 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattner141e71f2008-03-09 01:54:53 +0000609 // Okay, we're done parsing the directive.
610}
611
Chris Lattner478a18e2009-01-26 06:19:46 +0000612/// GetLineValue - Convert a numeric token into an unsigned value, emitting
613/// Diagnostic DiagID if it is invalid, and returning the value in Val.
614static bool GetLineValue(Token &DigitTok, unsigned &Val,
615 unsigned DiagID, Preprocessor &PP) {
616 if (DigitTok.isNot(tok::numeric_constant)) {
617 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Chris Lattner478a18e2009-01-26 06:19:46 +0000619 if (DigitTok.isNot(tok::eom))
620 PP.DiscardUntilEndOfDirective();
621 return true;
622 }
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattner478a18e2009-01-26 06:19:46 +0000624 llvm::SmallString<64> IntegerBuffer;
625 IntegerBuffer.resize(DigitTok.getLength());
626 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000627 bool Invalid = false;
628 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
629 if (Invalid)
630 return true;
631
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000632 // Verify that we have a simple digit-sequence, and compute the value. This
633 // is always a simple digit string computed in decimal, so we do this manually
634 // here.
635 Val = 0;
636 for (unsigned i = 0; i != ActualLength; ++i) {
637 if (!isdigit(DigitTokBegin[i])) {
638 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
639 diag::err_pp_line_digit_sequence);
640 PP.DiscardUntilEndOfDirective();
641 return true;
642 }
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000644 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
645 if (NextVal < Val) { // overflow.
646 PP.Diag(DigitTok, DiagID);
647 PP.DiscardUntilEndOfDirective();
648 return true;
649 }
650 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000651 }
Mike Stump1eb44332009-09-09 15:08:12 +0000652
653 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000654 if (Val == 0) {
655 PP.Diag(DigitTok, DiagID);
656 PP.DiscardUntilEndOfDirective();
657 return true;
658 }
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000660 if (DigitTokBegin[0] == '0')
661 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner478a18e2009-01-26 06:19:46 +0000663 return false;
664}
665
Mike Stump1eb44332009-09-09 15:08:12 +0000666/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000667/// acceptable forms are:
668/// # line digit-sequence
669/// # line digit-sequence "s-char-sequence"
670void Preprocessor::HandleLineDirective(Token &Tok) {
671 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
672 // expanded.
673 Token DigitTok;
674 Lex(DigitTok);
675
Chris Lattner359cc442009-01-26 05:29:08 +0000676 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000677 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000678 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000679 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000680
Chris Lattner478a18e2009-01-26 06:19:46 +0000681 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
682 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000683 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
684 if (LineNo >= LineLimit)
685 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Chris Lattner5b9a5042009-01-26 07:57:50 +0000687 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000688 Token StrTok;
689 Lex(StrTok);
690
691 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
692 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000693 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000694 ; // ok
695 else if (StrTok.isNot(tok::string_literal)) {
696 Diag(StrTok, diag::err_pp_line_invalid_filename);
697 DiscardUntilEndOfDirective();
698 return;
699 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000700 // Parse and validate the string, converting it into a unique ID.
701 StringLiteralParser Literal(&StrTok, 1, *this);
702 assert(!Literal.AnyWide && "Didn't allow wide strings in");
703 if (Literal.hadError)
704 return DiscardUntilEndOfDirective();
705 if (Literal.Pascal) {
706 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
707 return DiscardUntilEndOfDirective();
708 }
709 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
710 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattnerab82f412009-04-17 23:30:53 +0000712 // Verify that there is nothing after the string, other than EOM. Because
713 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
714 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000715 }
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattner4c4ea172009-02-03 21:52:55 +0000717 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Chris Lattner16629382009-03-27 17:13:49 +0000719 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000720 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
721 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000722 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000723}
724
Chris Lattner478a18e2009-01-26 06:19:46 +0000725/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
726/// marker directive.
727static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
728 bool &IsSystemHeader, bool &IsExternCHeader,
729 Preprocessor &PP) {
730 unsigned FlagVal;
731 Token FlagTok;
732 PP.Lex(FlagTok);
733 if (FlagTok.is(tok::eom)) return false;
734 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
735 return true;
736
737 if (FlagVal == 1) {
738 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattner478a18e2009-01-26 06:19:46 +0000740 PP.Lex(FlagTok);
741 if (FlagTok.is(tok::eom)) return false;
742 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
743 return true;
744 } else if (FlagVal == 2) {
745 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Chris Lattner137b6a62009-02-04 06:25:26 +0000747 SourceManager &SM = PP.getSourceManager();
748 // If we are leaving the current presumed file, check to make sure the
749 // presumed include stack isn't empty!
750 FileID CurFileID =
751 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
752 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Chris Lattner137b6a62009-02-04 06:25:26 +0000754 // If there is no include loc (main file) or if the include loc is in a
755 // different physical file, then we aren't in a "1" line marker flag region.
756 SourceLocation IncLoc = PLoc.getIncludeLoc();
757 if (IncLoc.isInvalid() ||
758 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
759 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
760 PP.DiscardUntilEndOfDirective();
761 return true;
762 }
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Chris Lattner478a18e2009-01-26 06:19:46 +0000764 PP.Lex(FlagTok);
765 if (FlagTok.is(tok::eom)) return false;
766 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
767 return true;
768 }
769
770 // We must have 3 if there are still flags.
771 if (FlagVal != 3) {
772 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000773 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000774 return true;
775 }
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Chris Lattner478a18e2009-01-26 06:19:46 +0000777 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Chris Lattner478a18e2009-01-26 06:19:46 +0000779 PP.Lex(FlagTok);
780 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000781 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000782 return true;
783
784 // We must have 4 if there is yet another flag.
785 if (FlagVal != 4) {
786 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000787 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000788 return true;
789 }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Chris Lattner478a18e2009-01-26 06:19:46 +0000791 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chris Lattner478a18e2009-01-26 06:19:46 +0000793 PP.Lex(FlagTok);
794 if (FlagTok.is(tok::eom)) return false;
795
796 // There are no more valid flags here.
797 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000798 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000799 return true;
800}
801
802/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
803/// one of the following forms:
804///
805/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000806/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000807/// # 42 "file" ('1' | '2')? '3' '4'?
808///
809void Preprocessor::HandleDigitDirective(Token &DigitTok) {
810 // Validate the number and convert it to an unsigned. GNU does not have a
811 // line # limit other than it fit in 32-bits.
812 unsigned LineNo;
813 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
814 *this))
815 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Chris Lattner478a18e2009-01-26 06:19:46 +0000817 Token StrTok;
818 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Chris Lattner478a18e2009-01-26 06:19:46 +0000820 bool IsFileEntry = false, IsFileExit = false;
821 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000822 int FilenameID = -1;
823
Chris Lattner478a18e2009-01-26 06:19:46 +0000824 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
825 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000826 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000827 ; // ok
828 else if (StrTok.isNot(tok::string_literal)) {
829 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000830 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000831 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000832 // Parse and validate the string, converting it into a unique ID.
833 StringLiteralParser Literal(&StrTok, 1, *this);
834 assert(!Literal.AnyWide && "Didn't allow wide strings in");
835 if (Literal.hadError)
836 return DiscardUntilEndOfDirective();
837 if (Literal.Pascal) {
838 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
839 return DiscardUntilEndOfDirective();
840 }
841 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
842 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Chris Lattner478a18e2009-01-26 06:19:46 +0000844 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000845 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000846 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000847 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000848 }
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Chris Lattner9d79eba2009-02-04 05:21:58 +0000850 // Create a line note with this information.
851 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000852 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000853 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Chris Lattner16629382009-03-27 17:13:49 +0000855 // If the preprocessor has callbacks installed, notify them of the #line
856 // change. This is used so that the line marker comes out in -E mode for
857 // example.
858 if (Callbacks) {
859 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
860 if (IsFileEntry)
861 Reason = PPCallbacks::EnterFile;
862 else if (IsFileExit)
863 Reason = PPCallbacks::ExitFile;
864 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
865 if (IsExternCHeader)
866 FileKind = SrcMgr::C_ExternCSystem;
867 else if (IsSystemHeader)
868 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Chris Lattner86d0ef72010-04-14 04:28:50 +0000870 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000871 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000872}
873
874
Chris Lattner099dd052009-01-26 05:30:54 +0000875/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
876///
Mike Stump1eb44332009-09-09 15:08:12 +0000877void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000878 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000879 // PTH doesn't emit #warning or #error directives.
880 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000881 return CurPTHLexer->DiscardToEndOfLine();
882
Chris Lattner141e71f2008-03-09 01:54:53 +0000883 // Read the rest of the line raw. We do this because we don't want macros
884 // to be expanded and we don't require that the tokens be valid preprocessing
885 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
886 // collapse multiple consequtive white space between tokens, but this isn't
887 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000888 std::string Message = CurLexer->ReadToEndOfLine();
889 if (isWarning)
890 Diag(Tok, diag::pp_hash_warning) << Message;
891 else
892 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000893}
894
895/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
896///
897void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
898 // Yes, this directive is an extension.
899 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chris Lattner141e71f2008-03-09 01:54:53 +0000901 // Read the string argument.
902 Token StrTok;
903 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Chris Lattner141e71f2008-03-09 01:54:53 +0000905 // If the token kind isn't a string, it's a malformed directive.
906 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000907 StrTok.isNot(tok::wide_string_literal)) {
908 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000909 if (StrTok.isNot(tok::eom))
910 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000911 return;
912 }
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Chris Lattner141e71f2008-03-09 01:54:53 +0000914 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000915 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000916
Douglas Gregor453091c2010-03-16 22:30:13 +0000917 if (Callbacks) {
918 bool Invalid = false;
919 std::string Str = getSpelling(StrTok, &Invalid);
920 if (!Invalid)
921 Callbacks->Ident(Tok.getLocation(), Str);
922 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000923}
924
925//===----------------------------------------------------------------------===//
926// Preprocessor Include Directive Handling.
927//===----------------------------------------------------------------------===//
928
929/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
930/// checked and spelled filename, e.g. as an operand of #include. This returns
931/// true if the input filename was in <>'s or false if it were in ""'s. The
932/// caller is expected to provide a buffer that is large enough to hold the
933/// spelling of the filename, but is also expected to handle the case when
934/// this method decides to use a different buffer.
935bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000936 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000937 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000938 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattner141e71f2008-03-09 01:54:53 +0000940 // Make sure the filename is <x> or "x".
941 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000942 if (Buffer[0] == '<') {
943 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000944 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 }
948 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +0000949 } else if (Buffer[0] == '"') {
950 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000951 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000952 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000953 return true;
954 }
955 isAngled = false;
956 } else {
957 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000958 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000959 return true;
960 }
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Chris Lattner141e71f2008-03-09 01:54:53 +0000962 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +0000963 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000964 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000965 Buffer = llvm::StringRef();
966 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000967 }
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Chris Lattner141e71f2008-03-09 01:54:53 +0000969 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +0000970 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +0000971 return isAngled;
972}
973
974/// ConcatenateIncludeName - Handle cases where the #include name is expanded
975/// from a macro as multiple tokens, which need to be glued together. This
976/// occurs for code like:
977/// #define FOO <a/b.h>
978/// #include FOO
979/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
980///
981/// This code concatenates and consumes tokens up to the '>' token. It returns
982/// false if the > was found, otherwise it returns true if it finds and consumes
983/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +0000984bool Preprocessor::ConcatenateIncludeName(
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000985 llvm::SmallString<128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000986 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +0000987
John Thompsona28cc092009-10-30 13:49:06 +0000988 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000989 while (CurTok.isNot(tok::eom)) {
990 // Append the spelling of this token to the buffer. If there was a space
991 // before it, add it now.
992 if (CurTok.hasLeadingSpace())
993 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Chris Lattner141e71f2008-03-09 01:54:53 +0000995 // Get the spelling of the token, directly into FilenameBuffer if possible.
996 unsigned PreAppendSize = FilenameBuffer.size();
997 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner141e71f2008-03-09 01:54:53 +0000999 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001000 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chris Lattner141e71f2008-03-09 01:54:53 +00001002 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1003 if (BufPtr != &FilenameBuffer[PreAppendSize])
1004 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chris Lattner141e71f2008-03-09 01:54:53 +00001006 // Resize FilenameBuffer to the correct size.
1007 if (CurTok.getLength() != ActualLen)
1008 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Chris Lattner141e71f2008-03-09 01:54:53 +00001010 // If we found the '>' marker, return success.
1011 if (CurTok.is(tok::greater))
1012 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001013
John Thompsona28cc092009-10-30 13:49:06 +00001014 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001015 }
1016
1017 // If we hit the eom marker, emit an error and return true so that the caller
1018 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001019 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001020 return true;
1021}
1022
1023/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1024/// file to be included from the lexer, then include it! This is a common
1025/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001026/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001027/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001028void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1029 const DirectoryLookup *LookupFrom,
1030 bool isImport) {
1031
1032 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001033 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Chris Lattner141e71f2008-03-09 01:54:53 +00001035 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001036 llvm::SmallString<128> FilenameBuffer;
1037 llvm::StringRef Filename;
Chris Lattner141e71f2008-03-09 01:54:53 +00001038
1039 switch (FilenameTok.getKind()) {
1040 case tok::eom:
1041 // If the token kind is EOM, the error has already been diagnosed.
1042 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Chris Lattner141e71f2008-03-09 01:54:53 +00001044 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001045 case tok::string_literal:
1046 Filename = getSpelling(FilenameTok, FilenameBuffer);
Chris Lattner141e71f2008-03-09 01:54:53 +00001047 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Chris Lattner141e71f2008-03-09 01:54:53 +00001049 case tok::less:
1050 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1051 // case, glue the tokens together into FilenameBuffer and interpret those.
1052 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001053 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001054 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001055 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001056 break;
1057 default:
1058 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1059 DiscardUntilEndOfDirective();
1060 return;
1061 }
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001063 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001064 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001065 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1066 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001067 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001068 DiscardUntilEndOfDirective();
1069 return;
1070 }
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001072 // Verify that there is nothing after the filename, other than EOM. Note that
1073 // we allow macros that expand to nothing after the filename, because this
1074 // falls into the category of "#include pp-tokens new-line" specified in
1075 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001076 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001077
1078 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001079 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1080 Diag(FilenameTok, diag::err_pp_include_too_deep);
1081 return;
1082 }
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Chris Lattner141e71f2008-03-09 01:54:53 +00001084 // Search include directories.
1085 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +00001086 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001087 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001088 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001089 return;
1090 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001091
Chris Lattner72181832008-09-26 20:12:23 +00001092 // The #included file will be considered to be a system header if either it is
1093 // in a system include directory, or if the #includer is a system include
1094 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001095 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001096 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001097 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001099 // Ask HeaderInfo if we should enter this #include file. If not, #including
1100 // this file will have no effect.
1101 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001102 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001103 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001104 return;
1105 }
1106
Chris Lattner141e71f2008-03-09 01:54:53 +00001107 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001108 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1109 FileCharacter);
1110 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001111 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001112 return;
1113 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001114
1115 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001116 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001117}
1118
1119/// HandleIncludeNextDirective - Implements #include_next.
1120///
1121void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1122 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner141e71f2008-03-09 01:54:53 +00001124 // #include_next is like #include, except that we start searching after
1125 // the current found directory. If we can't do this, issue a
1126 // diagnostic.
1127 const DirectoryLookup *Lookup = CurDirLookup;
1128 if (isInPrimaryFile()) {
1129 Lookup = 0;
1130 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1131 } else if (Lookup == 0) {
1132 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1133 } else {
1134 // Start looking up in the next directory.
1135 ++Lookup;
1136 }
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Chris Lattner141e71f2008-03-09 01:54:53 +00001138 return HandleIncludeDirective(IncludeNextTok, Lookup);
1139}
1140
1141/// HandleImportDirective - Implements #import.
1142///
1143void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001144 if (!Features.ObjC1) // #import is standard for ObjC.
1145 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Chris Lattner141e71f2008-03-09 01:54:53 +00001147 return HandleIncludeDirective(ImportTok, 0, true);
1148}
1149
Chris Lattnerde076652009-04-08 18:46:40 +00001150/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1151/// pseudo directive in the predefines buffer. This handles it by sucking all
1152/// tokens through the preprocessor and discarding them (only keeping the side
1153/// effects on the preprocessor).
1154void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1155 // This directive should only occur in the predefines buffer. If not, emit an
1156 // error and reject it.
1157 SourceLocation Loc = IncludeMacrosTok.getLocation();
1158 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1159 Diag(IncludeMacrosTok.getLocation(),
1160 diag::pp_include_macros_out_of_predefines);
1161 DiscardUntilEndOfDirective();
1162 return;
1163 }
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Chris Lattnerfd105112009-04-08 20:53:24 +00001165 // Treat this as a normal #include for checking purposes. If this is
1166 // successful, it will push a new lexer onto the include stack.
1167 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Chris Lattnerfd105112009-04-08 20:53:24 +00001169 Token TmpTok;
1170 do {
1171 Lex(TmpTok);
1172 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1173 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001174}
1175
Chris Lattner141e71f2008-03-09 01:54:53 +00001176//===----------------------------------------------------------------------===//
1177// Preprocessor Macro Directive Handling.
1178//===----------------------------------------------------------------------===//
1179
1180/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1181/// definition has just been read. Lex the rest of the arguments and the
1182/// closing ), updating MI with what we learn. Return true if an error occurs
1183/// parsing the arg list.
1184bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1185 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chris Lattner141e71f2008-03-09 01:54:53 +00001187 Token Tok;
1188 while (1) {
1189 LexUnexpandedToken(Tok);
1190 switch (Tok.getKind()) {
1191 case tok::r_paren:
1192 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001193 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001194 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001195 // Otherwise we have #define FOO(A,)
1196 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1197 return true;
1198 case tok::ellipsis: // #define X(... -> C99 varargs
1199 // Warn if use of C99 feature in non-C99 mode.
1200 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1201
1202 // Lex the token after the identifier.
1203 LexUnexpandedToken(Tok);
1204 if (Tok.isNot(tok::r_paren)) {
1205 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1206 return true;
1207 }
1208 // Add the __VA_ARGS__ identifier as an argument.
1209 Arguments.push_back(Ident__VA_ARGS__);
1210 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001211 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001212 return false;
1213 case tok::eom: // #define X(
1214 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1215 return true;
1216 default:
1217 // Handle keywords and identifiers here to accept things like
1218 // #define Foo(for) for.
1219 IdentifierInfo *II = Tok.getIdentifierInfo();
1220 if (II == 0) {
1221 // #define X(1
1222 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1223 return true;
1224 }
1225
1226 // If this is already used as an argument, it is used multiple times (e.g.
1227 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001228 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001229 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001230 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001231 return true;
1232 }
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Chris Lattner141e71f2008-03-09 01:54:53 +00001234 // Add the argument to the macro info.
1235 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Chris Lattner141e71f2008-03-09 01:54:53 +00001237 // Lex the token after the identifier.
1238 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Chris Lattner141e71f2008-03-09 01:54:53 +00001240 switch (Tok.getKind()) {
1241 default: // #define X(A B
1242 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1243 return true;
1244 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001245 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001246 return false;
1247 case tok::comma: // #define X(A,
1248 break;
1249 case tok::ellipsis: // #define X(A... -> GCC extension
1250 // Diagnose extension.
1251 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Chris Lattner141e71f2008-03-09 01:54:53 +00001253 // Lex the token after the identifier.
1254 LexUnexpandedToken(Tok);
1255 if (Tok.isNot(tok::r_paren)) {
1256 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1257 return true;
1258 }
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Chris Lattner141e71f2008-03-09 01:54:53 +00001260 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001261 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001262 return false;
1263 }
1264 }
1265 }
1266}
1267
1268/// HandleDefineDirective - Implements #define. This consumes the entire macro
1269/// line then lets the caller lex the next real token.
1270void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1271 ++NumDefined;
1272
1273 Token MacroNameTok;
1274 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Chris Lattner141e71f2008-03-09 01:54:53 +00001276 // Error reading macro name? If so, diagnostic already issued.
1277 if (MacroNameTok.is(tok::eom))
1278 return;
1279
Chris Lattner2451b522009-04-21 04:46:33 +00001280 Token LastTok = MacroNameTok;
1281
Chris Lattner141e71f2008-03-09 01:54:53 +00001282 // If we are supposed to keep comments in #defines, reenable comment saving
1283 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001284 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Chris Lattner141e71f2008-03-09 01:54:53 +00001286 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001287 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Chris Lattner141e71f2008-03-09 01:54:53 +00001289 Token Tok;
1290 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Chris Lattner141e71f2008-03-09 01:54:53 +00001292 // If this is a function-like macro definition, parse the argument list,
1293 // marking each of the identifiers as being used as macro arguments. Also,
1294 // check other constraints on the first token of the macro body.
1295 if (Tok.is(tok::eom)) {
1296 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001297 } else if (Tok.hasLeadingSpace()) {
1298 // This is a normal token with leading space. Clear the leading space
1299 // marker on the first token to get proper expansion.
1300 Tok.clearFlag(Token::LeadingSpace);
1301 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001302 // This is a function-like macro definition. Read the argument list.
1303 MI->setIsFunctionLike();
1304 if (ReadMacroDefinitionArgList(MI)) {
1305 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001306 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001307 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001308 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001309 DiscardUntilEndOfDirective();
1310 return;
1311 }
1312
Chris Lattner8fde5972009-04-19 18:26:34 +00001313 // If this is a definition of a variadic C99 function-like macro, not using
1314 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Chris Lattner8fde5972009-04-19 18:26:34 +00001316 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1317 // This gets unpoisoned where it is allowed.
1318 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1319 if (MI->isC99Varargs())
1320 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Chris Lattner141e71f2008-03-09 01:54:53 +00001322 // Read the first token after the arg list for down below.
1323 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001324 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001325 // C99 requires whitespace between the macro definition and the body. Emit
1326 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001327 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001328 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001329 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1330 // first character of a replacement list is not a character required by
1331 // subclause 5.2.1, then there shall be white-space separation between the
1332 // identifier and the replacement list.". 5.2.1 lists this set:
1333 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1334 // is irrelevant here.
1335 bool isInvalid = false;
1336 if (Tok.is(tok::at)) // @ is not in the list above.
1337 isInvalid = true;
1338 else if (Tok.is(tok::unknown)) {
1339 // If we have an unknown token, it is something strange like "`". Since
1340 // all of valid characters would have lexed into a single character
1341 // token of some sort, we know this is not a valid case.
1342 isInvalid = true;
1343 }
1344 if (isInvalid)
1345 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1346 else
1347 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001348 }
Chris Lattner2451b522009-04-21 04:46:33 +00001349
1350 if (!Tok.is(tok::eom))
1351 LastTok = Tok;
1352
Chris Lattner141e71f2008-03-09 01:54:53 +00001353 // Read the rest of the macro body.
1354 if (MI->isObjectLike()) {
1355 // Object-like macros are very simple, just read their body.
1356 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001357 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001358 MI->AddTokenToBody(Tok);
1359 // Get the next token of the macro.
1360 LexUnexpandedToken(Tok);
1361 }
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Chris Lattner141e71f2008-03-09 01:54:53 +00001363 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001364 // Otherwise, read the body of a function-like macro. While we are at it,
1365 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1366 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001367 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001368 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001369
Chris Lattner141e71f2008-03-09 01:54:53 +00001370 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001371 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Chris Lattner141e71f2008-03-09 01:54:53 +00001373 // Get the next token of the macro.
1374 LexUnexpandedToken(Tok);
1375 continue;
1376 }
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Chris Lattner141e71f2008-03-09 01:54:53 +00001378 // Get the next token of the macro.
1379 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Chris Lattner32404692009-05-25 17:16:10 +00001381 // Check for a valid macro arg identifier.
1382 if (Tok.getIdentifierInfo() == 0 ||
1383 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1384
1385 // If this is assembler-with-cpp mode, we accept random gibberish after
1386 // the '#' because '#' is often a comment character. However, change
1387 // the kind of the token to tok::unknown so that the preprocessor isn't
1388 // confused.
1389 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1390 LastTok.setKind(tok::unknown);
1391 } else {
1392 Diag(Tok, diag::err_pp_stringize_not_parameter);
1393 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Chris Lattner32404692009-05-25 17:16:10 +00001395 // Disable __VA_ARGS__ again.
1396 Ident__VA_ARGS__->setIsPoisoned(true);
1397 return;
1398 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001399 }
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Chris Lattner32404692009-05-25 17:16:10 +00001401 // Things look ok, add the '#' and param name tokens to the macro.
1402 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001403 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001404 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Chris Lattner141e71f2008-03-09 01:54:53 +00001406 // Get the next token of the macro.
1407 LexUnexpandedToken(Tok);
1408 }
1409 }
Mike Stump1eb44332009-09-09 15:08:12 +00001410
1411
Chris Lattner141e71f2008-03-09 01:54:53 +00001412 // Disable __VA_ARGS__ again.
1413 Ident__VA_ARGS__->setIsPoisoned(true);
1414
1415 // Check that there is no paste (##) operator at the begining or end of the
1416 // replacement list.
1417 unsigned NumTokens = MI->getNumTokens();
1418 if (NumTokens != 0) {
1419 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1420 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001421 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001422 return;
1423 }
1424 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1425 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001426 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001427 return;
1428 }
1429 }
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Chris Lattner141e71f2008-03-09 01:54:53 +00001431 // If this is the primary source file, remember that this macro hasn't been
1432 // used yet.
1433 if (isInPrimaryFile())
1434 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001435
1436 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Chris Lattner141e71f2008-03-09 01:54:53 +00001438 // Finally, if this identifier already had a macro defined for it, verify that
1439 // the macro bodies are identical and free the old definition.
1440 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001441 // It is very common for system headers to have tons of macro redefinitions
1442 // and for warnings to be disabled in system headers. If this is the case,
1443 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001444 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001445 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1446 if (!OtherMI->isUsed())
1447 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001448
Chris Lattner41c3ae12009-01-16 19:50:11 +00001449 // Macros must be identical. This means all tokes and whitespace
1450 // separation must be the same. C99 6.10.3.2.
1451 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1452 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1453 << MacroNameTok.getIdentifierInfo();
1454 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1455 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001456 }
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Ted Kremenek0ea76722008-12-15 19:56:42 +00001458 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001459 }
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Chris Lattner141e71f2008-03-09 01:54:53 +00001461 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001463 // If the callbacks want to know, tell them about the macro definition.
1464 if (Callbacks)
1465 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001466}
1467
1468/// HandleUndefDirective - Implements #undef.
1469///
1470void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1471 ++NumUndefined;
1472
1473 Token MacroNameTok;
1474 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Chris Lattner141e71f2008-03-09 01:54:53 +00001476 // Error reading macro name? If so, diagnostic already issued.
1477 if (MacroNameTok.is(tok::eom))
1478 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Chris Lattner141e71f2008-03-09 01:54:53 +00001480 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001481 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Chris Lattner141e71f2008-03-09 01:54:53 +00001483 // Okay, we finally have a valid identifier to undef.
1484 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Chris Lattner141e71f2008-03-09 01:54:53 +00001486 // If the macro is not defined, this is a noop undef, just return.
1487 if (MI == 0) return;
1488
1489 if (!MI->isUsed())
1490 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001491
1492 // If the callbacks want to know, tell them about the macro #undef.
1493 if (Callbacks)
Benjamin Kramer2f054492010-08-07 22:27:00 +00001494 Callbacks->MacroUndefined(MacroNameTok.getLocation(),
1495 MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001496
Chris Lattner141e71f2008-03-09 01:54:53 +00001497 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001498 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001499 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1500}
1501
1502
1503//===----------------------------------------------------------------------===//
1504// Preprocessor Conditional Directive Handling.
1505//===----------------------------------------------------------------------===//
1506
1507/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1508/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1509/// if any tokens have been returned or pp-directives activated before this
1510/// #ifndef has been lexed.
1511///
1512void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1513 bool ReadAnyTokensBeforeDirective) {
1514 ++NumIf;
1515 Token DirectiveTok = Result;
1516
1517 Token MacroNameTok;
1518 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Chris Lattner141e71f2008-03-09 01:54:53 +00001520 // Error reading macro name? If so, diagnostic already issued.
1521 if (MacroNameTok.is(tok::eom)) {
1522 // Skip code until we get to #endif. This helps with recovery by not
1523 // emitting an error when the #endif is reached.
1524 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1525 /*Foundnonskip*/false, /*FoundElse*/false);
1526 return;
1527 }
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Chris Lattner141e71f2008-03-09 01:54:53 +00001529 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001530 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001531
Chris Lattner13d283d2010-02-12 08:03:27 +00001532 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1533 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001534
Ted Kremenek60e45d42008-11-18 00:34:22 +00001535 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001536 // If the start of a top-level #ifdef and if the macro is not defined,
1537 // inform MIOpt that this might be the start of a proper include guard.
1538 // Otherwise it is some other form of unknown conditional which we can't
1539 // handle.
1540 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001541 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001542 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001543 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001544 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001545 }
1546
Chris Lattner141e71f2008-03-09 01:54:53 +00001547 // If there is a macro, process it.
1548 if (MI) // Mark it used.
1549 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Chris Lattner141e71f2008-03-09 01:54:53 +00001551 // Should we include the stuff contained by this directive?
1552 if (!MI == isIfndef) {
1553 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001554 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1555 /*wasskip*/false, /*foundnonskip*/true,
1556 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001557 } else {
1558 // No, skip the contents of this block and return the first token after it.
1559 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001560 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001561 /*FoundElse*/false);
1562 }
1563}
1564
1565/// HandleIfDirective - Implements the #if directive.
1566///
1567void Preprocessor::HandleIfDirective(Token &IfToken,
1568 bool ReadAnyTokensBeforeDirective) {
1569 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Chris Lattner141e71f2008-03-09 01:54:53 +00001571 // Parse and evaluation the conditional expression.
1572 IdentifierInfo *IfNDefMacro = 0;
1573 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Nuno Lopes0049db62008-06-01 18:31:24 +00001575
1576 // If this condition is equivalent to #ifndef X, and if this is the first
1577 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001578 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001579 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001580 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001581 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001582 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001583 }
1584
Chris Lattner141e71f2008-03-09 01:54:53 +00001585 // Should we include the stuff contained by this directive?
1586 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001587 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001588 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001589 /*foundnonskip*/true, /*foundelse*/false);
1590 } else {
1591 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001592 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001593 /*FoundElse*/false);
1594 }
1595}
1596
1597/// HandleEndifDirective - Implements the #endif directive.
1598///
1599void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1600 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Chris Lattner141e71f2008-03-09 01:54:53 +00001602 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001603 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Chris Lattner141e71f2008-03-09 01:54:53 +00001605 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001606 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001607 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001608 Diag(EndifToken, diag::err_pp_endif_without_if);
1609 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Chris Lattner141e71f2008-03-09 01:54:53 +00001612 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001613 if (CurPPLexer->getConditionalStackDepth() == 0)
1614 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Ted Kremenek60e45d42008-11-18 00:34:22 +00001616 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001617 "This code should only be reachable in the non-skipping case!");
1618}
1619
1620
1621void Preprocessor::HandleElseDirective(Token &Result) {
1622 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Chris Lattner141e71f2008-03-09 01:54:53 +00001624 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001625 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Chris Lattner141e71f2008-03-09 01:54:53 +00001627 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001628 if (CurPPLexer->popConditionalLevel(CI)) {
1629 Diag(Result, diag::pp_err_else_without_if);
1630 return;
1631 }
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Chris Lattner141e71f2008-03-09 01:54:53 +00001633 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001634 if (CurPPLexer->getConditionalStackDepth() == 0)
1635 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001636
1637 // If this is a #else with a #else before it, report the error.
1638 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Chris Lattner141e71f2008-03-09 01:54:53 +00001640 // Finally, skip the rest of the contents of this block and return the first
1641 // token after it.
1642 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1643 /*FoundElse*/true);
1644}
1645
1646void Preprocessor::HandleElifDirective(Token &ElifToken) {
1647 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Chris Lattner141e71f2008-03-09 01:54:53 +00001649 // #elif directive in a non-skipping conditional... start skipping.
1650 // We don't care what the condition is, because we will always skip it (since
1651 // the block immediately before it was included).
1652 DiscardUntilEndOfDirective();
1653
1654 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001655 if (CurPPLexer->popConditionalLevel(CI)) {
1656 Diag(ElifToken, diag::pp_err_elif_without_if);
1657 return;
1658 }
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Chris Lattner141e71f2008-03-09 01:54:53 +00001660 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001661 if (CurPPLexer->getConditionalStackDepth() == 0)
1662 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001663
Chris Lattner141e71f2008-03-09 01:54:53 +00001664 // If this is a #elif with a #else before it, report the error.
1665 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1666
1667 // Finally, skip the rest of the contents of this block and return the first
1668 // token after it.
1669 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1670 /*FoundElse*/CI.FoundElse);
1671}