blob: bfb6641a758d4a9a073799e38ca9b2690b9e5cc5 [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"
Douglas Gregorf44e8542010-08-24 19:08:16 +000019#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor80c60f72010-09-09 22:45:38 +000020#include "clang/Lex/Pragma.h"
Chris Lattner6e290142009-11-30 04:18:44 +000021#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000023#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000024using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Utility Methods for Preprocessor Directive Handling.
28//===----------------------------------------------------------------------===//
29
Chris Lattnerf47724b2010-08-17 15:55:45 +000030MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenek9714a232010-10-19 22:15:20 +000031 MacroInfoChain *MIChain;
Mike Stump1eb44332009-09-09 15:08:12 +000032
Ted Kremenek9714a232010-10-19 22:15:20 +000033 if (MICache) {
34 MIChain = MICache;
35 MICache = MICache->Next;
Ted Kremenekaf8fa252010-10-19 18:16:54 +000036 }
Ted Kremenek9714a232010-10-19 22:15:20 +000037 else {
38 MIChain = BP.Allocate<MacroInfoChain>();
39 }
40
41 MIChain->Next = MIChainHead;
42 MIChain->Prev = 0;
43 if (MIChainHead)
44 MIChainHead->Prev = MIChain;
45 MIChainHead = MIChain;
46
47 return &(MIChain->MI);
Chris Lattnerf47724b2010-08-17 15:55:45 +000048}
49
50MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
51 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000052 new (MI) MacroInfo(L);
53 return MI;
54}
55
Chris Lattnerf47724b2010-08-17 15:55:45 +000056MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
57 MacroInfo *MI = AllocateMacroInfo();
58 new (MI) MacroInfo(MacroToClone, BP);
59 return MI;
60}
61
Chris Lattner0301b3f2009-02-20 22:19:20 +000062/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
63/// be reused for allocating new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000064void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenek9714a232010-10-19 22:15:20 +000065 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
66 if (MacroInfoChain *Prev = MIChain->Prev) {
67 MacroInfoChain *Next = MIChain->Next;
68 Prev->Next = Next;
69 if (Next)
70 Next->Prev = Prev;
71 }
72 else {
73 assert(MIChainHead == MIChain);
74 MIChainHead = MIChain->Next;
75 MIChainHead->Prev = 0;
76 }
77 MIChain->Next = MICache;
78 MICache = MIChain;
Chris Lattner0301b3f2009-02-20 22:19:20 +000079
Ted Kremenek9714a232010-10-19 22:15:20 +000080 MI->Destroy();
81}
Chris Lattner0301b3f2009-02-20 22:19:20 +000082
Chris Lattner141e71f2008-03-09 01:54:53 +000083/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
Peter Collingbourne84021552011-02-28 02:37:51 +000084/// current line until the tok::eod token is found.
Chris Lattner141e71f2008-03-09 01:54:53 +000085void Preprocessor::DiscardUntilEndOfDirective() {
86 Token Tmp;
87 do {
88 LexUnexpandedToken(Tmp);
Peter Collingbournea5ef5842011-02-22 13:49:06 +000089 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne84021552011-02-28 02:37:51 +000090 } while (Tmp.isNot(tok::eod));
Chris Lattner141e71f2008-03-09 01:54:53 +000091}
92
Chris Lattner141e71f2008-03-09 01:54:53 +000093/// ReadMacroName - Lex and validate a macro name, which occurs after a
Peter Collingbourne84021552011-02-28 02:37:51 +000094/// #define or #undef. This sets the token kind to eod and discards the rest
Chris Lattner141e71f2008-03-09 01:54:53 +000095/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
96/// this is due to a a #define, 2 if #undef directive, 0 if it is something
97/// else (e.g. #ifdef).
98void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
99 // Read the token, don't allow macro expansion on it.
100 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000102 if (MacroNameTok.is(tok::code_completion)) {
103 if (CodeComplete)
104 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
105 LexUnexpandedToken(MacroNameTok);
106 return;
107 }
108
Chris Lattner141e71f2008-03-09 01:54:53 +0000109 // Missing macro name?
Peter Collingbourne84021552011-02-28 02:37:51 +0000110 if (MacroNameTok.is(tok::eod)) {
Chris Lattner3692b092008-11-18 07:59:24 +0000111 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
112 return;
113 }
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Chris Lattner141e71f2008-03-09 01:54:53 +0000115 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
116 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +0000117 bool Invalid = false;
118 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
119 if (Invalid)
120 return;
121
Chris Lattner9485d232008-12-13 20:12:40 +0000122 const IdentifierInfo &Info = Identifiers.get(Spelling);
123 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000124 // C++ 2.5p2: Alternative tokens behave the same as its primary token
125 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000126 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +0000127 else
128 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
129 // Fall through on error.
130 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
131 // Error if defining "defined": C99 6.10.8.4.
132 Diag(MacroNameTok, diag::err_defined_macro_name);
133 } else if (isDefineUndef && II->hasMacroDefinition() &&
134 getMacroInfo(II)->isBuiltinMacro()) {
135 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
136 if (isDefineUndef == 1)
137 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
138 else
139 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
140 } else {
141 // Okay, we got a good identifier node. Return it.
142 return;
143 }
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Chris Lattner141e71f2008-03-09 01:54:53 +0000145 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne84021552011-02-28 02:37:51 +0000146 // token kind to tok::eod.
147 MacroNameTok.setKind(tok::eod);
Chris Lattner141e71f2008-03-09 01:54:53 +0000148 return DiscardUntilEndOfDirective();
149}
150
Peter Collingbourne84021552011-02-28 02:37:51 +0000151/// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
152/// not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattnerab82f412009-04-17 23:30:53 +0000153/// true, then we consider macros that expand to zero tokens as being ok.
154void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000155 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000156 // Lex unexpanded tokens for most directives: macros might expand to zero
157 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
158 // #line) allow empty macros.
159 if (EnableMacros)
160 Lex(Tmp);
161 else
162 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Chris Lattner141e71f2008-03-09 01:54:53 +0000164 // There should be no tokens after the directive, but we allow them as an
165 // extension.
166 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
167 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Peter Collingbourne84021552011-02-28 02:37:51 +0000169 if (Tmp.isNot(tok::eod)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000170 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000171 // or if this is a macro-style preprocessing directive, because it is more
172 // trouble than it is worth to insert /**/ and check that there is no /**/
173 // in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000174 FixItHint Hint;
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000175 if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
176 !CurTokenLexer)
Douglas Gregor849b2432010-03-31 17:46:05 +0000177 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
178 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000179 DiscardUntilEndOfDirective();
180 }
181}
182
183
184
185/// SkipExcludedConditionalBlock - We just read a #if or related directive and
186/// decided that the subsequent tokens are in the #if'd out portion of the
187/// file. Lex the rest of the file, until we see an #endif. If
188/// FoundNonSkipPortion is true, then we have already emitted code for part of
189/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
190/// is true, then #else directives are ok, if not, then we have already seen one
191/// so a #else directive is a duplicate. When this returns, the caller can lex
192/// the first valid token.
193void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
194 bool FoundNonSkipPortion,
195 bool FoundElse) {
196 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000197 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000198
Ted Kremenek60e45d42008-11-18 00:34:22 +0000199 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000200 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Ted Kremenek268ee702008-12-12 18:34:08 +0000202 if (CurPTHLexer) {
203 PTHSkipExcludedConditionalBlock();
204 return;
205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattner141e71f2008-03-09 01:54:53 +0000207 // Enter raw mode to disable identifier lookup (and thus macro expansion),
208 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000209 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000210 Token Tok;
211 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000212 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Douglas Gregorf44e8542010-08-24 19:08:16 +0000214 if (Tok.is(tok::code_completion)) {
215 if (CodeComplete)
216 CodeComplete->CodeCompleteInConditionalExclusion();
217 continue;
218 }
219
Chris Lattner141e71f2008-03-09 01:54:53 +0000220 // If this is the end of the buffer, we have an error.
221 if (Tok.is(tok::eof)) {
222 // Emit errors for each unterminated conditional on the stack, including
223 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000224 while (!CurPPLexer->ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000225 if (!isCodeCompletionFile(Tok.getLocation()))
226 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
227 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000228 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000229 }
230
Chris Lattner141e71f2008-03-09 01:54:53 +0000231 // Just return and let the caller lex after this #include.
232 break;
233 }
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Chris Lattner141e71f2008-03-09 01:54:53 +0000235 // If this token is not a preprocessor directive, just skip it.
236 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
237 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattner141e71f2008-03-09 01:54:53 +0000239 // We just parsed a # character at the start of a line, so we're in
240 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne84021552011-02-28 02:37:51 +0000241 // converted into an EOD token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000242 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000243 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000244
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattner141e71f2008-03-09 01:54:53 +0000246 // Read the next token, the directive flavor.
247 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Chris Lattner141e71f2008-03-09 01:54:53 +0000249 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
250 // something bogus), skip it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000251 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000252 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000253 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000254 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000255 continue;
256 }
257
258 // If the first letter isn't i or e, it isn't intesting to us. We know that
259 // this is safe in the face of spelling differences, because there is no way
260 // to spell an i/e in a strange way that is another letter. Skipping this
261 // allows us to avoid looking up the identifier info for #define/#undef and
262 // other common directives.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000263 const char *RawCharData = Tok.getRawIdentifierData();
264
Chris Lattner141e71f2008-03-09 01:54:53 +0000265 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000266 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000267 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000268 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000269 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000270 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000271 continue;
272 }
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattner141e71f2008-03-09 01:54:53 +0000274 // Get the identifier name without trigraphs or embedded newlines. Note
275 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
276 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000277 char DirectiveBuf[20];
278 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000279 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000280 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000281 } else {
282 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000283 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000284 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000285 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000286 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000287 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000288 continue;
289 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000290 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
291 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000292 }
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000294 if (Directive.startswith("if")) {
295 llvm::StringRef Sub = Directive.substr(2);
296 if (Sub.empty() || // "if"
297 Sub == "def" || // "ifdef"
298 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000299 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
300 // bother parsing the condition.
301 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000302 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 /*foundnonskip*/false,
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000304 /*foundelse*/false);
305
306 if (Callbacks)
307 Callbacks->Endif();
Chris Lattner141e71f2008-03-09 01:54:53 +0000308 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000309 } else if (Directive[0] == 'e') {
310 llvm::StringRef Sub = Directive.substr(1);
311 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000312 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000313 PPConditionalInfo CondInfo;
314 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000315 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000316 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattner141e71f2008-03-09 01:54:53 +0000317 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chris Lattner141e71f2008-03-09 01:54:53 +0000319 // If we popped the outermost skipping block, we're done skipping!
320 if (!CondInfo.WasSkipping)
321 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000322 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000323 // #else directive in a skipping conditional. If not in some other
324 // skipping conditional, and if #else hasn't already been seen, enter it
325 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000326 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000327 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattner141e71f2008-03-09 01:54:53 +0000329 // If this is a #else with a #else before it, report the error.
330 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattner141e71f2008-03-09 01:54:53 +0000332 // Note that we've seen a #else in this conditional.
333 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000335 if (Callbacks)
336 Callbacks->Else();
337
Chris Lattner141e71f2008-03-09 01:54:53 +0000338 // If the conditional is at the top level, and the #if block wasn't
339 // entered, enter the #else block now.
340 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
341 CondInfo.FoundNonSkip = true;
342 break;
343 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000344 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000345 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000346
347 bool ShouldEnter;
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000348 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +0000349 // If this is in a skipping block or if we're already handled this #if
350 // block, don't bother parsing the condition.
351 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
352 DiscardUntilEndOfDirective();
353 ShouldEnter = false;
354 } else {
355 // Restore the value of LexingRawMode so that identifiers are
356 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000357 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
358 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000359 IdentifierInfo *IfNDefMacro = 0;
360 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000361 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000362 }
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000363 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Chris Lattner141e71f2008-03-09 01:54:53 +0000365 // If this is a #elif with a #else before it, report the error.
366 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000368 if (Callbacks)
369 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
370
Chris Lattner141e71f2008-03-09 01:54:53 +0000371 // If this condition is true, enter it!
372 if (ShouldEnter) {
373 CondInfo.FoundNonSkip = true;
374 break;
375 }
376 }
377 }
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Ted Kremenek60e45d42008-11-18 00:34:22 +0000379 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000380 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000381 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000382 }
383
384 // Finally, if we are out of the conditional (saw an #endif or ran off the end
385 // of the file, just stop skipping and return to lexing whatever came after
386 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000387 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000388}
389
Ted Kremenek268ee702008-12-12 18:34:08 +0000390void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000391
392 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000393 assert(CurPTHLexer);
394 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Ted Kremenek268ee702008-12-12 18:34:08 +0000396 // Skip to the next '#else', '#elif', or #endif.
397 if (CurPTHLexer->SkipBlock()) {
398 // We have reached an #endif. Both the '#' and 'endif' tokens
399 // have been consumed by the PTHLexer. Just pop off the condition level.
400 PPConditionalInfo CondInfo;
401 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000402 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek268ee702008-12-12 18:34:08 +0000403 assert(!InCond && "Can't be skipping if not in a conditional!");
404 break;
405 }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Ted Kremenek268ee702008-12-12 18:34:08 +0000407 // We have reached a '#else' or '#elif'. Lex the next token to get
408 // the directive flavor.
409 Token Tok;
410 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Ted Kremenek268ee702008-12-12 18:34:08 +0000412 // We can actually look up the IdentifierInfo here since we aren't in
413 // raw mode.
414 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
415
416 if (K == tok::pp_else) {
417 // #else: Enter the else condition. We aren't in a nested condition
418 // since we skip those. We're always in the one matching the last
419 // blocked we skipped.
420 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
421 // Note that we've seen a #else in this conditional.
422 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Ted Kremenek268ee702008-12-12 18:34:08 +0000424 // If the #if block wasn't entered then enter the #else block now.
425 if (!CondInfo.FoundNonSkip) {
426 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Peter Collingbourne84021552011-02-28 02:37:51 +0000428 // Scan until the eod token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000429 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000430 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000431 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Ted Kremenek268ee702008-12-12 18:34:08 +0000433 break;
434 }
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Ted Kremenek268ee702008-12-12 18:34:08 +0000436 // Otherwise skip this block.
437 continue;
438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Ted Kremenek268ee702008-12-12 18:34:08 +0000440 assert(K == tok::pp_elif);
441 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
442
443 // If this is a #elif with a #else before it, report the error.
444 if (CondInfo.FoundElse)
445 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Ted Kremenek268ee702008-12-12 18:34:08 +0000447 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000448 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000449 if (CondInfo.FoundNonSkip)
450 continue;
451
452 // Evaluate the condition of the #elif.
453 IdentifierInfo *IfNDefMacro = 0;
454 CurPTHLexer->ParsingPreprocessorDirective = true;
455 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
456 CurPTHLexer->ParsingPreprocessorDirective = false;
457
458 // If this condition is true, enter it!
459 if (ShouldEnter) {
460 CondInfo.FoundNonSkip = true;
461 break;
462 }
463
464 // Otherwise, skip this block and go to the next one.
465 continue;
466 }
467}
468
Chris Lattner10725092008-03-09 04:17:44 +0000469/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
470/// return null on failure. isAngled indicates whether the file reference is
471/// for system #include's or not (i.e. using <> instead of "").
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000472const FileEntry *Preprocessor::LookupFile(
473 llvm::StringRef Filename,
474 bool isAngled,
475 const DirectoryLookup *FromDir,
476 const DirectoryLookup *&CurDir,
477 llvm::SmallVectorImpl<char> *RawPath) {
Chris Lattner10725092008-03-09 04:17:44 +0000478 // If the header lookup mechanism may be relative to the current file, pass in
479 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000480 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000481 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000482 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000483 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000485 // If there is no file entry associated with this file, it must be the
486 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000487 // it won't be scanned for preprocessor directives. If we have the
488 // predefines buffer, resolve #include references (which come from the
489 // -include command line argument) as if they came from the main file, this
490 // affects file lookup etc.
491 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000492 FID = SourceMgr.getMainFileID();
493 CurFileEnt = SourceMgr.getFileEntryForID(FID);
494 }
Chris Lattner10725092008-03-09 04:17:44 +0000495 }
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Chris Lattner10725092008-03-09 04:17:44 +0000497 // Do a standard file entry lookup.
498 CurDir = CurDirLookup;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000499 const FileEntry *FE = HeaderInfo.LookupFile(
500 Filename, isAngled, FromDir, CurDir, CurFileEnt, RawPath);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000501 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Chris Lattner10725092008-03-09 04:17:44 +0000503 // Otherwise, see if this is a subframework header. If so, this is relative
504 // to one of the headers on the #include stack. Walk the list of the current
505 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000506 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000507 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000508 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
509 RawPath)))
Chris Lattner10725092008-03-09 04:17:44 +0000510 return FE;
511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattner10725092008-03-09 04:17:44 +0000513 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
514 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000515 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000516 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000517 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000518 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
519 RawPath)))
Chris Lattner10725092008-03-09 04:17:44 +0000520 return FE;
521 }
522 }
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Chris Lattner10725092008-03-09 04:17:44 +0000524 // Otherwise, we really couldn't find the file.
525 return 0;
526}
527
Chris Lattner141e71f2008-03-09 01:54:53 +0000528
529//===----------------------------------------------------------------------===//
530// Preprocessor Directive Handling.
531//===----------------------------------------------------------------------===//
532
533/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000534/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000535/// lexer/preprocessor state, and advances the lexer(s) so that the next token
536/// read is the correct one.
537void Preprocessor::HandleDirective(Token &Result) {
538 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Chris Lattner141e71f2008-03-09 01:54:53 +0000540 // We just parsed a # character at the start of a line, so we're in directive
541 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne84021552011-02-28 02:37:51 +0000542 // EOD token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000543 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner141e71f2008-03-09 01:54:53 +0000545 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000546
Chris Lattner141e71f2008-03-09 01:54:53 +0000547 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000548 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000549 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000550 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Chris Lattner42aa16c2009-03-18 21:00:25 +0000552 // Save the '#' token in case we need to return it later.
553 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Chris Lattner141e71f2008-03-09 01:54:53 +0000555 // Read the next token, the directive flavor. This isn't expanded due to
556 // C99 6.10.3p8.
557 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattner141e71f2008-03-09 01:54:53 +0000559 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
560 // #define A(x) #x
561 // A(abc
562 // #warning blah
563 // def)
564 // If so, the user is relying on non-portable behavior, emit a diagnostic.
565 if (InMacroArgs)
566 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Chris Lattner141e71f2008-03-09 01:54:53 +0000568TryAgain:
569 switch (Result.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000570 case tok::eod:
Chris Lattner141e71f2008-03-09 01:54:53 +0000571 return; // null directive.
572 case tok::comment:
573 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
574 LexUnexpandedToken(Result);
575 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000576 case tok::code_completion:
577 if (CodeComplete)
578 CodeComplete->CodeCompleteDirective(
579 CurPPLexer->getConditionalStackDepth() > 0);
580 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000581 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000582 if (getLangOptions().AsmPreprocessor)
583 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000584 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000585 default:
586 IdentifierInfo *II = Result.getIdentifierInfo();
587 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Chris Lattner141e71f2008-03-09 01:54:53 +0000589 // Ask what the preprocessor keyword ID is.
590 switch (II->getPPKeywordID()) {
591 default: break;
592 // C99 6.10.1 - Conditional Inclusion.
593 case tok::pp_if:
594 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
595 case tok::pp_ifdef:
596 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
597 case tok::pp_ifndef:
598 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
599 case tok::pp_elif:
600 return HandleElifDirective(Result);
601 case tok::pp_else:
602 return HandleElseDirective(Result);
603 case tok::pp_endif:
604 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Chris Lattner141e71f2008-03-09 01:54:53 +0000606 // C99 6.10.2 - Source File Inclusion.
607 case tok::pp_include:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000608 // Handle #include.
609 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000610 case tok::pp___include_macros:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000611 // Handle -imacros.
612 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Chris Lattner141e71f2008-03-09 01:54:53 +0000614 // C99 6.10.3 - Macro Replacement.
615 case tok::pp_define:
616 return HandleDefineDirective(Result);
617 case tok::pp_undef:
618 return HandleUndefDirective(Result);
619
620 // C99 6.10.4 - Line Control.
621 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000622 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattner141e71f2008-03-09 01:54:53 +0000624 // C99 6.10.5 - Error Directive.
625 case tok::pp_error:
626 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Chris Lattner141e71f2008-03-09 01:54:53 +0000628 // C99 6.10.6 - Pragma Directive.
629 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000630 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Chris Lattner141e71f2008-03-09 01:54:53 +0000632 // GNU Extensions.
633 case tok::pp_import:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000634 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000635 case tok::pp_include_next:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000636 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattner141e71f2008-03-09 01:54:53 +0000638 case tok::pp_warning:
639 Diag(Result, diag::ext_pp_warning_directive);
640 return HandleUserDiagnosticDirective(Result, true);
641 case tok::pp_ident:
642 return HandleIdentSCCSDirective(Result);
643 case tok::pp_sccs:
644 return HandleIdentSCCSDirective(Result);
645 case tok::pp_assert:
646 //isExtension = true; // FIXME: implement #assert
647 break;
648 case tok::pp_unassert:
649 //isExtension = true; // FIXME: implement #unassert
650 break;
651 }
652 break;
653 }
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Chris Lattner42aa16c2009-03-18 21:00:25 +0000655 // If this is a .S file, treat unknown # directives as non-preprocessor
656 // directives. This is important because # may be a comment or introduce
657 // various pseudo-ops. Just return the # token and push back the following
658 // token to be lexed next time.
659 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000660 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000661 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000662 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000663 Toks[1] = Result;
Chris Lattnerba3ca522011-01-06 05:01:51 +0000664
665 // If the second token is a hashhash token, then we need to translate it to
666 // unknown so the token lexer doesn't try to perform token pasting.
667 if (Result.is(tok::hashhash))
668 Toks[1].setKind(tok::unknown);
669
Chris Lattner42aa16c2009-03-18 21:00:25 +0000670 // Enter this token stream so that we re-lex the tokens. Make sure to
671 // enable macro expansion, in case the token after the # is an identifier
672 // that is expanded.
673 EnterTokenStream(Toks, 2, false, true);
674 return;
675 }
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Chris Lattner141e71f2008-03-09 01:54:53 +0000677 // If we reached here, the preprocessing token is not valid!
678 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Chris Lattner141e71f2008-03-09 01:54:53 +0000680 // Read the rest of the PP line.
681 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Chris Lattner141e71f2008-03-09 01:54:53 +0000683 // Okay, we're done parsing the directive.
684}
685
Chris Lattner478a18e2009-01-26 06:19:46 +0000686/// GetLineValue - Convert a numeric token into an unsigned value, emitting
687/// Diagnostic DiagID if it is invalid, and returning the value in Val.
688static bool GetLineValue(Token &DigitTok, unsigned &Val,
689 unsigned DiagID, Preprocessor &PP) {
690 if (DigitTok.isNot(tok::numeric_constant)) {
691 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Peter Collingbourne84021552011-02-28 02:37:51 +0000693 if (DigitTok.isNot(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000694 PP.DiscardUntilEndOfDirective();
695 return true;
696 }
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Chris Lattner478a18e2009-01-26 06:19:46 +0000698 llvm::SmallString<64> IntegerBuffer;
699 IntegerBuffer.resize(DigitTok.getLength());
700 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000701 bool Invalid = false;
702 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
703 if (Invalid)
704 return true;
705
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000706 // Verify that we have a simple digit-sequence, and compute the value. This
707 // is always a simple digit string computed in decimal, so we do this manually
708 // here.
709 Val = 0;
710 for (unsigned i = 0; i != ActualLength; ++i) {
711 if (!isdigit(DigitTokBegin[i])) {
712 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
713 diag::err_pp_line_digit_sequence);
714 PP.DiscardUntilEndOfDirective();
715 return true;
716 }
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000718 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
719 if (NextVal < Val) { // overflow.
720 PP.Diag(DigitTok, DiagID);
721 PP.DiscardUntilEndOfDirective();
722 return true;
723 }
724 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
727 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000728 if (Val == 0) {
729 PP.Diag(DigitTok, DiagID);
730 PP.DiscardUntilEndOfDirective();
731 return true;
732 }
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000734 if (DigitTokBegin[0] == '0')
735 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Chris Lattner478a18e2009-01-26 06:19:46 +0000737 return false;
738}
739
Mike Stump1eb44332009-09-09 15:08:12 +0000740/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000741/// acceptable forms are:
742/// # line digit-sequence
743/// # line digit-sequence "s-char-sequence"
744void Preprocessor::HandleLineDirective(Token &Tok) {
745 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
746 // expanded.
747 Token DigitTok;
748 Lex(DigitTok);
749
Chris Lattner359cc442009-01-26 05:29:08 +0000750 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000751 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000752 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000753 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000754
Chris Lattner478a18e2009-01-26 06:19:46 +0000755 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
756 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000757 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
758 if (LineNo >= LineLimit)
759 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Chris Lattner5b9a5042009-01-26 07:57:50 +0000761 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000762 Token StrTok;
763 Lex(StrTok);
764
Peter Collingbourne84021552011-02-28 02:37:51 +0000765 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
766 // string followed by eod.
767 if (StrTok.is(tok::eod))
Chris Lattner359cc442009-01-26 05:29:08 +0000768 ; // ok
769 else if (StrTok.isNot(tok::string_literal)) {
770 Diag(StrTok, diag::err_pp_line_invalid_filename);
771 DiscardUntilEndOfDirective();
772 return;
773 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000774 // Parse and validate the string, converting it into a unique ID.
775 StringLiteralParser Literal(&StrTok, 1, *this);
776 assert(!Literal.AnyWide && "Didn't allow wide strings in");
777 if (Literal.hadError)
778 return DiscardUntilEndOfDirective();
779 if (Literal.Pascal) {
780 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
781 return DiscardUntilEndOfDirective();
782 }
783 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
784 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Peter Collingbourne84021552011-02-28 02:37:51 +0000786 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattnerab82f412009-04-17 23:30:53 +0000787 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
788 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000789 }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Chris Lattner4c4ea172009-02-03 21:52:55 +0000791 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chris Lattner16629382009-03-27 17:13:49 +0000793 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000794 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
795 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000796 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000797}
798
Chris Lattner478a18e2009-01-26 06:19:46 +0000799/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
800/// marker directive.
801static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
802 bool &IsSystemHeader, bool &IsExternCHeader,
803 Preprocessor &PP) {
804 unsigned FlagVal;
805 Token FlagTok;
806 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000807 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000808 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
809 return true;
810
811 if (FlagVal == 1) {
812 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattner478a18e2009-01-26 06:19:46 +0000814 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000815 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000816 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
817 return true;
818 } else if (FlagVal == 2) {
819 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Chris Lattner137b6a62009-02-04 06:25:26 +0000821 SourceManager &SM = PP.getSourceManager();
822 // If we are leaving the current presumed file, check to make sure the
823 // presumed include stack isn't empty!
824 FileID CurFileID =
825 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
826 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000827 if (PLoc.isInvalid())
828 return true;
829
Chris Lattner137b6a62009-02-04 06:25:26 +0000830 // If there is no include loc (main file) or if the include loc is in a
831 // different physical file, then we aren't in a "1" line marker flag region.
832 SourceLocation IncLoc = PLoc.getIncludeLoc();
833 if (IncLoc.isInvalid() ||
834 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
835 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
836 PP.DiscardUntilEndOfDirective();
837 return true;
838 }
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattner478a18e2009-01-26 06:19:46 +0000840 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000841 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000842 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
843 return true;
844 }
845
846 // We must have 3 if there are still flags.
847 if (FlagVal != 3) {
848 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000849 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000850 return true;
851 }
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Chris Lattner478a18e2009-01-26 06:19:46 +0000853 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Chris Lattner478a18e2009-01-26 06:19:46 +0000855 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000856 if (FlagTok.is(tok::eod)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000857 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000858 return true;
859
860 // We must have 4 if there is yet another flag.
861 if (FlagVal != 4) {
862 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000863 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000864 return true;
865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Chris Lattner478a18e2009-01-26 06:19:46 +0000867 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Chris Lattner478a18e2009-01-26 06:19:46 +0000869 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000870 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000871
872 // There are no more valid flags here.
873 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000874 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000875 return true;
876}
877
878/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
879/// one of the following forms:
880///
881/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000882/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000883/// # 42 "file" ('1' | '2')? '3' '4'?
884///
885void Preprocessor::HandleDigitDirective(Token &DigitTok) {
886 // Validate the number and convert it to an unsigned. GNU does not have a
887 // line # limit other than it fit in 32-bits.
888 unsigned LineNo;
889 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
890 *this))
891 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Chris Lattner478a18e2009-01-26 06:19:46 +0000893 Token StrTok;
894 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner478a18e2009-01-26 06:19:46 +0000896 bool IsFileEntry = false, IsFileExit = false;
897 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000898 int FilenameID = -1;
899
Peter Collingbourne84021552011-02-28 02:37:51 +0000900 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
901 // string followed by eod.
902 if (StrTok.is(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000903 ; // ok
904 else if (StrTok.isNot(tok::string_literal)) {
905 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000906 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000907 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000908 // Parse and validate the string, converting it into a unique ID.
909 StringLiteralParser Literal(&StrTok, 1, *this);
910 assert(!Literal.AnyWide && "Didn't allow wide strings in");
911 if (Literal.hadError)
912 return DiscardUntilEndOfDirective();
913 if (Literal.Pascal) {
914 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
915 return DiscardUntilEndOfDirective();
916 }
917 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
918 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Chris Lattner478a18e2009-01-26 06:19:46 +0000920 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000921 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000922 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000923 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000924 }
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Chris Lattner9d79eba2009-02-04 05:21:58 +0000926 // Create a line note with this information.
927 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000928 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000929 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Chris Lattner16629382009-03-27 17:13:49 +0000931 // If the preprocessor has callbacks installed, notify them of the #line
932 // change. This is used so that the line marker comes out in -E mode for
933 // example.
934 if (Callbacks) {
935 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
936 if (IsFileEntry)
937 Reason = PPCallbacks::EnterFile;
938 else if (IsFileExit)
939 Reason = PPCallbacks::ExitFile;
940 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
941 if (IsExternCHeader)
942 FileKind = SrcMgr::C_ExternCSystem;
943 else if (IsSystemHeader)
944 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chris Lattner86d0ef72010-04-14 04:28:50 +0000946 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000947 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000948}
949
950
Chris Lattner099dd052009-01-26 05:30:54 +0000951/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
952///
Mike Stump1eb44332009-09-09 15:08:12 +0000953void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000954 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000955 // PTH doesn't emit #warning or #error directives.
956 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000957 return CurPTHLexer->DiscardToEndOfLine();
958
Chris Lattner141e71f2008-03-09 01:54:53 +0000959 // Read the rest of the line raw. We do this because we don't want macros
960 // to be expanded and we don't require that the tokens be valid preprocessing
961 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
962 // collapse multiple consequtive white space between tokens, but this isn't
963 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000964 std::string Message = CurLexer->ReadToEndOfLine();
965 if (isWarning)
966 Diag(Tok, diag::pp_hash_warning) << Message;
967 else
968 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000969}
970
971/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
972///
973void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
974 // Yes, this directive is an extension.
975 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Chris Lattner141e71f2008-03-09 01:54:53 +0000977 // Read the string argument.
978 Token StrTok;
979 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Chris Lattner141e71f2008-03-09 01:54:53 +0000981 // If the token kind isn't a string, it's a malformed directive.
982 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000983 StrTok.isNot(tok::wide_string_literal)) {
984 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne84021552011-02-28 02:37:51 +0000985 if (StrTok.isNot(tok::eod))
Chris Lattner099dd052009-01-26 05:30:54 +0000986 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000987 return;
988 }
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Peter Collingbourne84021552011-02-28 02:37:51 +0000990 // Verify that there is nothing after the string, other than EOD.
Chris Lattner35410d52009-04-14 05:07:49 +0000991 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000992
Douglas Gregor453091c2010-03-16 22:30:13 +0000993 if (Callbacks) {
994 bool Invalid = false;
995 std::string Str = getSpelling(StrTok, &Invalid);
996 if (!Invalid)
997 Callbacks->Ident(Tok.getLocation(), Str);
998 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000999}
1000
1001//===----------------------------------------------------------------------===//
1002// Preprocessor Include Directive Handling.
1003//===----------------------------------------------------------------------===//
1004
1005/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1006/// checked and spelled filename, e.g. as an operand of #include. This returns
1007/// true if the input filename was in <>'s or false if it were in ""'s. The
1008/// caller is expected to provide a buffer that is large enough to hold the
1009/// spelling of the filename, but is also expected to handle the case when
1010/// this method decides to use a different buffer.
1011bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +00001012 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001013 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +00001014 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Chris Lattner141e71f2008-03-09 01:54:53 +00001016 // Make sure the filename is <x> or "x".
1017 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +00001018 if (Buffer[0] == '<') {
1019 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001020 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +00001021 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001022 return true;
1023 }
1024 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +00001025 } else if (Buffer[0] == '"') {
1026 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001027 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +00001028 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001029 return true;
1030 }
1031 isAngled = false;
1032 } else {
1033 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +00001034 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001035 return true;
1036 }
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Chris Lattner141e71f2008-03-09 01:54:53 +00001038 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +00001039 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001040 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +00001041 Buffer = llvm::StringRef();
1042 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001043 }
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Chris Lattner141e71f2008-03-09 01:54:53 +00001045 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001046 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001047 return isAngled;
1048}
1049
1050/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1051/// from a macro as multiple tokens, which need to be glued together. This
1052/// occurs for code like:
1053/// #define FOO <a/b.h>
1054/// #include FOO
1055/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1056///
1057/// This code concatenates and consumes tokens up to the '>' token. It returns
1058/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne84021552011-02-28 02:37:51 +00001059/// the EOD marker.
John Thompsona28cc092009-10-30 13:49:06 +00001060bool Preprocessor::ConcatenateIncludeName(
Douglas Gregorecdcb882010-10-20 22:00:55 +00001061 llvm::SmallString<128> &FilenameBuffer,
1062 SourceLocation &End) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001063 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001064
John Thompsona28cc092009-10-30 13:49:06 +00001065 Lex(CurTok);
Peter Collingbourne84021552011-02-28 02:37:51 +00001066 while (CurTok.isNot(tok::eod)) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001067 End = CurTok.getLocation();
1068
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001069 // FIXME: Provide code completion for #includes.
1070 if (CurTok.is(tok::code_completion)) {
1071 Lex(CurTok);
1072 continue;
1073 }
1074
Chris Lattner141e71f2008-03-09 01:54:53 +00001075 // Append the spelling of this token to the buffer. If there was a space
1076 // before it, add it now.
1077 if (CurTok.hasLeadingSpace())
1078 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Chris Lattner141e71f2008-03-09 01:54:53 +00001080 // Get the spelling of the token, directly into FilenameBuffer if possible.
1081 unsigned PreAppendSize = FilenameBuffer.size();
1082 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Chris Lattner141e71f2008-03-09 01:54:53 +00001084 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001085 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Chris Lattner141e71f2008-03-09 01:54:53 +00001087 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1088 if (BufPtr != &FilenameBuffer[PreAppendSize])
1089 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Chris Lattner141e71f2008-03-09 01:54:53 +00001091 // Resize FilenameBuffer to the correct size.
1092 if (CurTok.getLength() != ActualLen)
1093 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Chris Lattner141e71f2008-03-09 01:54:53 +00001095 // If we found the '>' marker, return success.
1096 if (CurTok.is(tok::greater))
1097 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001098
John Thompsona28cc092009-10-30 13:49:06 +00001099 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001100 }
1101
Peter Collingbourne84021552011-02-28 02:37:51 +00001102 // If we hit the eod marker, emit an error and return true so that the caller
1103 // knows the EOD has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001104 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001105 return true;
1106}
1107
1108/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1109/// file to be included from the lexer, then include it! This is a common
1110/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001111/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001112/// specifies the file to start searching from.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001113void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1114 Token &IncludeTok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001115 const DirectoryLookup *LookupFrom,
1116 bool isImport) {
1117
1118 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001119 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Chris Lattner141e71f2008-03-09 01:54:53 +00001121 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001122 llvm::SmallString<128> FilenameBuffer;
1123 llvm::StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001124 SourceLocation End;
1125
Chris Lattner141e71f2008-03-09 01:54:53 +00001126 switch (FilenameTok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +00001127 case tok::eod:
1128 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattner141e71f2008-03-09 01:54:53 +00001129 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Chris Lattner141e71f2008-03-09 01:54:53 +00001131 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001132 case tok::string_literal:
1133 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregorecdcb882010-10-20 22:00:55 +00001134 End = FilenameTok.getLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001135 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattner141e71f2008-03-09 01:54:53 +00001137 case tok::less:
1138 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1139 // case, glue the tokens together into FilenameBuffer and interpret those.
1140 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +00001141 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne84021552011-02-28 02:37:51 +00001142 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001143 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001144 break;
1145 default:
1146 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1147 DiscardUntilEndOfDirective();
1148 return;
1149 }
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001151 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001152 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001153 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1154 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001155 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001156 DiscardUntilEndOfDirective();
1157 return;
1158 }
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Peter Collingbourne84021552011-02-28 02:37:51 +00001160 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001161 // we allow macros that expand to nothing after the filename, because this
1162 // falls into the category of "#include pp-tokens new-line" specified in
1163 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001164 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001165
1166 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001167 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1168 Diag(FilenameTok, diag::err_pp_include_too_deep);
1169 return;
1170 }
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Chris Lattner141e71f2008-03-09 01:54:53 +00001172 // Search include directories.
1173 const DirectoryLookup *CurDir;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001174 llvm::SmallString<1024> RawPath;
1175 // We get the raw path only if we have 'Callbacks' to which we later pass
1176 // the path.
1177 const FileEntry *File = LookupFile(
1178 Filename, isAngled, LookupFrom, CurDir, Callbacks ? &RawPath : NULL);
Chris Lattner3692b092008-11-18 07:59:24 +00001179 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001180 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001181 return;
1182 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001183
Douglas Gregorecdcb882010-10-20 22:00:55 +00001184 // Notify the callback object that we've seen an inclusion directive.
1185 if (Callbacks)
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001186 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1187 End, RawPath);
1188
Chris Lattner72181832008-09-26 20:12:23 +00001189 // The #included file will be considered to be a system header if either it is
1190 // in a system include directory, or if the #includer is a system include
1191 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001192 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001193 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001194 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001196 // Ask HeaderInfo if we should enter this #include file. If not, #including
1197 // this file will have no effect.
1198 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001199 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001200 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001201 return;
1202 }
1203
Chris Lattner141e71f2008-03-09 01:54:53 +00001204 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001205 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1206 FileCharacter);
1207 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001208 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001209 return;
1210 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001211
1212 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001213 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001214}
1215
1216/// HandleIncludeNextDirective - Implements #include_next.
1217///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001218void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1219 Token &IncludeNextTok) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001220 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Chris Lattner141e71f2008-03-09 01:54:53 +00001222 // #include_next is like #include, except that we start searching after
1223 // the current found directory. If we can't do this, issue a
1224 // diagnostic.
1225 const DirectoryLookup *Lookup = CurDirLookup;
1226 if (isInPrimaryFile()) {
1227 Lookup = 0;
1228 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1229 } else if (Lookup == 0) {
1230 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1231 } else {
1232 // Start looking up in the next directory.
1233 ++Lookup;
1234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Douglas Gregorecdcb882010-10-20 22:00:55 +00001236 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattner141e71f2008-03-09 01:54:53 +00001237}
1238
1239/// HandleImportDirective - Implements #import.
1240///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001241void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1242 Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001243 if (!Features.ObjC1) // #import is standard for ObjC.
1244 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Douglas Gregorecdcb882010-10-20 22:00:55 +00001246 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001247}
1248
Chris Lattnerde076652009-04-08 18:46:40 +00001249/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1250/// pseudo directive in the predefines buffer. This handles it by sucking all
1251/// tokens through the preprocessor and discarding them (only keeping the side
1252/// effects on the preprocessor).
Douglas Gregorecdcb882010-10-20 22:00:55 +00001253void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1254 Token &IncludeMacrosTok) {
Chris Lattnerde076652009-04-08 18:46:40 +00001255 // This directive should only occur in the predefines buffer. If not, emit an
1256 // error and reject it.
1257 SourceLocation Loc = IncludeMacrosTok.getLocation();
1258 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1259 Diag(IncludeMacrosTok.getLocation(),
1260 diag::pp_include_macros_out_of_predefines);
1261 DiscardUntilEndOfDirective();
1262 return;
1263 }
Mike Stump1eb44332009-09-09 15:08:12 +00001264
Chris Lattnerfd105112009-04-08 20:53:24 +00001265 // Treat this as a normal #include for checking purposes. If this is
1266 // successful, it will push a new lexer onto the include stack.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001267 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Chris Lattnerfd105112009-04-08 20:53:24 +00001269 Token TmpTok;
1270 do {
1271 Lex(TmpTok);
1272 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1273 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001274}
1275
Chris Lattner141e71f2008-03-09 01:54:53 +00001276//===----------------------------------------------------------------------===//
1277// Preprocessor Macro Directive Handling.
1278//===----------------------------------------------------------------------===//
1279
1280/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1281/// definition has just been read. Lex the rest of the arguments and the
1282/// closing ), updating MI with what we learn. Return true if an error occurs
1283/// parsing the arg list.
1284bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1285 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Chris Lattner141e71f2008-03-09 01:54:53 +00001287 Token Tok;
1288 while (1) {
1289 LexUnexpandedToken(Tok);
1290 switch (Tok.getKind()) {
1291 case tok::r_paren:
1292 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001293 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001294 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001295 // Otherwise we have #define FOO(A,)
1296 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1297 return true;
1298 case tok::ellipsis: // #define X(... -> C99 varargs
1299 // Warn if use of C99 feature in non-C99 mode.
1300 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1301
1302 // Lex the token after the identifier.
1303 LexUnexpandedToken(Tok);
1304 if (Tok.isNot(tok::r_paren)) {
1305 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1306 return true;
1307 }
1308 // Add the __VA_ARGS__ identifier as an argument.
1309 Arguments.push_back(Ident__VA_ARGS__);
1310 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001311 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001312 return false;
Peter Collingbourne84021552011-02-28 02:37:51 +00001313 case tok::eod: // #define X(
Chris Lattner141e71f2008-03-09 01:54:53 +00001314 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1315 return true;
1316 default:
1317 // Handle keywords and identifiers here to accept things like
1318 // #define Foo(for) for.
1319 IdentifierInfo *II = Tok.getIdentifierInfo();
1320 if (II == 0) {
1321 // #define X(1
1322 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1323 return true;
1324 }
1325
1326 // If this is already used as an argument, it is used multiple times (e.g.
1327 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001328 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001329 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001330 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001331 return true;
1332 }
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Chris Lattner141e71f2008-03-09 01:54:53 +00001334 // Add the argument to the macro info.
1335 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Chris Lattner141e71f2008-03-09 01:54:53 +00001337 // Lex the token after the identifier.
1338 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Chris Lattner141e71f2008-03-09 01:54:53 +00001340 switch (Tok.getKind()) {
1341 default: // #define X(A B
1342 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1343 return true;
1344 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001345 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001346 return false;
1347 case tok::comma: // #define X(A,
1348 break;
1349 case tok::ellipsis: // #define X(A... -> GCC extension
1350 // Diagnose extension.
1351 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Chris Lattner141e71f2008-03-09 01:54:53 +00001353 // Lex the token after the identifier.
1354 LexUnexpandedToken(Tok);
1355 if (Tok.isNot(tok::r_paren)) {
1356 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1357 return true;
1358 }
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Chris Lattner141e71f2008-03-09 01:54:53 +00001360 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001361 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001362 return false;
1363 }
1364 }
1365 }
1366}
1367
1368/// HandleDefineDirective - Implements #define. This consumes the entire macro
1369/// line then lets the caller lex the next real token.
1370void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1371 ++NumDefined;
1372
1373 Token MacroNameTok;
1374 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Chris Lattner141e71f2008-03-09 01:54:53 +00001376 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001377 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001378 return;
1379
Chris Lattner2451b522009-04-21 04:46:33 +00001380 Token LastTok = MacroNameTok;
1381
Chris Lattner141e71f2008-03-09 01:54:53 +00001382 // If we are supposed to keep comments in #defines, reenable comment saving
1383 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001384 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Chris Lattner141e71f2008-03-09 01:54:53 +00001386 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001387 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Chris Lattner141e71f2008-03-09 01:54:53 +00001389 Token Tok;
1390 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Chris Lattner141e71f2008-03-09 01:54:53 +00001392 // If this is a function-like macro definition, parse the argument list,
1393 // marking each of the identifiers as being used as macro arguments. Also,
1394 // check other constraints on the first token of the macro body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001395 if (Tok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001396 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001397 } else if (Tok.hasLeadingSpace()) {
1398 // This is a normal token with leading space. Clear the leading space
1399 // marker on the first token to get proper expansion.
1400 Tok.clearFlag(Token::LeadingSpace);
1401 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001402 // This is a function-like macro definition. Read the argument list.
1403 MI->setIsFunctionLike();
1404 if (ReadMacroDefinitionArgList(MI)) {
1405 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001406 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001407 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001408 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001409 DiscardUntilEndOfDirective();
1410 return;
1411 }
1412
Chris Lattner8fde5972009-04-19 18:26:34 +00001413 // If this is a definition of a variadic C99 function-like macro, not using
1414 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Chris Lattner8fde5972009-04-19 18:26:34 +00001416 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1417 // This gets unpoisoned where it is allowed.
1418 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1419 if (MI->isC99Varargs())
1420 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Chris Lattner141e71f2008-03-09 01:54:53 +00001422 // Read the first token after the arg list for down below.
1423 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001424 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001425 // C99 requires whitespace between the macro definition and the body. Emit
1426 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001427 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001428 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001429 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1430 // first character of a replacement list is not a character required by
1431 // subclause 5.2.1, then there shall be white-space separation between the
1432 // identifier and the replacement list.". 5.2.1 lists this set:
1433 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1434 // is irrelevant here.
1435 bool isInvalid = false;
1436 if (Tok.is(tok::at)) // @ is not in the list above.
1437 isInvalid = true;
1438 else if (Tok.is(tok::unknown)) {
1439 // If we have an unknown token, it is something strange like "`". Since
1440 // all of valid characters would have lexed into a single character
1441 // token of some sort, we know this is not a valid case.
1442 isInvalid = true;
1443 }
1444 if (isInvalid)
1445 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1446 else
1447 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001448 }
Chris Lattner2451b522009-04-21 04:46:33 +00001449
Peter Collingbourne84021552011-02-28 02:37:51 +00001450 if (!Tok.is(tok::eod))
Chris Lattner2451b522009-04-21 04:46:33 +00001451 LastTok = Tok;
1452
Chris Lattner141e71f2008-03-09 01:54:53 +00001453 // Read the rest of the macro body.
1454 if (MI->isObjectLike()) {
1455 // Object-like macros are very simple, just read their body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001456 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001457 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001458 MI->AddTokenToBody(Tok);
1459 // Get the next token of the macro.
1460 LexUnexpandedToken(Tok);
1461 }
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Chris Lattner141e71f2008-03-09 01:54:53 +00001463 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001464 // Otherwise, read the body of a function-like macro. While we are at it,
1465 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1466 // parameters in function-like macro expansions.
Peter Collingbourne84021552011-02-28 02:37:51 +00001467 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001468 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001469
Chris Lattner141e71f2008-03-09 01:54:53 +00001470 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001471 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Chris Lattner141e71f2008-03-09 01:54:53 +00001473 // Get the next token of the macro.
1474 LexUnexpandedToken(Tok);
1475 continue;
1476 }
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Chris Lattner141e71f2008-03-09 01:54:53 +00001478 // Get the next token of the macro.
1479 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Chris Lattner32404692009-05-25 17:16:10 +00001481 // Check for a valid macro arg identifier.
1482 if (Tok.getIdentifierInfo() == 0 ||
1483 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1484
1485 // If this is assembler-with-cpp mode, we accept random gibberish after
1486 // the '#' because '#' is often a comment character. However, change
1487 // the kind of the token to tok::unknown so that the preprocessor isn't
1488 // confused.
Peter Collingbourne84021552011-02-28 02:37:51 +00001489 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner32404692009-05-25 17:16:10 +00001490 LastTok.setKind(tok::unknown);
1491 } else {
1492 Diag(Tok, diag::err_pp_stringize_not_parameter);
1493 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Chris Lattner32404692009-05-25 17:16:10 +00001495 // Disable __VA_ARGS__ again.
1496 Ident__VA_ARGS__->setIsPoisoned(true);
1497 return;
1498 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001499 }
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Chris Lattner32404692009-05-25 17:16:10 +00001501 // Things look ok, add the '#' and param name tokens to the macro.
1502 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001503 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001504 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Chris Lattner141e71f2008-03-09 01:54:53 +00001506 // Get the next token of the macro.
1507 LexUnexpandedToken(Tok);
1508 }
1509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
1511
Chris Lattner141e71f2008-03-09 01:54:53 +00001512 // Disable __VA_ARGS__ again.
1513 Ident__VA_ARGS__->setIsPoisoned(true);
1514
1515 // Check that there is no paste (##) operator at the begining or end of the
1516 // replacement list.
1517 unsigned NumTokens = MI->getNumTokens();
1518 if (NumTokens != 0) {
1519 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1520 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001521 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001522 return;
1523 }
1524 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1525 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001526 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001527 return;
1528 }
1529 }
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Chris Lattner2451b522009-04-21 04:46:33 +00001531 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Chris Lattner141e71f2008-03-09 01:54:53 +00001533 // Finally, if this identifier already had a macro defined for it, verify that
1534 // the macro bodies are identical and free the old definition.
1535 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001536 // It is very common for system headers to have tons of macro redefinitions
1537 // and for warnings to be disabled in system headers. If this is the case,
1538 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001539 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001540 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001541 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner41c3ae12009-01-16 19:50:11 +00001542 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001543
Chris Lattnerf47724b2010-08-17 15:55:45 +00001544 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001545 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001546 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001547 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001548 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1549 << MacroNameTok.getIdentifierInfo();
1550 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1551 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001552 }
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001553 if (OtherMI->isWarnIfUnused())
1554 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek0ea76722008-12-15 19:56:42 +00001555 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001556 }
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Chris Lattner141e71f2008-03-09 01:54:53 +00001558 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001560 assert(!MI->isUsed());
1561 // If we need warning for not using the macro, add its location in the
1562 // warn-because-unused-macro set. If it gets used it will be removed from set.
1563 if (isInPrimaryFile() && // don't warn for include'd macros.
1564 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1565 MI->getDefinitionLoc()) != Diagnostic::Ignored) {
1566 MI->setIsWarnIfUnused(true);
1567 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1568 }
1569
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001570 // If the callbacks want to know, tell them about the macro definition.
1571 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001572 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001573}
1574
1575/// HandleUndefDirective - Implements #undef.
1576///
1577void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1578 ++NumUndefined;
1579
1580 Token MacroNameTok;
1581 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Chris Lattner141e71f2008-03-09 01:54:53 +00001583 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001584 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001585 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Chris Lattner141e71f2008-03-09 01:54:53 +00001587 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001588 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Chris Lattner141e71f2008-03-09 01:54:53 +00001590 // Okay, we finally have a valid identifier to undef.
1591 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Chris Lattner141e71f2008-03-09 01:54:53 +00001593 // If the macro is not defined, this is a noop undef, just return.
1594 if (MI == 0) return;
1595
1596 if (!MI->isUsed())
1597 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001598
1599 // If the callbacks want to know, tell them about the macro #undef.
1600 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001601 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001602
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001603 if (MI->isWarnIfUnused())
1604 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1605
Chris Lattner141e71f2008-03-09 01:54:53 +00001606 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001607 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001608 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1609}
1610
1611
1612//===----------------------------------------------------------------------===//
1613// Preprocessor Conditional Directive Handling.
1614//===----------------------------------------------------------------------===//
1615
1616/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1617/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1618/// if any tokens have been returned or pp-directives activated before this
1619/// #ifndef has been lexed.
1620///
1621void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1622 bool ReadAnyTokensBeforeDirective) {
1623 ++NumIf;
1624 Token DirectiveTok = Result;
1625
1626 Token MacroNameTok;
1627 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Chris Lattner141e71f2008-03-09 01:54:53 +00001629 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001630 if (MacroNameTok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001631 // Skip code until we get to #endif. This helps with recovery by not
1632 // emitting an error when the #endif is reached.
1633 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1634 /*Foundnonskip*/false, /*FoundElse*/false);
1635 return;
1636 }
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Chris Lattner141e71f2008-03-09 01:54:53 +00001638 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001639 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001640
Chris Lattner13d283d2010-02-12 08:03:27 +00001641 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1642 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001643
Ted Kremenek60e45d42008-11-18 00:34:22 +00001644 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001645 // If the start of a top-level #ifdef and if the macro is not defined,
1646 // inform MIOpt that this might be the start of a proper include guard.
1647 // Otherwise it is some other form of unknown conditional which we can't
1648 // handle.
1649 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001650 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001651 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001652 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001653 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001654 }
1655
Chris Lattner141e71f2008-03-09 01:54:53 +00001656 // If there is a macro, process it.
1657 if (MI) // Mark it used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001658 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Chris Lattner141e71f2008-03-09 01:54:53 +00001660 // Should we include the stuff contained by this directive?
1661 if (!MI == isIfndef) {
1662 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001663 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1664 /*wasskip*/false, /*foundnonskip*/true,
1665 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001666 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001667 // No, skip the contents of this block.
Chris Lattner141e71f2008-03-09 01:54:53 +00001668 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001669 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001670 /*FoundElse*/false);
1671 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001672
1673 if (Callbacks) {
1674 if (isIfndef)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001675 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001676 else
Craig Silverstein2aa92672010-11-19 21:33:15 +00001677 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001678 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001679}
1680
1681/// HandleIfDirective - Implements the #if directive.
1682///
1683void Preprocessor::HandleIfDirective(Token &IfToken,
1684 bool ReadAnyTokensBeforeDirective) {
1685 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Craig Silverstein08985b92010-11-06 01:19:03 +00001687 // Parse and evaluate the conditional expression.
Chris Lattner141e71f2008-03-09 01:54:53 +00001688 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein08985b92010-11-06 01:19:03 +00001689 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1690 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1691 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes0049db62008-06-01 18:31:24 +00001692
1693 // If this condition is equivalent to #ifndef X, and if this is the first
1694 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001695 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001696 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001697 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001698 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001699 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001700 }
1701
Chris Lattner141e71f2008-03-09 01:54:53 +00001702 // Should we include the stuff contained by this directive?
1703 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001704 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001705 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001706 /*foundnonskip*/true, /*foundelse*/false);
1707 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001708 // No, skip the contents of this block.
Mike Stump1eb44332009-09-09 15:08:12 +00001709 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001710 /*FoundElse*/false);
1711 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001712
1713 if (Callbacks)
1714 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001715}
1716
1717/// HandleEndifDirective - Implements the #endif directive.
1718///
1719void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1720 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Chris Lattner141e71f2008-03-09 01:54:53 +00001722 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001723 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Chris Lattner141e71f2008-03-09 01:54:53 +00001725 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001726 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001727 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001728 Diag(EndifToken, diag::err_pp_endif_without_if);
1729 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001730 }
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Chris Lattner141e71f2008-03-09 01:54:53 +00001732 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001733 if (CurPPLexer->getConditionalStackDepth() == 0)
1734 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Ted Kremenek60e45d42008-11-18 00:34:22 +00001736 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001737 "This code should only be reachable in the non-skipping case!");
Craig Silverstein08985b92010-11-06 01:19:03 +00001738
1739 if (Callbacks)
1740 Callbacks->Endif();
Chris Lattner141e71f2008-03-09 01:54:53 +00001741}
1742
Craig Silverstein08985b92010-11-06 01:19:03 +00001743/// HandleElseDirective - Implements the #else directive.
1744///
Chris Lattner141e71f2008-03-09 01:54:53 +00001745void Preprocessor::HandleElseDirective(Token &Result) {
1746 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Chris Lattner141e71f2008-03-09 01:54:53 +00001748 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001749 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Chris Lattner141e71f2008-03-09 01:54:53 +00001751 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001752 if (CurPPLexer->popConditionalLevel(CI)) {
1753 Diag(Result, diag::pp_err_else_without_if);
1754 return;
1755 }
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Chris Lattner141e71f2008-03-09 01:54:53 +00001757 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001758 if (CurPPLexer->getConditionalStackDepth() == 0)
1759 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001760
1761 // If this is a #else with a #else before it, report the error.
1762 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Craig Silverstein08985b92010-11-06 01:19:03 +00001764 // Finally, skip the rest of the contents of this block.
1765 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1766 /*FoundElse*/true);
1767
1768 if (Callbacks)
1769 Callbacks->Else();
Chris Lattner141e71f2008-03-09 01:54:53 +00001770}
1771
Craig Silverstein08985b92010-11-06 01:19:03 +00001772/// HandleElifDirective - Implements the #elif directive.
1773///
Chris Lattner141e71f2008-03-09 01:54:53 +00001774void Preprocessor::HandleElifDirective(Token &ElifToken) {
1775 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Chris Lattner141e71f2008-03-09 01:54:53 +00001777 // #elif directive in a non-skipping conditional... start skipping.
1778 // We don't care what the condition is, because we will always skip it (since
1779 // the block immediately before it was included).
Craig Silverstein08985b92010-11-06 01:19:03 +00001780 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001781 DiscardUntilEndOfDirective();
Craig Silverstein08985b92010-11-06 01:19:03 +00001782 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001783
1784 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001785 if (CurPPLexer->popConditionalLevel(CI)) {
1786 Diag(ElifToken, diag::pp_err_elif_without_if);
1787 return;
1788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Chris Lattner141e71f2008-03-09 01:54:53 +00001790 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001791 if (CurPPLexer->getConditionalStackDepth() == 0)
1792 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Chris Lattner141e71f2008-03-09 01:54:53 +00001794 // If this is a #elif with a #else before it, report the error.
1795 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1796
Craig Silverstein08985b92010-11-06 01:19:03 +00001797 // Finally, skip the rest of the contents of this block.
1798 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1799 /*FoundElse*/CI.FoundElse);
1800
1801 if (Callbacks)
1802 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001803}