blob: cddc6cff727ab5b3d59597b8cc72e45c8ff7d740 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Chris Lattner359cc442009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Chris Lattner6e290142009-11-30 04:18:44 +000019#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000021#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000022using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// Utility Methods for Preprocessor Directive Handling.
26//===----------------------------------------------------------------------===//
27
Chris Lattner0301b3f2009-02-20 22:19:20 +000028MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
Ted Kremenek0ea76722008-12-15 19:56:42 +000029 MacroInfo *MI;
Mike Stump1eb44332009-09-09 15:08:12 +000030
Ted Kremenek0ea76722008-12-15 19:56:42 +000031 if (!MICache.empty()) {
32 MI = MICache.back();
33 MICache.pop_back();
Chris Lattner0301b3f2009-02-20 22:19:20 +000034 } else
35 MI = (MacroInfo*) BP.Allocate<MacroInfo>();
Ted Kremenek0ea76722008-12-15 19:56:42 +000036 new (MI) MacroInfo(L);
37 return MI;
38}
39
Chris Lattner0301b3f2009-02-20 22:19:20 +000040/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
41/// be reused for allocating new MacroInfo objects.
42void Preprocessor::ReleaseMacroInfo(MacroInfo* MI) {
43 MICache.push_back(MI);
Chris Lattner685befe2009-02-20 22:46:43 +000044 MI->FreeArgumentList(BP);
Chris Lattner0301b3f2009-02-20 22:19:20 +000045}
46
47
Chris Lattner141e71f2008-03-09 01:54:53 +000048/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
49/// current line until the tok::eom token is found.
50void Preprocessor::DiscardUntilEndOfDirective() {
51 Token Tmp;
52 do {
53 LexUnexpandedToken(Tmp);
54 } while (Tmp.isNot(tok::eom));
55}
56
Chris Lattner141e71f2008-03-09 01:54:53 +000057/// ReadMacroName - Lex and validate a macro name, which occurs after a
58/// #define or #undef. This sets the token kind to eom and discards the rest
59/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
60/// this is due to a a #define, 2 if #undef directive, 0 if it is something
61/// else (e.g. #ifdef).
62void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
63 // Read the token, don't allow macro expansion on it.
64 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner141e71f2008-03-09 01:54:53 +000066 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000067 if (MacroNameTok.is(tok::eom)) {
68 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
69 return;
70 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner141e71f2008-03-09 01:54:53 +000072 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
73 if (II == 0) {
74 std::string Spelling = getSpelling(MacroNameTok);
Chris Lattner9485d232008-12-13 20:12:40 +000075 const IdentifierInfo &Info = Identifiers.get(Spelling);
76 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +000077 // C++ 2.5p2: Alternative tokens behave the same as its primary token
78 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +000079 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000080 else
81 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
82 // Fall through on error.
83 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
84 // Error if defining "defined": C99 6.10.8.4.
85 Diag(MacroNameTok, diag::err_defined_macro_name);
86 } else if (isDefineUndef && II->hasMacroDefinition() &&
87 getMacroInfo(II)->isBuiltinMacro()) {
88 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
89 if (isDefineUndef == 1)
90 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
91 else
92 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
93 } else {
94 // Okay, we got a good identifier node. Return it.
95 return;
96 }
Mike Stump1eb44332009-09-09 15:08:12 +000097
Chris Lattner141e71f2008-03-09 01:54:53 +000098 // Invalid macro name, read and discard the rest of the line. Then set the
99 // token kind to tok::eom.
100 MacroNameTok.setKind(tok::eom);
101 return DiscardUntilEndOfDirective();
102}
103
104/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattnerab82f412009-04-17 23:30:53 +0000105/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
106/// true, then we consider macros that expand to zero tokens as being ok.
107void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000108 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000109 // Lex unexpanded tokens for most directives: macros might expand to zero
110 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
111 // #line) allow empty macros.
112 if (EnableMacros)
113 Lex(Tmp);
114 else
115 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Chris Lattner141e71f2008-03-09 01:54:53 +0000117 // There should be no tokens after the directive, but we allow them as an
118 // extension.
119 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
120 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattner141e71f2008-03-09 01:54:53 +0000122 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000123 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
124 // because it is more trouble than it is worth to insert /**/ and check that
125 // there is no /**/ in the range also.
126 CodeModificationHint FixItHint;
127 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
128 FixItHint = CodeModificationHint::CreateInsertion(Tmp.getLocation(),"//");
129 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << FixItHint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000130 DiscardUntilEndOfDirective();
131 }
132}
133
134
135
136/// SkipExcludedConditionalBlock - We just read a #if or related directive and
137/// decided that the subsequent tokens are in the #if'd out portion of the
138/// file. Lex the rest of the file, until we see an #endif. If
139/// FoundNonSkipPortion is true, then we have already emitted code for part of
140/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
141/// is true, then #else directives are ok, if not, then we have already seen one
142/// so a #else directive is a duplicate. When this returns, the caller can lex
143/// the first valid token.
144void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
145 bool FoundNonSkipPortion,
146 bool FoundElse) {
147 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000148 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000149
Ted Kremenek60e45d42008-11-18 00:34:22 +0000150 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000151 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Ted Kremenek268ee702008-12-12 18:34:08 +0000153 if (CurPTHLexer) {
154 PTHSkipExcludedConditionalBlock();
155 return;
156 }
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Chris Lattner141e71f2008-03-09 01:54:53 +0000158 // Enter raw mode to disable identifier lookup (and thus macro expansion),
159 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000160 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000161 Token Tok;
162 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000163 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattner141e71f2008-03-09 01:54:53 +0000165 // If this is the end of the buffer, we have an error.
166 if (Tok.is(tok::eof)) {
167 // Emit errors for each unterminated conditional on the stack, including
168 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000169 while (!CurPPLexer->ConditionalStack.empty()) {
170 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000171 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000172 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000173 }
174
Chris Lattner141e71f2008-03-09 01:54:53 +0000175 // Just return and let the caller lex after this #include.
176 break;
177 }
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Chris Lattner141e71f2008-03-09 01:54:53 +0000179 // If this token is not a preprocessor directive, just skip it.
180 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
181 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Chris Lattner141e71f2008-03-09 01:54:53 +0000183 // We just parsed a # character at the start of a line, so we're in
184 // directive mode. Tell the lexer this so any newlines we see will be
185 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000186 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000187 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000188
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Chris Lattner141e71f2008-03-09 01:54:53 +0000190 // Read the next token, the directive flavor.
191 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner141e71f2008-03-09 01:54:53 +0000193 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
194 // something bogus), skip it.
195 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000196 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000197 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000198 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000199 continue;
200 }
201
202 // If the first letter isn't i or e, it isn't intesting to us. We know that
203 // this is safe in the face of spelling differences, because there is no way
204 // to spell an i/e in a strange way that is another letter. Skipping this
205 // allows us to avoid looking up the identifier info for #define/#undef and
206 // other common directives.
207 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
208 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000209 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000210 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000211 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000212 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000213 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000214 continue;
215 }
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Chris Lattner141e71f2008-03-09 01:54:53 +0000217 // Get the identifier name without trigraphs or embedded newlines. Note
218 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
219 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000220 char DirectiveBuf[20];
221 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000222 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000223 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000224 } else {
225 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000226 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000227 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000228 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000229 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000230 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000231 continue;
232 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000233 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
234 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000235 }
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000237 if (Directive.startswith("if")) {
238 llvm::StringRef Sub = Directive.substr(2);
239 if (Sub.empty() || // "if"
240 Sub == "def" || // "ifdef"
241 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000242 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
243 // bother parsing the condition.
244 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000245 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000246 /*foundnonskip*/false,
247 /*fnddelse*/false);
248 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000249 } else if (Directive[0] == 'e') {
250 llvm::StringRef Sub = Directive.substr(1);
251 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000252 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000253 PPConditionalInfo CondInfo;
254 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000255 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000256 InCond = InCond; // Silence warning in no-asserts mode.
257 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Chris Lattner141e71f2008-03-09 01:54:53 +0000259 // If we popped the outermost skipping block, we're done skipping!
260 if (!CondInfo.WasSkipping)
261 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000262 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000263 // #else directive in a skipping conditional. If not in some other
264 // skipping conditional, and if #else hasn't already been seen, enter it
265 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000266 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000267 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Chris Lattner141e71f2008-03-09 01:54:53 +0000269 // If this is a #else with a #else before it, report the error.
270 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Chris Lattner141e71f2008-03-09 01:54:53 +0000272 // Note that we've seen a #else in this conditional.
273 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattner141e71f2008-03-09 01:54:53 +0000275 // If the conditional is at the top level, and the #if block wasn't
276 // entered, enter the #else block now.
277 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
278 CondInfo.FoundNonSkip = true;
279 break;
280 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000281 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000282 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000283
284 bool ShouldEnter;
285 // If this is in a skipping block or if we're already handled this #if
286 // block, don't bother parsing the condition.
287 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
288 DiscardUntilEndOfDirective();
289 ShouldEnter = false;
290 } else {
291 // Restore the value of LexingRawMode so that identifiers are
292 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000293 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
294 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000295 IdentifierInfo *IfNDefMacro = 0;
296 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000297 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000298 }
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattner141e71f2008-03-09 01:54:53 +0000300 // If this is a #elif with a #else before it, report the error.
301 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 // If this condition is true, enter it!
304 if (ShouldEnter) {
305 CondInfo.FoundNonSkip = true;
306 break;
307 }
308 }
309 }
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Ted Kremenek60e45d42008-11-18 00:34:22 +0000311 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000312 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000313 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000314 }
315
316 // Finally, if we are out of the conditional (saw an #endif or ran off the end
317 // of the file, just stop skipping and return to lexing whatever came after
318 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000319 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000320}
321
Ted Kremenek268ee702008-12-12 18:34:08 +0000322void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000323
324 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000325 assert(CurPTHLexer);
326 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Ted Kremenek268ee702008-12-12 18:34:08 +0000328 // Skip to the next '#else', '#elif', or #endif.
329 if (CurPTHLexer->SkipBlock()) {
330 // We have reached an #endif. Both the '#' and 'endif' tokens
331 // have been consumed by the PTHLexer. Just pop off the condition level.
332 PPConditionalInfo CondInfo;
333 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
334 InCond = InCond; // Silence warning in no-asserts mode.
335 assert(!InCond && "Can't be skipping if not in a conditional!");
336 break;
337 }
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Ted Kremenek268ee702008-12-12 18:34:08 +0000339 // We have reached a '#else' or '#elif'. Lex the next token to get
340 // the directive flavor.
341 Token Tok;
342 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Ted Kremenek268ee702008-12-12 18:34:08 +0000344 // We can actually look up the IdentifierInfo here since we aren't in
345 // raw mode.
346 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
347
348 if (K == tok::pp_else) {
349 // #else: Enter the else condition. We aren't in a nested condition
350 // since we skip those. We're always in the one matching the last
351 // blocked we skipped.
352 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
353 // Note that we've seen a #else in this conditional.
354 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Ted Kremenek268ee702008-12-12 18:34:08 +0000356 // If the #if block wasn't entered then enter the #else block now.
357 if (!CondInfo.FoundNonSkip) {
358 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000360 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000361 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000362 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000363 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Ted Kremenek268ee702008-12-12 18:34:08 +0000365 break;
366 }
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Ted Kremenek268ee702008-12-12 18:34:08 +0000368 // Otherwise skip this block.
369 continue;
370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Ted Kremenek268ee702008-12-12 18:34:08 +0000372 assert(K == tok::pp_elif);
373 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
374
375 // If this is a #elif with a #else before it, report the error.
376 if (CondInfo.FoundElse)
377 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Ted Kremenek268ee702008-12-12 18:34:08 +0000379 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000380 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000381 if (CondInfo.FoundNonSkip)
382 continue;
383
384 // Evaluate the condition of the #elif.
385 IdentifierInfo *IfNDefMacro = 0;
386 CurPTHLexer->ParsingPreprocessorDirective = true;
387 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
388 CurPTHLexer->ParsingPreprocessorDirective = false;
389
390 // If this condition is true, enter it!
391 if (ShouldEnter) {
392 CondInfo.FoundNonSkip = true;
393 break;
394 }
395
396 // Otherwise, skip this block and go to the next one.
397 continue;
398 }
399}
400
Chris Lattner10725092008-03-09 04:17:44 +0000401/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
402/// return null on failure. isAngled indicates whether the file reference is
403/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnera1394812010-01-10 01:35:12 +0000404const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattner10725092008-03-09 04:17:44 +0000405 bool isAngled,
406 const DirectoryLookup *FromDir,
407 const DirectoryLookup *&CurDir) {
408 // If the header lookup mechanism may be relative to the current file, pass in
409 // info about where the current file is.
410 const FileEntry *CurFileEnt = 0;
411 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000412 FileID FID = getCurrentFileLexer()->getFileID();
413 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000415 // If there is no file entry associated with this file, it must be the
416 // predefines buffer. Any other file is not lexed with a normal lexer, so
417 // it won't be scanned for preprocessor directives. If we have the
418 // predefines buffer, resolve #include references (which come from the
419 // -include command line argument) as if they came from the main file, this
420 // affects file lookup etc.
421 if (CurFileEnt == 0) {
422 FID = SourceMgr.getMainFileID();
423 CurFileEnt = SourceMgr.getFileEntryForID(FID);
424 }
Chris Lattner10725092008-03-09 04:17:44 +0000425 }
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Chris Lattner10725092008-03-09 04:17:44 +0000427 // Do a standard file entry lookup.
428 CurDir = CurDirLookup;
429 const FileEntry *FE =
Chris Lattnera1394812010-01-10 01:35:12 +0000430 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000431 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Chris Lattner10725092008-03-09 04:17:44 +0000433 // Otherwise, see if this is a subframework header. If so, this is relative
434 // to one of the headers on the #include stack. Walk the list of the current
435 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000436 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000437 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000438 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000439 return FE;
440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner10725092008-03-09 04:17:44 +0000442 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
443 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000444 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000445 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000446 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000447 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000448 return FE;
449 }
450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Chris Lattner10725092008-03-09 04:17:44 +0000452 // Otherwise, we really couldn't find the file.
453 return 0;
454}
455
Chris Lattner141e71f2008-03-09 01:54:53 +0000456
457//===----------------------------------------------------------------------===//
458// Preprocessor Directive Handling.
459//===----------------------------------------------------------------------===//
460
461/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000462/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000463/// lexer/preprocessor state, and advances the lexer(s) so that the next token
464/// read is the correct one.
465void Preprocessor::HandleDirective(Token &Result) {
466 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Chris Lattner141e71f2008-03-09 01:54:53 +0000468 // We just parsed a # character at the start of a line, so we're in directive
469 // mode. Tell the lexer this so any newlines we see will be converted into an
470 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000471 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Chris Lattner141e71f2008-03-09 01:54:53 +0000473 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000474
Chris Lattner141e71f2008-03-09 01:54:53 +0000475 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000476 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000477 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000478 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner42aa16c2009-03-18 21:00:25 +0000480 // Save the '#' token in case we need to return it later.
481 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Chris Lattner141e71f2008-03-09 01:54:53 +0000483 // Read the next token, the directive flavor. This isn't expanded due to
484 // C99 6.10.3p8.
485 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Chris Lattner141e71f2008-03-09 01:54:53 +0000487 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
488 // #define A(x) #x
489 // A(abc
490 // #warning blah
491 // def)
492 // If so, the user is relying on non-portable behavior, emit a diagnostic.
493 if (InMacroArgs)
494 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Chris Lattner141e71f2008-03-09 01:54:53 +0000496TryAgain:
497 switch (Result.getKind()) {
498 case tok::eom:
499 return; // null directive.
500 case tok::comment:
501 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
502 LexUnexpandedToken(Result);
503 goto TryAgain;
504
Chris Lattner478a18e2009-01-26 06:19:46 +0000505 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000506 if (getLangOptions().AsmPreprocessor)
507 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000508 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000509 default:
510 IdentifierInfo *II = Result.getIdentifierInfo();
511 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattner141e71f2008-03-09 01:54:53 +0000513 // Ask what the preprocessor keyword ID is.
514 switch (II->getPPKeywordID()) {
515 default: break;
516 // C99 6.10.1 - Conditional Inclusion.
517 case tok::pp_if:
518 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
519 case tok::pp_ifdef:
520 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
521 case tok::pp_ifndef:
522 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
523 case tok::pp_elif:
524 return HandleElifDirective(Result);
525 case tok::pp_else:
526 return HandleElseDirective(Result);
527 case tok::pp_endif:
528 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Chris Lattner141e71f2008-03-09 01:54:53 +0000530 // C99 6.10.2 - Source File Inclusion.
531 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000532 return HandleIncludeDirective(Result); // Handle #include.
533 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000534 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Chris Lattner141e71f2008-03-09 01:54:53 +0000536 // C99 6.10.3 - Macro Replacement.
537 case tok::pp_define:
538 return HandleDefineDirective(Result);
539 case tok::pp_undef:
540 return HandleUndefDirective(Result);
541
542 // C99 6.10.4 - Line Control.
543 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000544 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattner141e71f2008-03-09 01:54:53 +0000546 // C99 6.10.5 - Error Directive.
547 case tok::pp_error:
548 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Chris Lattner141e71f2008-03-09 01:54:53 +0000550 // C99 6.10.6 - Pragma Directive.
551 case tok::pp_pragma:
552 return HandlePragmaDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Chris Lattner141e71f2008-03-09 01:54:53 +0000554 // GNU Extensions.
555 case tok::pp_import:
556 return HandleImportDirective(Result);
557 case tok::pp_include_next:
558 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner141e71f2008-03-09 01:54:53 +0000560 case tok::pp_warning:
561 Diag(Result, diag::ext_pp_warning_directive);
562 return HandleUserDiagnosticDirective(Result, true);
563 case tok::pp_ident:
564 return HandleIdentSCCSDirective(Result);
565 case tok::pp_sccs:
566 return HandleIdentSCCSDirective(Result);
567 case tok::pp_assert:
568 //isExtension = true; // FIXME: implement #assert
569 break;
570 case tok::pp_unassert:
571 //isExtension = true; // FIXME: implement #unassert
572 break;
573 }
574 break;
575 }
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattner42aa16c2009-03-18 21:00:25 +0000577 // If this is a .S file, treat unknown # directives as non-preprocessor
578 // directives. This is important because # may be a comment or introduce
579 // various pseudo-ops. Just return the # token and push back the following
580 // token to be lexed next time.
581 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000582 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000583 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000584 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000585 Toks[1] = Result;
586 // Enter this token stream so that we re-lex the tokens. Make sure to
587 // enable macro expansion, in case the token after the # is an identifier
588 // that is expanded.
589 EnterTokenStream(Toks, 2, false, true);
590 return;
591 }
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Chris Lattner141e71f2008-03-09 01:54:53 +0000593 // If we reached here, the preprocessing token is not valid!
594 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chris Lattner141e71f2008-03-09 01:54:53 +0000596 // Read the rest of the PP line.
597 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Chris Lattner141e71f2008-03-09 01:54:53 +0000599 // Okay, we're done parsing the directive.
600}
601
Chris Lattner478a18e2009-01-26 06:19:46 +0000602/// GetLineValue - Convert a numeric token into an unsigned value, emitting
603/// Diagnostic DiagID if it is invalid, and returning the value in Val.
604static bool GetLineValue(Token &DigitTok, unsigned &Val,
605 unsigned DiagID, Preprocessor &PP) {
606 if (DigitTok.isNot(tok::numeric_constant)) {
607 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattner478a18e2009-01-26 06:19:46 +0000609 if (DigitTok.isNot(tok::eom))
610 PP.DiscardUntilEndOfDirective();
611 return true;
612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Chris Lattner478a18e2009-01-26 06:19:46 +0000614 llvm::SmallString<64> IntegerBuffer;
615 IntegerBuffer.resize(DigitTok.getLength());
616 const char *DigitTokBegin = &IntegerBuffer[0];
617 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000619 // Verify that we have a simple digit-sequence, and compute the value. This
620 // is always a simple digit string computed in decimal, so we do this manually
621 // here.
622 Val = 0;
623 for (unsigned i = 0; i != ActualLength; ++i) {
624 if (!isdigit(DigitTokBegin[i])) {
625 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
626 diag::err_pp_line_digit_sequence);
627 PP.DiscardUntilEndOfDirective();
628 return true;
629 }
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000631 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
632 if (NextVal < Val) { // overflow.
633 PP.Diag(DigitTok, DiagID);
634 PP.DiscardUntilEndOfDirective();
635 return true;
636 }
637 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000638 }
Mike Stump1eb44332009-09-09 15:08:12 +0000639
640 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000641 if (Val == 0) {
642 PP.Diag(DigitTok, DiagID);
643 PP.DiscardUntilEndOfDirective();
644 return true;
645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000647 if (DigitTokBegin[0] == '0')
648 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Chris Lattner478a18e2009-01-26 06:19:46 +0000650 return false;
651}
652
Mike Stump1eb44332009-09-09 15:08:12 +0000653/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000654/// acceptable forms are:
655/// # line digit-sequence
656/// # line digit-sequence "s-char-sequence"
657void Preprocessor::HandleLineDirective(Token &Tok) {
658 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
659 // expanded.
660 Token DigitTok;
661 Lex(DigitTok);
662
Chris Lattner359cc442009-01-26 05:29:08 +0000663 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000664 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000665 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000666 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000667
Chris Lattner478a18e2009-01-26 06:19:46 +0000668 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
669 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000670 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
671 if (LineNo >= LineLimit)
672 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Chris Lattner5b9a5042009-01-26 07:57:50 +0000674 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000675 Token StrTok;
676 Lex(StrTok);
677
678 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
679 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000680 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000681 ; // ok
682 else if (StrTok.isNot(tok::string_literal)) {
683 Diag(StrTok, diag::err_pp_line_invalid_filename);
684 DiscardUntilEndOfDirective();
685 return;
686 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000687 // Parse and validate the string, converting it into a unique ID.
688 StringLiteralParser Literal(&StrTok, 1, *this);
689 assert(!Literal.AnyWide && "Didn't allow wide strings in");
690 if (Literal.hadError)
691 return DiscardUntilEndOfDirective();
692 if (Literal.Pascal) {
693 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
694 return DiscardUntilEndOfDirective();
695 }
696 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
697 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Chris Lattnerab82f412009-04-17 23:30:53 +0000699 // Verify that there is nothing after the string, other than EOM. Because
700 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
701 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000702 }
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Chris Lattner4c4ea172009-02-03 21:52:55 +0000704 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Chris Lattner16629382009-03-27 17:13:49 +0000706 if (Callbacks)
707 Callbacks->FileChanged(DigitTok.getLocation(), PPCallbacks::RenameFile,
708 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000709}
710
Chris Lattner478a18e2009-01-26 06:19:46 +0000711/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
712/// marker directive.
713static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
714 bool &IsSystemHeader, bool &IsExternCHeader,
715 Preprocessor &PP) {
716 unsigned FlagVal;
717 Token FlagTok;
718 PP.Lex(FlagTok);
719 if (FlagTok.is(tok::eom)) return false;
720 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
721 return true;
722
723 if (FlagVal == 1) {
724 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Chris Lattner478a18e2009-01-26 06:19:46 +0000726 PP.Lex(FlagTok);
727 if (FlagTok.is(tok::eom)) return false;
728 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
729 return true;
730 } else if (FlagVal == 2) {
731 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Chris Lattner137b6a62009-02-04 06:25:26 +0000733 SourceManager &SM = PP.getSourceManager();
734 // If we are leaving the current presumed file, check to make sure the
735 // presumed include stack isn't empty!
736 FileID CurFileID =
737 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
738 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattner137b6a62009-02-04 06:25:26 +0000740 // If there is no include loc (main file) or if the include loc is in a
741 // different physical file, then we aren't in a "1" line marker flag region.
742 SourceLocation IncLoc = PLoc.getIncludeLoc();
743 if (IncLoc.isInvalid() ||
744 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
745 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
746 PP.DiscardUntilEndOfDirective();
747 return true;
748 }
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Chris Lattner478a18e2009-01-26 06:19:46 +0000750 PP.Lex(FlagTok);
751 if (FlagTok.is(tok::eom)) return false;
752 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
753 return true;
754 }
755
756 // We must have 3 if there are still flags.
757 if (FlagVal != 3) {
758 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000759 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000760 return true;
761 }
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Chris Lattner478a18e2009-01-26 06:19:46 +0000763 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner478a18e2009-01-26 06:19:46 +0000765 PP.Lex(FlagTok);
766 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000767 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000768 return true;
769
770 // We must have 4 if there is yet another flag.
771 if (FlagVal != 4) {
772 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000773 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000774 return true;
775 }
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Chris Lattner478a18e2009-01-26 06:19:46 +0000777 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Chris Lattner478a18e2009-01-26 06:19:46 +0000779 PP.Lex(FlagTok);
780 if (FlagTok.is(tok::eom)) return false;
781
782 // There are no more valid flags here.
783 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000784 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000785 return true;
786}
787
788/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
789/// one of the following forms:
790///
791/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000792/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000793/// # 42 "file" ('1' | '2')? '3' '4'?
794///
795void Preprocessor::HandleDigitDirective(Token &DigitTok) {
796 // Validate the number and convert it to an unsigned. GNU does not have a
797 // line # limit other than it fit in 32-bits.
798 unsigned LineNo;
799 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
800 *this))
801 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Chris Lattner478a18e2009-01-26 06:19:46 +0000803 Token StrTok;
804 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Chris Lattner478a18e2009-01-26 06:19:46 +0000806 bool IsFileEntry = false, IsFileExit = false;
807 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000808 int FilenameID = -1;
809
Chris Lattner478a18e2009-01-26 06:19:46 +0000810 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
811 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000812 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000813 ; // ok
814 else if (StrTok.isNot(tok::string_literal)) {
815 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000816 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000817 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000818 // Parse and validate the string, converting it into a unique ID.
819 StringLiteralParser Literal(&StrTok, 1, *this);
820 assert(!Literal.AnyWide && "Didn't allow wide strings in");
821 if (Literal.hadError)
822 return DiscardUntilEndOfDirective();
823 if (Literal.Pascal) {
824 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
825 return DiscardUntilEndOfDirective();
826 }
827 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
828 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Chris Lattner478a18e2009-01-26 06:19:46 +0000830 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000831 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000832 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000833 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000834 }
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Chris Lattner9d79eba2009-02-04 05:21:58 +0000836 // Create a line note with this information.
837 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000838 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000839 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Chris Lattner16629382009-03-27 17:13:49 +0000841 // If the preprocessor has callbacks installed, notify them of the #line
842 // change. This is used so that the line marker comes out in -E mode for
843 // example.
844 if (Callbacks) {
845 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
846 if (IsFileEntry)
847 Reason = PPCallbacks::EnterFile;
848 else if (IsFileExit)
849 Reason = PPCallbacks::ExitFile;
850 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
851 if (IsExternCHeader)
852 FileKind = SrcMgr::C_ExternCSystem;
853 else if (IsSystemHeader)
854 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Chris Lattner16629382009-03-27 17:13:49 +0000856 Callbacks->FileChanged(DigitTok.getLocation(), Reason, FileKind);
857 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000858}
859
860
Chris Lattner099dd052009-01-26 05:30:54 +0000861/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
862///
Mike Stump1eb44332009-09-09 15:08:12 +0000863void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000864 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000865 // PTH doesn't emit #warning or #error directives.
866 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000867 return CurPTHLexer->DiscardToEndOfLine();
868
Chris Lattner141e71f2008-03-09 01:54:53 +0000869 // Read the rest of the line raw. We do this because we don't want macros
870 // to be expanded and we don't require that the tokens be valid preprocessing
871 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
872 // collapse multiple consequtive white space between tokens, but this isn't
873 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000874 std::string Message = CurLexer->ReadToEndOfLine();
875 if (isWarning)
876 Diag(Tok, diag::pp_hash_warning) << Message;
877 else
878 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000879}
880
881/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
882///
883void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
884 // Yes, this directive is an extension.
885 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Chris Lattner141e71f2008-03-09 01:54:53 +0000887 // Read the string argument.
888 Token StrTok;
889 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Chris Lattner141e71f2008-03-09 01:54:53 +0000891 // If the token kind isn't a string, it's a malformed directive.
892 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000893 StrTok.isNot(tok::wide_string_literal)) {
894 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000895 if (StrTok.isNot(tok::eom))
896 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000897 return;
898 }
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner141e71f2008-03-09 01:54:53 +0000900 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000901 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000902
903 if (Callbacks)
904 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
905}
906
907//===----------------------------------------------------------------------===//
908// Preprocessor Include Directive Handling.
909//===----------------------------------------------------------------------===//
910
911/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
912/// checked and spelled filename, e.g. as an operand of #include. This returns
913/// true if the input filename was in <>'s or false if it were in ""'s. The
914/// caller is expected to provide a buffer that is large enough to hold the
915/// spelling of the filename, but is also expected to handle the case when
916/// this method decides to use a different buffer.
917bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000918 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000919 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000920 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Chris Lattner141e71f2008-03-09 01:54:53 +0000922 // Make sure the filename is <x> or "x".
923 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000924 if (Buffer[0] == '<') {
925 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000926 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000927 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000928 return true;
929 }
930 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +0000931 } else if (Buffer[0] == '"') {
932 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000933 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000934 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000935 return true;
936 }
937 isAngled = false;
938 } else {
939 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000940 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000941 return true;
942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Chris Lattner141e71f2008-03-09 01:54:53 +0000944 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +0000945 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000946 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000947 Buffer = llvm::StringRef();
948 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000949 }
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattner141e71f2008-03-09 01:54:53 +0000951 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +0000952 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +0000953 return isAngled;
954}
955
956/// ConcatenateIncludeName - Handle cases where the #include name is expanded
957/// from a macro as multiple tokens, which need to be glued together. This
958/// occurs for code like:
959/// #define FOO <a/b.h>
960/// #include FOO
961/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
962///
963/// This code concatenates and consumes tokens up to the '>' token. It returns
964/// false if the > was found, otherwise it returns true if it finds and consumes
965/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +0000966bool Preprocessor::ConcatenateIncludeName(
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000967 llvm::SmallString<128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000968 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +0000969
John Thompsona28cc092009-10-30 13:49:06 +0000970 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000971 while (CurTok.isNot(tok::eom)) {
972 // Append the spelling of this token to the buffer. If there was a space
973 // before it, add it now.
974 if (CurTok.hasLeadingSpace())
975 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Chris Lattner141e71f2008-03-09 01:54:53 +0000977 // Get the spelling of the token, directly into FilenameBuffer if possible.
978 unsigned PreAppendSize = FilenameBuffer.size();
979 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Chris Lattner141e71f2008-03-09 01:54:53 +0000981 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +0000982 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Chris Lattner141e71f2008-03-09 01:54:53 +0000984 // If the token was spelled somewhere else, copy it into FilenameBuffer.
985 if (BufPtr != &FilenameBuffer[PreAppendSize])
986 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Chris Lattner141e71f2008-03-09 01:54:53 +0000988 // Resize FilenameBuffer to the correct size.
989 if (CurTok.getLength() != ActualLen)
990 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner141e71f2008-03-09 01:54:53 +0000992 // If we found the '>' marker, return success.
993 if (CurTok.is(tok::greater))
994 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000995
John Thompsona28cc092009-10-30 13:49:06 +0000996 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000997 }
998
999 // If we hit the eom marker, emit an error and return true so that the caller
1000 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001001 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001002 return true;
1003}
1004
1005/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1006/// file to be included from the lexer, then include it! This is a common
1007/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001008/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001009/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001010void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1011 const DirectoryLookup *LookupFrom,
1012 bool isImport) {
1013
1014 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001015 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattner141e71f2008-03-09 01:54:53 +00001017 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001018 llvm::SmallString<128> FilenameBuffer;
1019 llvm::StringRef Filename;
Chris Lattner141e71f2008-03-09 01:54:53 +00001020
1021 switch (FilenameTok.getKind()) {
1022 case tok::eom:
1023 // If the token kind is EOM, the error has already been diagnosed.
1024 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattner141e71f2008-03-09 01:54:53 +00001026 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001027 case tok::string_literal:
1028 Filename = getSpelling(FilenameTok, FilenameBuffer);
Chris Lattner141e71f2008-03-09 01:54:53 +00001029 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Chris Lattner141e71f2008-03-09 01:54:53 +00001031 case tok::less:
1032 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1033 // case, glue the tokens together into FilenameBuffer and interpret those.
1034 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001035 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001036 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001037 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001038 break;
1039 default:
1040 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1041 DiscardUntilEndOfDirective();
1042 return;
1043 }
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001045 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001046 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001047 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1048 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001049 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001050 DiscardUntilEndOfDirective();
1051 return;
1052 }
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001054 // Verify that there is nothing after the filename, other than EOM. Note that
1055 // we allow macros that expand to nothing after the filename, because this
1056 // falls into the category of "#include pp-tokens new-line" specified in
1057 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001058 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001059
1060 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001061 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1062 Diag(FilenameTok, diag::err_pp_include_too_deep);
1063 return;
1064 }
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Chris Lattner141e71f2008-03-09 01:54:53 +00001066 // Search include directories.
1067 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +00001068 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001069 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001070 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001071 return;
1072 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001073
Chris Lattner72181832008-09-26 20:12:23 +00001074 // Ask HeaderInfo if we should enter this #include file. If not, #including
1075 // this file will have no effect.
1076 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001077 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Chris Lattner72181832008-09-26 20:12:23 +00001079 // The #included file will be considered to be a system header if either it is
1080 // in a system include directory, or if the #includer is a system include
1081 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001082 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001083 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001084 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Chris Lattner141e71f2008-03-09 01:54:53 +00001086 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001087 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1088 FileCharacter);
1089 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001090 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001091 return;
1092 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001093
1094 // Finally, if all is good, enter the new file!
Chris Lattner39d98412009-12-01 22:52:33 +00001095 std::string ErrorStr;
Daniel Dunbar63ceaa32009-12-06 09:19:12 +00001096 if (EnterSourceFile(FID, CurDir, ErrorStr))
Chris Lattner6e290142009-11-30 04:18:44 +00001097 Diag(FilenameTok, diag::err_pp_error_opening_file)
Chris Lattner39d98412009-12-01 22:52:33 +00001098 << std::string(SourceMgr.getFileEntryForID(FID)->getName()) << ErrorStr;
Chris Lattner141e71f2008-03-09 01:54:53 +00001099}
1100
1101/// HandleIncludeNextDirective - Implements #include_next.
1102///
1103void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1104 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Chris Lattner141e71f2008-03-09 01:54:53 +00001106 // #include_next is like #include, except that we start searching after
1107 // the current found directory. If we can't do this, issue a
1108 // diagnostic.
1109 const DirectoryLookup *Lookup = CurDirLookup;
1110 if (isInPrimaryFile()) {
1111 Lookup = 0;
1112 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1113 } else if (Lookup == 0) {
1114 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1115 } else {
1116 // Start looking up in the next directory.
1117 ++Lookup;
1118 }
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Chris Lattner141e71f2008-03-09 01:54:53 +00001120 return HandleIncludeDirective(IncludeNextTok, Lookup);
1121}
1122
1123/// HandleImportDirective - Implements #import.
1124///
1125void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001126 if (!Features.ObjC1) // #import is standard for ObjC.
1127 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Chris Lattner141e71f2008-03-09 01:54:53 +00001129 return HandleIncludeDirective(ImportTok, 0, true);
1130}
1131
Chris Lattnerde076652009-04-08 18:46:40 +00001132/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1133/// pseudo directive in the predefines buffer. This handles it by sucking all
1134/// tokens through the preprocessor and discarding them (only keeping the side
1135/// effects on the preprocessor).
1136void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1137 // This directive should only occur in the predefines buffer. If not, emit an
1138 // error and reject it.
1139 SourceLocation Loc = IncludeMacrosTok.getLocation();
1140 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1141 Diag(IncludeMacrosTok.getLocation(),
1142 diag::pp_include_macros_out_of_predefines);
1143 DiscardUntilEndOfDirective();
1144 return;
1145 }
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Chris Lattnerfd105112009-04-08 20:53:24 +00001147 // Treat this as a normal #include for checking purposes. If this is
1148 // successful, it will push a new lexer onto the include stack.
1149 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Chris Lattnerfd105112009-04-08 20:53:24 +00001151 Token TmpTok;
1152 do {
1153 Lex(TmpTok);
1154 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1155 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001156}
1157
Chris Lattner141e71f2008-03-09 01:54:53 +00001158//===----------------------------------------------------------------------===//
1159// Preprocessor Macro Directive Handling.
1160//===----------------------------------------------------------------------===//
1161
1162/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1163/// definition has just been read. Lex the rest of the arguments and the
1164/// closing ), updating MI with what we learn. Return true if an error occurs
1165/// parsing the arg list.
1166bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1167 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Chris Lattner141e71f2008-03-09 01:54:53 +00001169 Token Tok;
1170 while (1) {
1171 LexUnexpandedToken(Tok);
1172 switch (Tok.getKind()) {
1173 case tok::r_paren:
1174 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001175 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001176 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001177 // Otherwise we have #define FOO(A,)
1178 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1179 return true;
1180 case tok::ellipsis: // #define X(... -> C99 varargs
1181 // Warn if use of C99 feature in non-C99 mode.
1182 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1183
1184 // Lex the token after the identifier.
1185 LexUnexpandedToken(Tok);
1186 if (Tok.isNot(tok::r_paren)) {
1187 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1188 return true;
1189 }
1190 // Add the __VA_ARGS__ identifier as an argument.
1191 Arguments.push_back(Ident__VA_ARGS__);
1192 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001193 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001194 return false;
1195 case tok::eom: // #define X(
1196 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1197 return true;
1198 default:
1199 // Handle keywords and identifiers here to accept things like
1200 // #define Foo(for) for.
1201 IdentifierInfo *II = Tok.getIdentifierInfo();
1202 if (II == 0) {
1203 // #define X(1
1204 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1205 return true;
1206 }
1207
1208 // If this is already used as an argument, it is used multiple times (e.g.
1209 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001210 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001211 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001212 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001213 return true;
1214 }
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Chris Lattner141e71f2008-03-09 01:54:53 +00001216 // Add the argument to the macro info.
1217 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Chris Lattner141e71f2008-03-09 01:54:53 +00001219 // Lex the token after the identifier.
1220 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Chris Lattner141e71f2008-03-09 01:54:53 +00001222 switch (Tok.getKind()) {
1223 default: // #define X(A B
1224 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1225 return true;
1226 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001227 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001228 return false;
1229 case tok::comma: // #define X(A,
1230 break;
1231 case tok::ellipsis: // #define X(A... -> GCC extension
1232 // Diagnose extension.
1233 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Chris Lattner141e71f2008-03-09 01:54:53 +00001235 // Lex the token after the identifier.
1236 LexUnexpandedToken(Tok);
1237 if (Tok.isNot(tok::r_paren)) {
1238 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1239 return true;
1240 }
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Chris Lattner141e71f2008-03-09 01:54:53 +00001242 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001243 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001244 return false;
1245 }
1246 }
1247 }
1248}
1249
1250/// HandleDefineDirective - Implements #define. This consumes the entire macro
1251/// line then lets the caller lex the next real token.
1252void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1253 ++NumDefined;
1254
1255 Token MacroNameTok;
1256 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Chris Lattner141e71f2008-03-09 01:54:53 +00001258 // Error reading macro name? If so, diagnostic already issued.
1259 if (MacroNameTok.is(tok::eom))
1260 return;
1261
Chris Lattner2451b522009-04-21 04:46:33 +00001262 Token LastTok = MacroNameTok;
1263
Chris Lattner141e71f2008-03-09 01:54:53 +00001264 // If we are supposed to keep comments in #defines, reenable comment saving
1265 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001266 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Chris Lattner141e71f2008-03-09 01:54:53 +00001268 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001269 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Chris Lattner141e71f2008-03-09 01:54:53 +00001271 Token Tok;
1272 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Chris Lattner141e71f2008-03-09 01:54:53 +00001274 // If this is a function-like macro definition, parse the argument list,
1275 // marking each of the identifiers as being used as macro arguments. Also,
1276 // check other constraints on the first token of the macro body.
1277 if (Tok.is(tok::eom)) {
1278 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001279 } else if (Tok.hasLeadingSpace()) {
1280 // This is a normal token with leading space. Clear the leading space
1281 // marker on the first token to get proper expansion.
1282 Tok.clearFlag(Token::LeadingSpace);
1283 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001284 // This is a function-like macro definition. Read the argument list.
1285 MI->setIsFunctionLike();
1286 if (ReadMacroDefinitionArgList(MI)) {
1287 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001288 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001289 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001290 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001291 DiscardUntilEndOfDirective();
1292 return;
1293 }
1294
Chris Lattner8fde5972009-04-19 18:26:34 +00001295 // If this is a definition of a variadic C99 function-like macro, not using
1296 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Chris Lattner8fde5972009-04-19 18:26:34 +00001298 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1299 // This gets unpoisoned where it is allowed.
1300 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1301 if (MI->isC99Varargs())
1302 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Chris Lattner141e71f2008-03-09 01:54:53 +00001304 // Read the first token after the arg list for down below.
1305 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001306 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001307 // C99 requires whitespace between the macro definition and the body. Emit
1308 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001309 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001310 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001311 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1312 // first character of a replacement list is not a character required by
1313 // subclause 5.2.1, then there shall be white-space separation between the
1314 // identifier and the replacement list.". 5.2.1 lists this set:
1315 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1316 // is irrelevant here.
1317 bool isInvalid = false;
1318 if (Tok.is(tok::at)) // @ is not in the list above.
1319 isInvalid = true;
1320 else if (Tok.is(tok::unknown)) {
1321 // If we have an unknown token, it is something strange like "`". Since
1322 // all of valid characters would have lexed into a single character
1323 // token of some sort, we know this is not a valid case.
1324 isInvalid = true;
1325 }
1326 if (isInvalid)
1327 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1328 else
1329 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001330 }
Chris Lattner2451b522009-04-21 04:46:33 +00001331
1332 if (!Tok.is(tok::eom))
1333 LastTok = Tok;
1334
Chris Lattner141e71f2008-03-09 01:54:53 +00001335 // Read the rest of the macro body.
1336 if (MI->isObjectLike()) {
1337 // Object-like macros are very simple, just read their body.
1338 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001339 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001340 MI->AddTokenToBody(Tok);
1341 // Get the next token of the macro.
1342 LexUnexpandedToken(Tok);
1343 }
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Chris Lattner141e71f2008-03-09 01:54:53 +00001345 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001346 // Otherwise, read the body of a function-like macro. While we are at it,
1347 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1348 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001349 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001350 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001351
Chris Lattner141e71f2008-03-09 01:54:53 +00001352 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001353 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Chris Lattner141e71f2008-03-09 01:54:53 +00001355 // Get the next token of the macro.
1356 LexUnexpandedToken(Tok);
1357 continue;
1358 }
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Chris Lattner141e71f2008-03-09 01:54:53 +00001360 // Get the next token of the macro.
1361 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Chris Lattner32404692009-05-25 17:16:10 +00001363 // Check for a valid macro arg identifier.
1364 if (Tok.getIdentifierInfo() == 0 ||
1365 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1366
1367 // If this is assembler-with-cpp mode, we accept random gibberish after
1368 // the '#' because '#' is often a comment character. However, change
1369 // the kind of the token to tok::unknown so that the preprocessor isn't
1370 // confused.
1371 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1372 LastTok.setKind(tok::unknown);
1373 } else {
1374 Diag(Tok, diag::err_pp_stringize_not_parameter);
1375 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Chris Lattner32404692009-05-25 17:16:10 +00001377 // Disable __VA_ARGS__ again.
1378 Ident__VA_ARGS__->setIsPoisoned(true);
1379 return;
1380 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001381 }
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Chris Lattner32404692009-05-25 17:16:10 +00001383 // Things look ok, add the '#' and param name tokens to the macro.
1384 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001385 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001386 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Chris Lattner141e71f2008-03-09 01:54:53 +00001388 // Get the next token of the macro.
1389 LexUnexpandedToken(Tok);
1390 }
1391 }
Mike Stump1eb44332009-09-09 15:08:12 +00001392
1393
Chris Lattner141e71f2008-03-09 01:54:53 +00001394 // Disable __VA_ARGS__ again.
1395 Ident__VA_ARGS__->setIsPoisoned(true);
1396
1397 // Check that there is no paste (##) operator at the begining or end of the
1398 // replacement list.
1399 unsigned NumTokens = MI->getNumTokens();
1400 if (NumTokens != 0) {
1401 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1402 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001403 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001404 return;
1405 }
1406 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1407 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001408 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001409 return;
1410 }
1411 }
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Chris Lattner141e71f2008-03-09 01:54:53 +00001413 // If this is the primary source file, remember that this macro hasn't been
1414 // used yet.
1415 if (isInPrimaryFile())
1416 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001417
1418 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Chris Lattner141e71f2008-03-09 01:54:53 +00001420 // Finally, if this identifier already had a macro defined for it, verify that
1421 // the macro bodies are identical and free the old definition.
1422 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001423 // It is very common for system headers to have tons of macro redefinitions
1424 // and for warnings to be disabled in system headers. If this is the case,
1425 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001426 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001427 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1428 if (!OtherMI->isUsed())
1429 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001430
Chris Lattner41c3ae12009-01-16 19:50:11 +00001431 // Macros must be identical. This means all tokes and whitespace
1432 // separation must be the same. C99 6.10.3.2.
1433 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1434 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1435 << MacroNameTok.getIdentifierInfo();
1436 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1437 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001438 }
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Ted Kremenek0ea76722008-12-15 19:56:42 +00001440 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001441 }
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Chris Lattner141e71f2008-03-09 01:54:53 +00001443 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001445 // If the callbacks want to know, tell them about the macro definition.
1446 if (Callbacks)
1447 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001448}
1449
1450/// HandleUndefDirective - Implements #undef.
1451///
1452void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1453 ++NumUndefined;
1454
1455 Token MacroNameTok;
1456 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Chris Lattner141e71f2008-03-09 01:54:53 +00001458 // Error reading macro name? If so, diagnostic already issued.
1459 if (MacroNameTok.is(tok::eom))
1460 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Chris Lattner141e71f2008-03-09 01:54:53 +00001462 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001463 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Chris Lattner141e71f2008-03-09 01:54:53 +00001465 // Okay, we finally have a valid identifier to undef.
1466 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Chris Lattner141e71f2008-03-09 01:54:53 +00001468 // If the macro is not defined, this is a noop undef, just return.
1469 if (MI == 0) return;
1470
1471 if (!MI->isUsed())
1472 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001473
1474 // If the callbacks want to know, tell them about the macro #undef.
1475 if (Callbacks)
1476 Callbacks->MacroUndefined(MacroNameTok.getIdentifierInfo(), MI);
1477
Chris Lattner141e71f2008-03-09 01:54:53 +00001478 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001479 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001480 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1481}
1482
1483
1484//===----------------------------------------------------------------------===//
1485// Preprocessor Conditional Directive Handling.
1486//===----------------------------------------------------------------------===//
1487
1488/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1489/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1490/// if any tokens have been returned or pp-directives activated before this
1491/// #ifndef has been lexed.
1492///
1493void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1494 bool ReadAnyTokensBeforeDirective) {
1495 ++NumIf;
1496 Token DirectiveTok = Result;
1497
1498 Token MacroNameTok;
1499 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Chris Lattner141e71f2008-03-09 01:54:53 +00001501 // Error reading macro name? If so, diagnostic already issued.
1502 if (MacroNameTok.is(tok::eom)) {
1503 // Skip code until we get to #endif. This helps with recovery by not
1504 // emitting an error when the #endif is reached.
1505 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1506 /*Foundnonskip*/false, /*FoundElse*/false);
1507 return;
1508 }
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Chris Lattner141e71f2008-03-09 01:54:53 +00001510 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001511 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001512
Chris Lattner13d283d2010-02-12 08:03:27 +00001513 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1514 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001515
Ted Kremenek60e45d42008-11-18 00:34:22 +00001516 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001517 // If the start of a top-level #ifdef and if the macro is not defined,
1518 // inform MIOpt that this might be the start of a proper include guard.
1519 // Otherwise it is some other form of unknown conditional which we can't
1520 // handle.
1521 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001522 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001523 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001524 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001525 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001526 }
1527
Chris Lattner141e71f2008-03-09 01:54:53 +00001528 // If there is a macro, process it.
1529 if (MI) // Mark it used.
1530 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Chris Lattner141e71f2008-03-09 01:54:53 +00001532 // Should we include the stuff contained by this directive?
1533 if (!MI == isIfndef) {
1534 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001535 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1536 /*wasskip*/false, /*foundnonskip*/true,
1537 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001538 } else {
1539 // No, skip the contents of this block and return the first token after it.
1540 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001541 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001542 /*FoundElse*/false);
1543 }
1544}
1545
1546/// HandleIfDirective - Implements the #if directive.
1547///
1548void Preprocessor::HandleIfDirective(Token &IfToken,
1549 bool ReadAnyTokensBeforeDirective) {
1550 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Chris Lattner141e71f2008-03-09 01:54:53 +00001552 // Parse and evaluation the conditional expression.
1553 IdentifierInfo *IfNDefMacro = 0;
1554 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Nuno Lopes0049db62008-06-01 18:31:24 +00001556
1557 // If this condition is equivalent to #ifndef X, and if this is the first
1558 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001559 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001560 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001561 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001562 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001563 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001564 }
1565
Chris Lattner141e71f2008-03-09 01:54:53 +00001566 // Should we include the stuff contained by this directive?
1567 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001568 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001569 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001570 /*foundnonskip*/true, /*foundelse*/false);
1571 } else {
1572 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001573 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001574 /*FoundElse*/false);
1575 }
1576}
1577
1578/// HandleEndifDirective - Implements the #endif directive.
1579///
1580void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1581 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Chris Lattner141e71f2008-03-09 01:54:53 +00001583 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001584 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Chris Lattner141e71f2008-03-09 01:54:53 +00001586 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001587 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001588 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001589 Diag(EndifToken, diag::err_pp_endif_without_if);
1590 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001591 }
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Chris Lattner141e71f2008-03-09 01:54:53 +00001593 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001594 if (CurPPLexer->getConditionalStackDepth() == 0)
1595 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Ted Kremenek60e45d42008-11-18 00:34:22 +00001597 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001598 "This code should only be reachable in the non-skipping case!");
1599}
1600
1601
1602void Preprocessor::HandleElseDirective(Token &Result) {
1603 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Chris Lattner141e71f2008-03-09 01:54:53 +00001605 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001606 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Chris Lattner141e71f2008-03-09 01:54:53 +00001608 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001609 if (CurPPLexer->popConditionalLevel(CI)) {
1610 Diag(Result, diag::pp_err_else_without_if);
1611 return;
1612 }
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Chris Lattner141e71f2008-03-09 01:54:53 +00001614 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001615 if (CurPPLexer->getConditionalStackDepth() == 0)
1616 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001617
1618 // If this is a #else with a #else before it, report the error.
1619 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Chris Lattner141e71f2008-03-09 01:54:53 +00001621 // Finally, skip the rest of the contents of this block and return the first
1622 // token after it.
1623 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1624 /*FoundElse*/true);
1625}
1626
1627void Preprocessor::HandleElifDirective(Token &ElifToken) {
1628 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Chris Lattner141e71f2008-03-09 01:54:53 +00001630 // #elif directive in a non-skipping conditional... start skipping.
1631 // We don't care what the condition is, because we will always skip it (since
1632 // the block immediately before it was included).
1633 DiscardUntilEndOfDirective();
1634
1635 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001636 if (CurPPLexer->popConditionalLevel(CI)) {
1637 Diag(ElifToken, diag::pp_err_elif_without_if);
1638 return;
1639 }
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Chris Lattner141e71f2008-03-09 01:54:53 +00001641 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001642 if (CurPPLexer->getConditionalStackDepth() == 0)
1643 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Chris Lattner141e71f2008-03-09 01:54:53 +00001645 // If this is a #elif with a #else before it, report the error.
1646 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1647
1648 // Finally, skip the rest of the contents of this block and return the first
1649 // token after it.
1650 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1651 /*FoundElse*/CI.FoundElse);
1652}
1653