blob: dc5b204216e85aa59a1b503f365bd7ea934742e8 [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 Lattner804f6522010-01-10 00:24:58 +0000405 SourceLocation FilenameTokLoc,
Chris Lattner10725092008-03-09 04:17:44 +0000406 bool isAngled,
407 const DirectoryLookup *FromDir,
408 const DirectoryLookup *&CurDir) {
409 // If the header lookup mechanism may be relative to the current file, pass in
410 // info about where the current file is.
411 const FileEntry *CurFileEnt = 0;
412 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000413 FileID FID = getCurrentFileLexer()->getFileID();
414 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000416 // If there is no file entry associated with this file, it must be the
417 // predefines buffer. Any other file is not lexed with a normal lexer, so
418 // it won't be scanned for preprocessor directives. If we have the
419 // predefines buffer, resolve #include references (which come from the
420 // -include command line argument) as if they came from the main file, this
421 // affects file lookup etc.
422 if (CurFileEnt == 0) {
423 FID = SourceMgr.getMainFileID();
424 CurFileEnt = SourceMgr.getFileEntryForID(FID);
425 }
Chris Lattner10725092008-03-09 04:17:44 +0000426 }
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Chris Lattner10725092008-03-09 04:17:44 +0000428 // Do a standard file entry lookup.
429 CurDir = CurDirLookup;
430 const FileEntry *FE =
Chris Lattnera1394812010-01-10 01:35:12 +0000431 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner804f6522010-01-10 00:24:58 +0000432 if (FE) {
433 // Warn about normal quoted #include from framework headers. Since
434 // framework headers are published (both public and private ones) they
Chris Lattnerc1abafc2010-01-10 00:35:27 +0000435 // should not do relative searches, they should do an include with the
436 // framework path included.
Chris Lattner804f6522010-01-10 00:24:58 +0000437 if (!isAngled && CurDir && FilenameTokLoc.isValid() &&
438 CurDir->isFramework() && CurDir == CurDirLookup)
439 Diag(FilenameTokLoc, diag::warn_pp_relative_include_from_framework);
440 return FE;
441 }
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;
Chris Lattner1d9c54d2009-12-14 04:54:40 +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];
627 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin);
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000629 // Verify that we have a simple digit-sequence, and compute the value. This
630 // is always a simple digit string computed in decimal, so we do this manually
631 // here.
632 Val = 0;
633 for (unsigned i = 0; i != ActualLength; ++i) {
634 if (!isdigit(DigitTokBegin[i])) {
635 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
636 diag::err_pp_line_digit_sequence);
637 PP.DiscardUntilEndOfDirective();
638 return true;
639 }
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000641 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
642 if (NextVal < Val) { // overflow.
643 PP.Diag(DigitTok, DiagID);
644 PP.DiscardUntilEndOfDirective();
645 return true;
646 }
647 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000648 }
Mike Stump1eb44332009-09-09 15:08:12 +0000649
650 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000651 if (Val == 0) {
652 PP.Diag(DigitTok, DiagID);
653 PP.DiscardUntilEndOfDirective();
654 return true;
655 }
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000657 if (DigitTokBegin[0] == '0')
658 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Chris Lattner478a18e2009-01-26 06:19:46 +0000660 return false;
661}
662
Mike Stump1eb44332009-09-09 15:08:12 +0000663/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000664/// acceptable forms are:
665/// # line digit-sequence
666/// # line digit-sequence "s-char-sequence"
667void Preprocessor::HandleLineDirective(Token &Tok) {
668 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
669 // expanded.
670 Token DigitTok;
671 Lex(DigitTok);
672
Chris Lattner359cc442009-01-26 05:29:08 +0000673 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000674 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000675 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000676 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000677
Chris Lattner478a18e2009-01-26 06:19:46 +0000678 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
679 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000680 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
681 if (LineNo >= LineLimit)
682 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattner5b9a5042009-01-26 07:57:50 +0000684 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000685 Token StrTok;
686 Lex(StrTok);
687
688 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
689 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000690 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000691 ; // ok
692 else if (StrTok.isNot(tok::string_literal)) {
693 Diag(StrTok, diag::err_pp_line_invalid_filename);
694 DiscardUntilEndOfDirective();
695 return;
696 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000697 // Parse and validate the string, converting it into a unique ID.
698 StringLiteralParser Literal(&StrTok, 1, *this);
699 assert(!Literal.AnyWide && "Didn't allow wide strings in");
700 if (Literal.hadError)
701 return DiscardUntilEndOfDirective();
702 if (Literal.Pascal) {
703 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
704 return DiscardUntilEndOfDirective();
705 }
706 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
707 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattnerab82f412009-04-17 23:30:53 +0000709 // Verify that there is nothing after the string, other than EOM. Because
710 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
711 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000712 }
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattner4c4ea172009-02-03 21:52:55 +0000714 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Chris Lattner16629382009-03-27 17:13:49 +0000716 if (Callbacks)
717 Callbacks->FileChanged(DigitTok.getLocation(), PPCallbacks::RenameFile,
718 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000719}
720
Chris Lattner478a18e2009-01-26 06:19:46 +0000721/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
722/// marker directive.
723static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
724 bool &IsSystemHeader, bool &IsExternCHeader,
725 Preprocessor &PP) {
726 unsigned FlagVal;
727 Token FlagTok;
728 PP.Lex(FlagTok);
729 if (FlagTok.is(tok::eom)) return false;
730 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
731 return true;
732
733 if (FlagVal == 1) {
734 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Chris Lattner478a18e2009-01-26 06:19:46 +0000736 PP.Lex(FlagTok);
737 if (FlagTok.is(tok::eom)) return false;
738 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
739 return true;
740 } else if (FlagVal == 2) {
741 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Chris Lattner137b6a62009-02-04 06:25:26 +0000743 SourceManager &SM = PP.getSourceManager();
744 // If we are leaving the current presumed file, check to make sure the
745 // presumed include stack isn't empty!
746 FileID CurFileID =
747 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
748 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Chris Lattner137b6a62009-02-04 06:25:26 +0000750 // If there is no include loc (main file) or if the include loc is in a
751 // different physical file, then we aren't in a "1" line marker flag region.
752 SourceLocation IncLoc = PLoc.getIncludeLoc();
753 if (IncLoc.isInvalid() ||
754 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
755 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
756 PP.DiscardUntilEndOfDirective();
757 return true;
758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Chris Lattner478a18e2009-01-26 06:19:46 +0000760 PP.Lex(FlagTok);
761 if (FlagTok.is(tok::eom)) return false;
762 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
763 return true;
764 }
765
766 // We must have 3 if there are still flags.
767 if (FlagVal != 3) {
768 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000769 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000770 return true;
771 }
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Chris Lattner478a18e2009-01-26 06:19:46 +0000773 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Chris Lattner478a18e2009-01-26 06:19:46 +0000775 PP.Lex(FlagTok);
776 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000777 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000778 return true;
779
780 // We must have 4 if there is yet another flag.
781 if (FlagVal != 4) {
782 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000783 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000784 return true;
785 }
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattner478a18e2009-01-26 06:19:46 +0000787 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Chris Lattner478a18e2009-01-26 06:19:46 +0000789 PP.Lex(FlagTok);
790 if (FlagTok.is(tok::eom)) return false;
791
792 // There are no more valid flags here.
793 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000794 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000795 return true;
796}
797
798/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
799/// one of the following forms:
800///
801/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000802/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000803/// # 42 "file" ('1' | '2')? '3' '4'?
804///
805void Preprocessor::HandleDigitDirective(Token &DigitTok) {
806 // Validate the number and convert it to an unsigned. GNU does not have a
807 // line # limit other than it fit in 32-bits.
808 unsigned LineNo;
809 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
810 *this))
811 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Chris Lattner478a18e2009-01-26 06:19:46 +0000813 Token StrTok;
814 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Chris Lattner478a18e2009-01-26 06:19:46 +0000816 bool IsFileEntry = false, IsFileExit = false;
817 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000818 int FilenameID = -1;
819
Chris Lattner478a18e2009-01-26 06:19:46 +0000820 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
821 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000822 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000823 ; // ok
824 else if (StrTok.isNot(tok::string_literal)) {
825 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000826 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000827 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000828 // Parse and validate the string, converting it into a unique ID.
829 StringLiteralParser Literal(&StrTok, 1, *this);
830 assert(!Literal.AnyWide && "Didn't allow wide strings in");
831 if (Literal.hadError)
832 return DiscardUntilEndOfDirective();
833 if (Literal.Pascal) {
834 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
835 return DiscardUntilEndOfDirective();
836 }
837 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
838 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattner478a18e2009-01-26 06:19:46 +0000840 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000841 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000842 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000843 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000844 }
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Chris Lattner9d79eba2009-02-04 05:21:58 +0000846 // Create a line note with this information.
847 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000848 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000849 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Chris Lattner16629382009-03-27 17:13:49 +0000851 // If the preprocessor has callbacks installed, notify them of the #line
852 // change. This is used so that the line marker comes out in -E mode for
853 // example.
854 if (Callbacks) {
855 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
856 if (IsFileEntry)
857 Reason = PPCallbacks::EnterFile;
858 else if (IsFileExit)
859 Reason = PPCallbacks::ExitFile;
860 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
861 if (IsExternCHeader)
862 FileKind = SrcMgr::C_ExternCSystem;
863 else if (IsSystemHeader)
864 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Chris Lattner16629382009-03-27 17:13:49 +0000866 Callbacks->FileChanged(DigitTok.getLocation(), Reason, FileKind);
867 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000868}
869
870
Chris Lattner099dd052009-01-26 05:30:54 +0000871/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
872///
Mike Stump1eb44332009-09-09 15:08:12 +0000873void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000874 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000875 // PTH doesn't emit #warning or #error directives.
876 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000877 return CurPTHLexer->DiscardToEndOfLine();
878
Chris Lattner141e71f2008-03-09 01:54:53 +0000879 // Read the rest of the line raw. We do this because we don't want macros
880 // to be expanded and we don't require that the tokens be valid preprocessing
881 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
882 // collapse multiple consequtive white space between tokens, but this isn't
883 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000884 std::string Message = CurLexer->ReadToEndOfLine();
885 if (isWarning)
886 Diag(Tok, diag::pp_hash_warning) << Message;
887 else
888 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000889}
890
891/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
892///
893void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
894 // Yes, this directive is an extension.
895 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattner141e71f2008-03-09 01:54:53 +0000897 // Read the string argument.
898 Token StrTok;
899 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chris Lattner141e71f2008-03-09 01:54:53 +0000901 // If the token kind isn't a string, it's a malformed directive.
902 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000903 StrTok.isNot(tok::wide_string_literal)) {
904 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000905 if (StrTok.isNot(tok::eom))
906 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000907 return;
908 }
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Chris Lattner141e71f2008-03-09 01:54:53 +0000910 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000911 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000912
913 if (Callbacks)
914 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
915}
916
917//===----------------------------------------------------------------------===//
918// Preprocessor Include Directive Handling.
919//===----------------------------------------------------------------------===//
920
921/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
922/// checked and spelled filename, e.g. as an operand of #include. This returns
923/// true if the input filename was in <>'s or false if it were in ""'s. The
924/// caller is expected to provide a buffer that is large enough to hold the
925/// spelling of the filename, but is also expected to handle the case when
926/// this method decides to use a different buffer.
927bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000928 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000929 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000930 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Chris Lattner141e71f2008-03-09 01:54:53 +0000932 // Make sure the filename is <x> or "x".
933 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000934 if (Buffer[0] == '<') {
935 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000936 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000937 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000938 return true;
939 }
940 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +0000941 } else if (Buffer[0] == '"') {
942 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000943 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000944 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000945 return true;
946 }
947 isAngled = false;
948 } else {
949 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000950 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000951 return true;
952 }
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Chris Lattner141e71f2008-03-09 01:54:53 +0000954 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +0000955 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000956 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000957 Buffer = llvm::StringRef();
958 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattner141e71f2008-03-09 01:54:53 +0000961 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +0000962 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +0000963 return isAngled;
964}
965
966/// ConcatenateIncludeName - Handle cases where the #include name is expanded
967/// from a macro as multiple tokens, which need to be glued together. This
968/// occurs for code like:
969/// #define FOO <a/b.h>
970/// #include FOO
971/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
972///
973/// This code concatenates and consumes tokens up to the '>' token. It returns
974/// false if the > was found, otherwise it returns true if it finds and consumes
975/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +0000976bool Preprocessor::ConcatenateIncludeName(
977 llvm::SmallVector<char, 128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000978 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +0000979
John Thompsona28cc092009-10-30 13:49:06 +0000980 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000981 while (CurTok.isNot(tok::eom)) {
982 // Append the spelling of this token to the buffer. If there was a space
983 // before it, add it now.
984 if (CurTok.hasLeadingSpace())
985 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chris Lattner141e71f2008-03-09 01:54:53 +0000987 // Get the spelling of the token, directly into FilenameBuffer if possible.
988 unsigned PreAppendSize = FilenameBuffer.size();
989 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattner141e71f2008-03-09 01:54:53 +0000991 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +0000992 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner141e71f2008-03-09 01:54:53 +0000994 // If the token was spelled somewhere else, copy it into FilenameBuffer.
995 if (BufPtr != &FilenameBuffer[PreAppendSize])
996 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Chris Lattner141e71f2008-03-09 01:54:53 +0000998 // Resize FilenameBuffer to the correct size.
999 if (CurTok.getLength() != ActualLen)
1000 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chris Lattner141e71f2008-03-09 01:54:53 +00001002 // If we found the '>' marker, return success.
1003 if (CurTok.is(tok::greater))
1004 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001005
John Thompsona28cc092009-10-30 13:49:06 +00001006 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001007 }
1008
1009 // If we hit the eom marker, emit an error and return true so that the caller
1010 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001011 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001012 return true;
1013}
1014
1015/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1016/// file to be included from the lexer, then include it! This is a common
1017/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001018/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001019/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001020void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1021 const DirectoryLookup *LookupFrom,
1022 bool isImport) {
1023
1024 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001025 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Chris Lattner141e71f2008-03-09 01:54:53 +00001027 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001028 llvm::SmallString<128> FilenameBuffer;
1029 llvm::StringRef Filename;
Chris Lattner141e71f2008-03-09 01:54:53 +00001030
1031 switch (FilenameTok.getKind()) {
1032 case tok::eom:
1033 // If the token kind is EOM, the error has already been diagnosed.
1034 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Chris Lattner141e71f2008-03-09 01:54:53 +00001036 case tok::angle_string_literal:
1037 case tok::string_literal: {
1038 FilenameBuffer.resize(FilenameTok.getLength());
Chris Lattnera1394812010-01-10 01:35:12 +00001039 const char *FilenameStart = &FilenameBuffer[0];
Chris Lattner141e71f2008-03-09 01:54:53 +00001040 unsigned Len = getSpelling(FilenameTok, FilenameStart);
Chris Lattnera1394812010-01-10 01:35:12 +00001041 Filename = llvm::StringRef(FilenameStart, Len);
Chris Lattner141e71f2008-03-09 01:54:53 +00001042 break;
1043 }
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Chris Lattner141e71f2008-03-09 01:54:53 +00001045 case tok::less:
1046 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1047 // case, glue the tokens together into FilenameBuffer and interpret those.
1048 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001049 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001050 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001051 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001052 break;
1053 default:
1054 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1055 DiscardUntilEndOfDirective();
1056 return;
1057 }
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Chris Lattnera1394812010-01-10 01:35:12 +00001059 bool isAngled =
1060 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001061 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1062 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001063 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001064 DiscardUntilEndOfDirective();
1065 return;
1066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001068 // Verify that there is nothing after the filename, other than EOM. Note that
1069 // we allow macros that expand to nothing after the filename, because this
1070 // falls into the category of "#include pp-tokens new-line" specified in
1071 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001072 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001073
1074 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001075 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1076 Diag(FilenameTok, diag::err_pp_include_too_deep);
1077 return;
1078 }
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Chris Lattner141e71f2008-03-09 01:54:53 +00001080 // Search include directories.
1081 const DirectoryLookup *CurDir;
Chris Lattnera1394812010-01-10 01:35:12 +00001082 const FileEntry *File = LookupFile(Filename, FilenameTok.getLocation(),
Chris Lattner141e71f2008-03-09 01:54:53 +00001083 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001084 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001085 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001086 return;
1087 }
Chris Lattner804f6522010-01-10 00:24:58 +00001088
Chris Lattner72181832008-09-26 20:12:23 +00001089 // Ask HeaderInfo if we should enter this #include file. If not, #including
1090 // this file will have no effect.
1091 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +00001092 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Chris Lattner72181832008-09-26 20:12:23 +00001094 // The #included file will be considered to be a system header if either it is
1095 // in a system include directory, or if the #includer is a system include
1096 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001097 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001098 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001099 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Chris Lattner141e71f2008-03-09 01:54:53 +00001101 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001102 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1103 FileCharacter);
1104 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001105 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001106 return;
1107 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001108
1109 // Finally, if all is good, enter the new file!
Chris Lattner39d98412009-12-01 22:52:33 +00001110 std::string ErrorStr;
Daniel Dunbar63ceaa32009-12-06 09:19:12 +00001111 if (EnterSourceFile(FID, CurDir, ErrorStr))
Chris Lattner6e290142009-11-30 04:18:44 +00001112 Diag(FilenameTok, diag::err_pp_error_opening_file)
Chris Lattner39d98412009-12-01 22:52:33 +00001113 << std::string(SourceMgr.getFileEntryForID(FID)->getName()) << ErrorStr;
Chris Lattner141e71f2008-03-09 01:54:53 +00001114}
1115
1116/// HandleIncludeNextDirective - Implements #include_next.
1117///
1118void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1119 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Chris Lattner141e71f2008-03-09 01:54:53 +00001121 // #include_next is like #include, except that we start searching after
1122 // the current found directory. If we can't do this, issue a
1123 // diagnostic.
1124 const DirectoryLookup *Lookup = CurDirLookup;
1125 if (isInPrimaryFile()) {
1126 Lookup = 0;
1127 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1128 } else if (Lookup == 0) {
1129 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1130 } else {
1131 // Start looking up in the next directory.
1132 ++Lookup;
1133 }
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Chris Lattner141e71f2008-03-09 01:54:53 +00001135 return HandleIncludeDirective(IncludeNextTok, Lookup);
1136}
1137
1138/// HandleImportDirective - Implements #import.
1139///
1140void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001141 if (!Features.ObjC1) // #import is standard for ObjC.
1142 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Chris Lattner141e71f2008-03-09 01:54:53 +00001144 return HandleIncludeDirective(ImportTok, 0, true);
1145}
1146
Chris Lattnerde076652009-04-08 18:46:40 +00001147/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1148/// pseudo directive in the predefines buffer. This handles it by sucking all
1149/// tokens through the preprocessor and discarding them (only keeping the side
1150/// effects on the preprocessor).
1151void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1152 // This directive should only occur in the predefines buffer. If not, emit an
1153 // error and reject it.
1154 SourceLocation Loc = IncludeMacrosTok.getLocation();
1155 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1156 Diag(IncludeMacrosTok.getLocation(),
1157 diag::pp_include_macros_out_of_predefines);
1158 DiscardUntilEndOfDirective();
1159 return;
1160 }
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Chris Lattnerfd105112009-04-08 20:53:24 +00001162 // Treat this as a normal #include for checking purposes. If this is
1163 // successful, it will push a new lexer onto the include stack.
1164 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Chris Lattnerfd105112009-04-08 20:53:24 +00001166 Token TmpTok;
1167 do {
1168 Lex(TmpTok);
1169 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1170 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001171}
1172
Chris Lattner141e71f2008-03-09 01:54:53 +00001173//===----------------------------------------------------------------------===//
1174// Preprocessor Macro Directive Handling.
1175//===----------------------------------------------------------------------===//
1176
1177/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1178/// definition has just been read. Lex the rest of the arguments and the
1179/// closing ), updating MI with what we learn. Return true if an error occurs
1180/// parsing the arg list.
1181bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1182 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Chris Lattner141e71f2008-03-09 01:54:53 +00001184 Token Tok;
1185 while (1) {
1186 LexUnexpandedToken(Tok);
1187 switch (Tok.getKind()) {
1188 case tok::r_paren:
1189 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001190 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001191 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001192 // Otherwise we have #define FOO(A,)
1193 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1194 return true;
1195 case tok::ellipsis: // #define X(... -> C99 varargs
1196 // Warn if use of C99 feature in non-C99 mode.
1197 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1198
1199 // Lex the token after the identifier.
1200 LexUnexpandedToken(Tok);
1201 if (Tok.isNot(tok::r_paren)) {
1202 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1203 return true;
1204 }
1205 // Add the __VA_ARGS__ identifier as an argument.
1206 Arguments.push_back(Ident__VA_ARGS__);
1207 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001208 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001209 return false;
1210 case tok::eom: // #define X(
1211 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1212 return true;
1213 default:
1214 // Handle keywords and identifiers here to accept things like
1215 // #define Foo(for) for.
1216 IdentifierInfo *II = Tok.getIdentifierInfo();
1217 if (II == 0) {
1218 // #define X(1
1219 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1220 return true;
1221 }
1222
1223 // If this is already used as an argument, it is used multiple times (e.g.
1224 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001225 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001226 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001227 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001228 return true;
1229 }
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Chris Lattner141e71f2008-03-09 01:54:53 +00001231 // Add the argument to the macro info.
1232 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Chris Lattner141e71f2008-03-09 01:54:53 +00001234 // Lex the token after the identifier.
1235 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Chris Lattner141e71f2008-03-09 01:54:53 +00001237 switch (Tok.getKind()) {
1238 default: // #define X(A B
1239 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1240 return true;
1241 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001242 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001243 return false;
1244 case tok::comma: // #define X(A,
1245 break;
1246 case tok::ellipsis: // #define X(A... -> GCC extension
1247 // Diagnose extension.
1248 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Chris Lattner141e71f2008-03-09 01:54:53 +00001250 // Lex the token after the identifier.
1251 LexUnexpandedToken(Tok);
1252 if (Tok.isNot(tok::r_paren)) {
1253 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1254 return true;
1255 }
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Chris Lattner141e71f2008-03-09 01:54:53 +00001257 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001258 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001259 return false;
1260 }
1261 }
1262 }
1263}
1264
1265/// HandleDefineDirective - Implements #define. This consumes the entire macro
1266/// line then lets the caller lex the next real token.
1267void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1268 ++NumDefined;
1269
1270 Token MacroNameTok;
1271 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Chris Lattner141e71f2008-03-09 01:54:53 +00001273 // Error reading macro name? If so, diagnostic already issued.
1274 if (MacroNameTok.is(tok::eom))
1275 return;
1276
Chris Lattner2451b522009-04-21 04:46:33 +00001277 Token LastTok = MacroNameTok;
1278
Chris Lattner141e71f2008-03-09 01:54:53 +00001279 // If we are supposed to keep comments in #defines, reenable comment saving
1280 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001281 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Chris Lattner141e71f2008-03-09 01:54:53 +00001283 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001284 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Chris Lattner141e71f2008-03-09 01:54:53 +00001286 Token Tok;
1287 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Chris Lattner141e71f2008-03-09 01:54:53 +00001289 // If this is a function-like macro definition, parse the argument list,
1290 // marking each of the identifiers as being used as macro arguments. Also,
1291 // check other constraints on the first token of the macro body.
1292 if (Tok.is(tok::eom)) {
1293 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001294 } else if (Tok.hasLeadingSpace()) {
1295 // This is a normal token with leading space. Clear the leading space
1296 // marker on the first token to get proper expansion.
1297 Tok.clearFlag(Token::LeadingSpace);
1298 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001299 // This is a function-like macro definition. Read the argument list.
1300 MI->setIsFunctionLike();
1301 if (ReadMacroDefinitionArgList(MI)) {
1302 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001303 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001304 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001305 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001306 DiscardUntilEndOfDirective();
1307 return;
1308 }
1309
Chris Lattner8fde5972009-04-19 18:26:34 +00001310 // If this is a definition of a variadic C99 function-like macro, not using
1311 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Chris Lattner8fde5972009-04-19 18:26:34 +00001313 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1314 // This gets unpoisoned where it is allowed.
1315 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1316 if (MI->isC99Varargs())
1317 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Chris Lattner141e71f2008-03-09 01:54:53 +00001319 // Read the first token after the arg list for down below.
1320 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001321 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001322 // C99 requires whitespace between the macro definition and the body. Emit
1323 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001324 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001325 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001326 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1327 // first character of a replacement list is not a character required by
1328 // subclause 5.2.1, then there shall be white-space separation between the
1329 // identifier and the replacement list.". 5.2.1 lists this set:
1330 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1331 // is irrelevant here.
1332 bool isInvalid = false;
1333 if (Tok.is(tok::at)) // @ is not in the list above.
1334 isInvalid = true;
1335 else if (Tok.is(tok::unknown)) {
1336 // If we have an unknown token, it is something strange like "`". Since
1337 // all of valid characters would have lexed into a single character
1338 // token of some sort, we know this is not a valid case.
1339 isInvalid = true;
1340 }
1341 if (isInvalid)
1342 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1343 else
1344 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001345 }
Chris Lattner2451b522009-04-21 04:46:33 +00001346
1347 if (!Tok.is(tok::eom))
1348 LastTok = Tok;
1349
Chris Lattner141e71f2008-03-09 01:54:53 +00001350 // Read the rest of the macro body.
1351 if (MI->isObjectLike()) {
1352 // Object-like macros are very simple, just read their body.
1353 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001354 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001355 MI->AddTokenToBody(Tok);
1356 // Get the next token of the macro.
1357 LexUnexpandedToken(Tok);
1358 }
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Chris Lattner141e71f2008-03-09 01:54:53 +00001360 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001361 // Otherwise, read the body of a function-like macro. While we are at it,
1362 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1363 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001364 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001365 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001366
Chris Lattner141e71f2008-03-09 01:54:53 +00001367 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001368 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Chris Lattner141e71f2008-03-09 01:54:53 +00001370 // Get the next token of the macro.
1371 LexUnexpandedToken(Tok);
1372 continue;
1373 }
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Chris Lattner141e71f2008-03-09 01:54:53 +00001375 // Get the next token of the macro.
1376 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Chris Lattner32404692009-05-25 17:16:10 +00001378 // Check for a valid macro arg identifier.
1379 if (Tok.getIdentifierInfo() == 0 ||
1380 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1381
1382 // If this is assembler-with-cpp mode, we accept random gibberish after
1383 // the '#' because '#' is often a comment character. However, change
1384 // the kind of the token to tok::unknown so that the preprocessor isn't
1385 // confused.
1386 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1387 LastTok.setKind(tok::unknown);
1388 } else {
1389 Diag(Tok, diag::err_pp_stringize_not_parameter);
1390 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Chris Lattner32404692009-05-25 17:16:10 +00001392 // Disable __VA_ARGS__ again.
1393 Ident__VA_ARGS__->setIsPoisoned(true);
1394 return;
1395 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001396 }
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Chris Lattner32404692009-05-25 17:16:10 +00001398 // Things look ok, add the '#' and param name tokens to the macro.
1399 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001400 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001401 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Chris Lattner141e71f2008-03-09 01:54:53 +00001403 // Get the next token of the macro.
1404 LexUnexpandedToken(Tok);
1405 }
1406 }
Mike Stump1eb44332009-09-09 15:08:12 +00001407
1408
Chris Lattner141e71f2008-03-09 01:54:53 +00001409 // Disable __VA_ARGS__ again.
1410 Ident__VA_ARGS__->setIsPoisoned(true);
1411
1412 // Check that there is no paste (##) operator at the begining or end of the
1413 // replacement list.
1414 unsigned NumTokens = MI->getNumTokens();
1415 if (NumTokens != 0) {
1416 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1417 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001418 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001419 return;
1420 }
1421 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1422 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001423 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001424 return;
1425 }
1426 }
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Chris Lattner141e71f2008-03-09 01:54:53 +00001428 // If this is the primary source file, remember that this macro hasn't been
1429 // used yet.
1430 if (isInPrimaryFile())
1431 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001432
1433 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Chris Lattner141e71f2008-03-09 01:54:53 +00001435 // Finally, if this identifier already had a macro defined for it, verify that
1436 // the macro bodies are identical and free the old definition.
1437 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001438 // It is very common for system headers to have tons of macro redefinitions
1439 // and for warnings to be disabled in system headers. If this is the case,
1440 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001441 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001442 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1443 if (!OtherMI->isUsed())
1444 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001445
Chris Lattner41c3ae12009-01-16 19:50:11 +00001446 // Macros must be identical. This means all tokes and whitespace
1447 // separation must be the same. C99 6.10.3.2.
1448 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1449 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1450 << MacroNameTok.getIdentifierInfo();
1451 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1452 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001453 }
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Ted Kremenek0ea76722008-12-15 19:56:42 +00001455 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001456 }
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Chris Lattner141e71f2008-03-09 01:54:53 +00001458 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001460 // If the callbacks want to know, tell them about the macro definition.
1461 if (Callbacks)
1462 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001463}
1464
1465/// HandleUndefDirective - Implements #undef.
1466///
1467void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1468 ++NumUndefined;
1469
1470 Token MacroNameTok;
1471 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Chris Lattner141e71f2008-03-09 01:54:53 +00001473 // Error reading macro name? If so, diagnostic already issued.
1474 if (MacroNameTok.is(tok::eom))
1475 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Chris Lattner141e71f2008-03-09 01:54:53 +00001477 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001478 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Chris Lattner141e71f2008-03-09 01:54:53 +00001480 // Okay, we finally have a valid identifier to undef.
1481 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Chris Lattner141e71f2008-03-09 01:54:53 +00001483 // If the macro is not defined, this is a noop undef, just return.
1484 if (MI == 0) return;
1485
1486 if (!MI->isUsed())
1487 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001488
1489 // If the callbacks want to know, tell them about the macro #undef.
1490 if (Callbacks)
1491 Callbacks->MacroUndefined(MacroNameTok.getIdentifierInfo(), MI);
1492
Chris Lattner141e71f2008-03-09 01:54:53 +00001493 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001494 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001495 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1496}
1497
1498
1499//===----------------------------------------------------------------------===//
1500// Preprocessor Conditional Directive Handling.
1501//===----------------------------------------------------------------------===//
1502
1503/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1504/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1505/// if any tokens have been returned or pp-directives activated before this
1506/// #ifndef has been lexed.
1507///
1508void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1509 bool ReadAnyTokensBeforeDirective) {
1510 ++NumIf;
1511 Token DirectiveTok = Result;
1512
1513 Token MacroNameTok;
1514 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Chris Lattner141e71f2008-03-09 01:54:53 +00001516 // Error reading macro name? If so, diagnostic already issued.
1517 if (MacroNameTok.is(tok::eom)) {
1518 // Skip code until we get to #endif. This helps with recovery by not
1519 // emitting an error when the #endif is reached.
1520 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1521 /*Foundnonskip*/false, /*FoundElse*/false);
1522 return;
1523 }
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Chris Lattner141e71f2008-03-09 01:54:53 +00001525 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001526 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001527
Ted Kremenek60e45d42008-11-18 00:34:22 +00001528 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001529 // If the start of a top-level #ifdef, inform MIOpt.
1530 if (!ReadAnyTokensBeforeDirective) {
1531 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001532 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001533 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001534 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001535 }
1536
1537 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1538 MacroInfo *MI = getMacroInfo(MII);
1539
1540 // If there is a macro, process it.
1541 if (MI) // Mark it used.
1542 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Chris Lattner141e71f2008-03-09 01:54:53 +00001544 // Should we include the stuff contained by this directive?
1545 if (!MI == isIfndef) {
1546 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001547 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1548 /*wasskip*/false, /*foundnonskip*/true,
1549 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001550 } else {
1551 // No, skip the contents of this block and return the first token after it.
1552 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001553 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001554 /*FoundElse*/false);
1555 }
1556}
1557
1558/// HandleIfDirective - Implements the #if directive.
1559///
1560void Preprocessor::HandleIfDirective(Token &IfToken,
1561 bool ReadAnyTokensBeforeDirective) {
1562 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Chris Lattner141e71f2008-03-09 01:54:53 +00001564 // Parse and evaluation the conditional expression.
1565 IdentifierInfo *IfNDefMacro = 0;
1566 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Nuno Lopes0049db62008-06-01 18:31:24 +00001568
1569 // If this condition is equivalent to #ifndef X, and if this is the first
1570 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001571 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001572 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001573 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001574 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001575 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001576 }
1577
Chris Lattner141e71f2008-03-09 01:54:53 +00001578 // Should we include the stuff contained by this directive?
1579 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001580 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001581 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001582 /*foundnonskip*/true, /*foundelse*/false);
1583 } else {
1584 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001585 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001586 /*FoundElse*/false);
1587 }
1588}
1589
1590/// HandleEndifDirective - Implements the #endif directive.
1591///
1592void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1593 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Chris Lattner141e71f2008-03-09 01:54:53 +00001595 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001596 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Chris Lattner141e71f2008-03-09 01:54:53 +00001598 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001599 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001600 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001601 Diag(EndifToken, diag::err_pp_endif_without_if);
1602 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001603 }
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Chris Lattner141e71f2008-03-09 01:54:53 +00001605 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001606 if (CurPPLexer->getConditionalStackDepth() == 0)
1607 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Ted Kremenek60e45d42008-11-18 00:34:22 +00001609 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001610 "This code should only be reachable in the non-skipping case!");
1611}
1612
1613
1614void Preprocessor::HandleElseDirective(Token &Result) {
1615 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Chris Lattner141e71f2008-03-09 01:54:53 +00001617 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001618 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Chris Lattner141e71f2008-03-09 01:54:53 +00001620 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001621 if (CurPPLexer->popConditionalLevel(CI)) {
1622 Diag(Result, diag::pp_err_else_without_if);
1623 return;
1624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Chris Lattner141e71f2008-03-09 01:54:53 +00001626 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001627 if (CurPPLexer->getConditionalStackDepth() == 0)
1628 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001629
1630 // If this is a #else with a #else before it, report the error.
1631 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Chris Lattner141e71f2008-03-09 01:54:53 +00001633 // Finally, skip the rest of the contents of this block and return the first
1634 // token after it.
1635 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1636 /*FoundElse*/true);
1637}
1638
1639void Preprocessor::HandleElifDirective(Token &ElifToken) {
1640 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Chris Lattner141e71f2008-03-09 01:54:53 +00001642 // #elif directive in a non-skipping conditional... start skipping.
1643 // We don't care what the condition is, because we will always skip it (since
1644 // the block immediately before it was included).
1645 DiscardUntilEndOfDirective();
1646
1647 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001648 if (CurPPLexer->popConditionalLevel(CI)) {
1649 Diag(ElifToken, diag::pp_err_elif_without_if);
1650 return;
1651 }
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Chris Lattner141e71f2008-03-09 01:54:53 +00001653 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001654 if (CurPPLexer->getConditionalStackDepth() == 0)
1655 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Chris Lattner141e71f2008-03-09 01:54:53 +00001657 // If this is a #elif with a #else before it, report the error.
1658 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1659
1660 // Finally, skip the rest of the contents of this block and return the first
1661 // token after it.
1662 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1663 /*FoundElse*/CI.FoundElse);
1664}
1665