blob: 99383e4791ba17bb5ce4fdf85dd9874337061411 [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];
Chris Lattner5f9e2722011-07-23 10:55:15 +0000278 StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000279 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000280 Directive = 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);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000291 Directive = 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")) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000295 StringRef Sub = Directive.substr(2);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000296 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') {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000310 StringRef Sub = Directive.substr(1);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000311 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.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000326 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Chris Lattner141e71f2008-03-09 01:54:53 +0000328 // If this is a #else with a #else before it, report the error.
329 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Chris Lattner141e71f2008-03-09 01:54:53 +0000331 // Note that we've seen a #else in this conditional.
332 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000334 if (Callbacks)
335 Callbacks->Else();
336
Chris Lattner141e71f2008-03-09 01:54:53 +0000337 // If the conditional is at the top level, and the #if block wasn't
338 // entered, enter the #else block now.
339 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
340 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000341 CheckEndOfDirective("else");
Chris Lattner141e71f2008-03-09 01:54:53 +0000342 break;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000343 } else {
344 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattner141e71f2008-03-09 01:54:53 +0000345 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000346 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000347 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000348
349 bool ShouldEnter;
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000350 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +0000351 // If this is in a skipping block or if we're already handled this #if
352 // block, don't bother parsing the condition.
353 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
354 DiscardUntilEndOfDirective();
355 ShouldEnter = false;
356 } else {
357 // Restore the value of LexingRawMode so that identifiers are
358 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000359 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
360 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000361 IdentifierInfo *IfNDefMacro = 0;
362 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000363 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000364 }
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000365 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Chris Lattner141e71f2008-03-09 01:54:53 +0000367 // If this is a #elif with a #else before it, report the error.
368 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000370 if (Callbacks)
371 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
372
Chris Lattner141e71f2008-03-09 01:54:53 +0000373 // If this condition is true, enter it!
374 if (ShouldEnter) {
375 CondInfo.FoundNonSkip = true;
376 break;
377 }
378 }
379 }
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Ted Kremenek60e45d42008-11-18 00:34:22 +0000381 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000382 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000383 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000384 }
385
386 // Finally, if we are out of the conditional (saw an #endif or ran off the end
387 // of the file, just stop skipping and return to lexing whatever came after
388 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000389 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000390}
391
Ted Kremenek268ee702008-12-12 18:34:08 +0000392void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000393
394 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000395 assert(CurPTHLexer);
396 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Ted Kremenek268ee702008-12-12 18:34:08 +0000398 // Skip to the next '#else', '#elif', or #endif.
399 if (CurPTHLexer->SkipBlock()) {
400 // We have reached an #endif. Both the '#' and 'endif' tokens
401 // have been consumed by the PTHLexer. Just pop off the condition level.
402 PPConditionalInfo CondInfo;
403 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000404 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek268ee702008-12-12 18:34:08 +0000405 assert(!InCond && "Can't be skipping if not in a conditional!");
406 break;
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Ted Kremenek268ee702008-12-12 18:34:08 +0000409 // We have reached a '#else' or '#elif'. Lex the next token to get
410 // the directive flavor.
411 Token Tok;
412 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Ted Kremenek268ee702008-12-12 18:34:08 +0000414 // We can actually look up the IdentifierInfo here since we aren't in
415 // raw mode.
416 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
417
418 if (K == tok::pp_else) {
419 // #else: Enter the else condition. We aren't in a nested condition
420 // since we skip those. We're always in the one matching the last
421 // blocked we skipped.
422 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
423 // Note that we've seen a #else in this conditional.
424 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Ted Kremenek268ee702008-12-12 18:34:08 +0000426 // If the #if block wasn't entered then enter the #else block now.
427 if (!CondInfo.FoundNonSkip) {
428 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Peter Collingbourne84021552011-02-28 02:37:51 +0000430 // Scan until the eod token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000431 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000432 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000433 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Ted Kremenek268ee702008-12-12 18:34:08 +0000435 break;
436 }
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Ted Kremenek268ee702008-12-12 18:34:08 +0000438 // Otherwise skip this block.
439 continue;
440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Ted Kremenek268ee702008-12-12 18:34:08 +0000442 assert(K == tok::pp_elif);
443 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
444
445 // If this is a #elif with a #else before it, report the error.
446 if (CondInfo.FoundElse)
447 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Ted Kremenek268ee702008-12-12 18:34:08 +0000449 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000450 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000451 if (CondInfo.FoundNonSkip)
452 continue;
453
454 // Evaluate the condition of the #elif.
455 IdentifierInfo *IfNDefMacro = 0;
456 CurPTHLexer->ParsingPreprocessorDirective = true;
457 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
458 CurPTHLexer->ParsingPreprocessorDirective = false;
459
460 // If this condition is true, enter it!
461 if (ShouldEnter) {
462 CondInfo.FoundNonSkip = true;
463 break;
464 }
465
466 // Otherwise, skip this block and go to the next one.
467 continue;
468 }
469}
470
Chris Lattner10725092008-03-09 04:17:44 +0000471/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
472/// return null on failure. isAngled indicates whether the file reference is
473/// for system #include's or not (i.e. using <> instead of "").
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000474const FileEntry *Preprocessor::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000475 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000476 bool isAngled,
477 const DirectoryLookup *FromDir,
478 const DirectoryLookup *&CurDir,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000479 SmallVectorImpl<char> *SearchPath,
480 SmallVectorImpl<char> *RelativePath) {
Chris Lattner10725092008-03-09 04:17:44 +0000481 // If the header lookup mechanism may be relative to the current file, pass in
482 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000483 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000484 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000485 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000486 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000488 // If there is no file entry associated with this file, it must be the
489 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000490 // it won't be scanned for preprocessor directives. If we have the
491 // predefines buffer, resolve #include references (which come from the
492 // -include command line argument) as if they came from the main file, this
493 // affects file lookup etc.
494 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000495 FID = SourceMgr.getMainFileID();
496 CurFileEnt = SourceMgr.getFileEntryForID(FID);
497 }
Chris Lattner10725092008-03-09 04:17:44 +0000498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Chris Lattner10725092008-03-09 04:17:44 +0000500 // Do a standard file entry lookup.
501 CurDir = CurDirLookup;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000502 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +0000503 Filename, isAngled, FromDir, CurDir, CurFileEnt,
504 SearchPath, RelativePath);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000505 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Chris Lattner10725092008-03-09 04:17:44 +0000507 // Otherwise, see if this is a subframework header. If so, this is relative
508 // to one of the headers on the #include stack. Walk the list of the current
509 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000510 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000511 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000512 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek74124942011-04-26 21:50:03 +0000513 SearchPath, RelativePath)))
Chris Lattner10725092008-03-09 04:17:44 +0000514 return FE;
515 }
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Chris Lattner10725092008-03-09 04:17:44 +0000517 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
518 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000519 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000520 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000521 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek74124942011-04-26 21:50:03 +0000522 if ((FE = HeaderInfo.LookupSubframeworkHeader(
523 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattner10725092008-03-09 04:17:44 +0000524 return FE;
525 }
526 }
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Chris Lattner10725092008-03-09 04:17:44 +0000528 // Otherwise, we really couldn't find the file.
529 return 0;
530}
531
Chris Lattner141e71f2008-03-09 01:54:53 +0000532
533//===----------------------------------------------------------------------===//
534// Preprocessor Directive Handling.
535//===----------------------------------------------------------------------===//
536
537/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000538/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000539/// lexer/preprocessor state, and advances the lexer(s) so that the next token
540/// read is the correct one.
541void Preprocessor::HandleDirective(Token &Result) {
542 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Chris Lattner141e71f2008-03-09 01:54:53 +0000544 // We just parsed a # character at the start of a line, so we're in directive
545 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne84021552011-02-28 02:37:51 +0000546 // EOD token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000547 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chris Lattner141e71f2008-03-09 01:54:53 +0000549 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000550
Chris Lattner141e71f2008-03-09 01:54:53 +0000551 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000552 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000553 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000554 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Chris Lattner42aa16c2009-03-18 21:00:25 +0000556 // Save the '#' token in case we need to return it later.
557 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattner141e71f2008-03-09 01:54:53 +0000559 // Read the next token, the directive flavor. This isn't expanded due to
560 // C99 6.10.3p8.
561 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Chris Lattner141e71f2008-03-09 01:54:53 +0000563 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
564 // #define A(x) #x
565 // A(abc
566 // #warning blah
567 // def)
568 // If so, the user is relying on non-portable behavior, emit a diagnostic.
569 if (InMacroArgs)
570 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Chris Lattner141e71f2008-03-09 01:54:53 +0000572TryAgain:
573 switch (Result.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000574 case tok::eod:
Chris Lattner141e71f2008-03-09 01:54:53 +0000575 return; // null directive.
576 case tok::comment:
577 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
578 LexUnexpandedToken(Result);
579 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000580 case tok::code_completion:
581 if (CodeComplete)
582 CodeComplete->CodeCompleteDirective(
583 CurPPLexer->getConditionalStackDepth() > 0);
584 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000585 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000586 if (getLangOptions().AsmPreprocessor)
587 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000588 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000589 default:
590 IdentifierInfo *II = Result.getIdentifierInfo();
591 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Chris Lattner141e71f2008-03-09 01:54:53 +0000593 // Ask what the preprocessor keyword ID is.
594 switch (II->getPPKeywordID()) {
595 default: break;
596 // C99 6.10.1 - Conditional Inclusion.
597 case tok::pp_if:
598 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
599 case tok::pp_ifdef:
600 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
601 case tok::pp_ifndef:
602 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
603 case tok::pp_elif:
604 return HandleElifDirective(Result);
605 case tok::pp_else:
606 return HandleElseDirective(Result);
607 case tok::pp_endif:
608 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Chris Lattner141e71f2008-03-09 01:54:53 +0000610 // C99 6.10.2 - Source File Inclusion.
611 case tok::pp_include:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000612 // Handle #include.
613 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000614 case tok::pp___include_macros:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000615 // Handle -imacros.
616 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Chris Lattner141e71f2008-03-09 01:54:53 +0000618 // C99 6.10.3 - Macro Replacement.
619 case tok::pp_define:
620 return HandleDefineDirective(Result);
621 case tok::pp_undef:
622 return HandleUndefDirective(Result);
623
624 // C99 6.10.4 - Line Control.
625 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000626 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Chris Lattner141e71f2008-03-09 01:54:53 +0000628 // C99 6.10.5 - Error Directive.
629 case tok::pp_error:
630 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Chris Lattner141e71f2008-03-09 01:54:53 +0000632 // C99 6.10.6 - Pragma Directive.
633 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000634 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Chris Lattner141e71f2008-03-09 01:54:53 +0000636 // GNU Extensions.
637 case tok::pp_import:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000638 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000639 case tok::pp_include_next:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000640 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Chris Lattner141e71f2008-03-09 01:54:53 +0000642 case tok::pp_warning:
643 Diag(Result, diag::ext_pp_warning_directive);
644 return HandleUserDiagnosticDirective(Result, true);
645 case tok::pp_ident:
646 return HandleIdentSCCSDirective(Result);
647 case tok::pp_sccs:
648 return HandleIdentSCCSDirective(Result);
649 case tok::pp_assert:
650 //isExtension = true; // FIXME: implement #assert
651 break;
652 case tok::pp_unassert:
653 //isExtension = true; // FIXME: implement #unassert
654 break;
655 }
656 break;
657 }
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Chris Lattner42aa16c2009-03-18 21:00:25 +0000659 // If this is a .S file, treat unknown # directives as non-preprocessor
660 // directives. This is important because # may be a comment or introduce
661 // various pseudo-ops. Just return the # token and push back the following
662 // token to be lexed next time.
663 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000664 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000665 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000666 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000667 Toks[1] = Result;
Chris Lattnerba3ca522011-01-06 05:01:51 +0000668
669 // If the second token is a hashhash token, then we need to translate it to
670 // unknown so the token lexer doesn't try to perform token pasting.
671 if (Result.is(tok::hashhash))
672 Toks[1].setKind(tok::unknown);
673
Chris Lattner42aa16c2009-03-18 21:00:25 +0000674 // Enter this token stream so that we re-lex the tokens. Make sure to
675 // enable macro expansion, in case the token after the # is an identifier
676 // that is expanded.
677 EnterTokenStream(Toks, 2, false, true);
678 return;
679 }
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Chris Lattner141e71f2008-03-09 01:54:53 +0000681 // If we reached here, the preprocessing token is not valid!
682 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattner141e71f2008-03-09 01:54:53 +0000684 // Read the rest of the PP line.
685 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Chris Lattner141e71f2008-03-09 01:54:53 +0000687 // Okay, we're done parsing the directive.
688}
689
Chris Lattner478a18e2009-01-26 06:19:46 +0000690/// GetLineValue - Convert a numeric token into an unsigned value, emitting
691/// Diagnostic DiagID if it is invalid, and returning the value in Val.
692static bool GetLineValue(Token &DigitTok, unsigned &Val,
693 unsigned DiagID, Preprocessor &PP) {
694 if (DigitTok.isNot(tok::numeric_constant)) {
695 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Peter Collingbourne84021552011-02-28 02:37:51 +0000697 if (DigitTok.isNot(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000698 PP.DiscardUntilEndOfDirective();
699 return true;
700 }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Chris Lattner478a18e2009-01-26 06:19:46 +0000702 llvm::SmallString<64> IntegerBuffer;
703 IntegerBuffer.resize(DigitTok.getLength());
704 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000705 bool Invalid = false;
706 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
707 if (Invalid)
708 return true;
709
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000710 // Verify that we have a simple digit-sequence, and compute the value. This
711 // is always a simple digit string computed in decimal, so we do this manually
712 // here.
713 Val = 0;
714 for (unsigned i = 0; i != ActualLength; ++i) {
715 if (!isdigit(DigitTokBegin[i])) {
716 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
717 diag::err_pp_line_digit_sequence);
718 PP.DiscardUntilEndOfDirective();
719 return true;
720 }
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000722 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
723 if (NextVal < Val) { // overflow.
724 PP.Diag(DigitTok, DiagID);
725 PP.DiscardUntilEndOfDirective();
726 return true;
727 }
728 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000729 }
Mike Stump1eb44332009-09-09 15:08:12 +0000730
731 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000732 if (Val == 0) {
733 PP.Diag(DigitTok, DiagID);
734 PP.DiscardUntilEndOfDirective();
735 return true;
736 }
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000738 if (DigitTokBegin[0] == '0')
739 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Chris Lattner478a18e2009-01-26 06:19:46 +0000741 return false;
742}
743
Mike Stump1eb44332009-09-09 15:08:12 +0000744/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000745/// acceptable forms are:
746/// # line digit-sequence
747/// # line digit-sequence "s-char-sequence"
748void Preprocessor::HandleLineDirective(Token &Tok) {
749 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
750 // expanded.
751 Token DigitTok;
752 Lex(DigitTok);
753
Chris Lattner359cc442009-01-26 05:29:08 +0000754 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000755 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000756 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000757 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000758
Chris Lattner478a18e2009-01-26 06:19:46 +0000759 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
760 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000761 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
762 if (LineNo >= LineLimit)
763 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner5b9a5042009-01-26 07:57:50 +0000765 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000766 Token StrTok;
767 Lex(StrTok);
768
Peter Collingbourne84021552011-02-28 02:37:51 +0000769 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
770 // string followed by eod.
771 if (StrTok.is(tok::eod))
Chris Lattner359cc442009-01-26 05:29:08 +0000772 ; // ok
773 else if (StrTok.isNot(tok::string_literal)) {
774 Diag(StrTok, diag::err_pp_line_invalid_filename);
775 DiscardUntilEndOfDirective();
776 return;
777 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000778 // Parse and validate the string, converting it into a unique ID.
779 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000780 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000781 if (Literal.hadError)
782 return DiscardUntilEndOfDirective();
783 if (Literal.Pascal) {
784 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
785 return DiscardUntilEndOfDirective();
786 }
Jay Foad65aa6882011-06-21 15:13:30 +0000787 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Peter Collingbourne84021552011-02-28 02:37:51 +0000789 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattnerab82f412009-04-17 23:30:53 +0000790 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
791 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000792 }
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Chris Lattner4c4ea172009-02-03 21:52:55 +0000794 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Chris Lattner16629382009-03-27 17:13:49 +0000796 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000797 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
798 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000799 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000800}
801
Chris Lattner478a18e2009-01-26 06:19:46 +0000802/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
803/// marker directive.
804static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
805 bool &IsSystemHeader, bool &IsExternCHeader,
806 Preprocessor &PP) {
807 unsigned FlagVal;
808 Token FlagTok;
809 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000810 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000811 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
812 return true;
813
814 if (FlagVal == 1) {
815 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Chris Lattner478a18e2009-01-26 06:19:46 +0000817 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000818 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000819 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
820 return true;
821 } else if (FlagVal == 2) {
822 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Chris Lattner137b6a62009-02-04 06:25:26 +0000824 SourceManager &SM = PP.getSourceManager();
825 // If we are leaving the current presumed file, check to make sure the
826 // presumed include stack isn't empty!
827 FileID CurFileID =
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000828 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner137b6a62009-02-04 06:25:26 +0000829 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000830 if (PLoc.isInvalid())
831 return true;
832
Chris Lattner137b6a62009-02-04 06:25:26 +0000833 // If there is no include loc (main file) or if the include loc is in a
834 // different physical file, then we aren't in a "1" line marker flag region.
835 SourceLocation IncLoc = PLoc.getIncludeLoc();
836 if (IncLoc.isInvalid() ||
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000837 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner137b6a62009-02-04 06:25:26 +0000838 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
839 PP.DiscardUntilEndOfDirective();
840 return true;
841 }
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Chris Lattner478a18e2009-01-26 06:19:46 +0000843 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000844 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000845 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
846 return true;
847 }
848
849 // We must have 3 if there are still flags.
850 if (FlagVal != 3) {
851 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000852 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000853 return true;
854 }
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Chris Lattner478a18e2009-01-26 06:19:46 +0000856 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Chris Lattner478a18e2009-01-26 06:19:46 +0000858 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000859 if (FlagTok.is(tok::eod)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000860 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000861 return true;
862
863 // We must have 4 if there is yet another flag.
864 if (FlagVal != 4) {
865 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000866 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000867 return true;
868 }
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Chris Lattner478a18e2009-01-26 06:19:46 +0000870 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Chris Lattner478a18e2009-01-26 06:19:46 +0000872 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000873 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000874
875 // There are no more valid flags here.
876 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000877 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000878 return true;
879}
880
881/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
882/// one of the following forms:
883///
884/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000885/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000886/// # 42 "file" ('1' | '2')? '3' '4'?
887///
888void Preprocessor::HandleDigitDirective(Token &DigitTok) {
889 // Validate the number and convert it to an unsigned. GNU does not have a
890 // line # limit other than it fit in 32-bits.
891 unsigned LineNo;
892 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
893 *this))
894 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner478a18e2009-01-26 06:19:46 +0000896 Token StrTok;
897 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Chris Lattner478a18e2009-01-26 06:19:46 +0000899 bool IsFileEntry = false, IsFileExit = false;
900 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000901 int FilenameID = -1;
902
Peter Collingbourne84021552011-02-28 02:37:51 +0000903 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
904 // string followed by eod.
905 if (StrTok.is(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000906 ; // ok
907 else if (StrTok.isNot(tok::string_literal)) {
908 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000909 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000910 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000911 // Parse and validate the string, converting it into a unique ID.
912 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000913 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000914 if (Literal.hadError)
915 return DiscardUntilEndOfDirective();
916 if (Literal.Pascal) {
917 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
918 return DiscardUntilEndOfDirective();
919 }
Jay Foad65aa6882011-06-21 15:13:30 +0000920 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Chris Lattner478a18e2009-01-26 06:19:46 +0000922 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000923 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000924 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000925 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000926 }
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Chris Lattner9d79eba2009-02-04 05:21:58 +0000928 // Create a line note with this information.
929 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000930 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000931 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattner16629382009-03-27 17:13:49 +0000933 // If the preprocessor has callbacks installed, notify them of the #line
934 // change. This is used so that the line marker comes out in -E mode for
935 // example.
936 if (Callbacks) {
937 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
938 if (IsFileEntry)
939 Reason = PPCallbacks::EnterFile;
940 else if (IsFileExit)
941 Reason = PPCallbacks::ExitFile;
942 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
943 if (IsExternCHeader)
944 FileKind = SrcMgr::C_ExternCSystem;
945 else if (IsSystemHeader)
946 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Chris Lattner86d0ef72010-04-14 04:28:50 +0000948 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000949 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000950}
951
952
Chris Lattner099dd052009-01-26 05:30:54 +0000953/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
954///
Mike Stump1eb44332009-09-09 15:08:12 +0000955void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000956 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000957 // PTH doesn't emit #warning or #error directives.
958 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000959 return CurPTHLexer->DiscardToEndOfLine();
960
Chris Lattner141e71f2008-03-09 01:54:53 +0000961 // Read the rest of the line raw. We do this because we don't want macros
962 // to be expanded and we don't require that the tokens be valid preprocessing
963 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
964 // collapse multiple consequtive white space between tokens, but this isn't
965 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000966 std::string Message = CurLexer->ReadToEndOfLine();
967 if (isWarning)
968 Diag(Tok, diag::pp_hash_warning) << Message;
969 else
970 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000971}
972
973/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
974///
975void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
976 // Yes, this directive is an extension.
977 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattner141e71f2008-03-09 01:54:53 +0000979 // Read the string argument.
980 Token StrTok;
981 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Chris Lattner141e71f2008-03-09 01:54:53 +0000983 // If the token kind isn't a string, it's a malformed directive.
984 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000985 StrTok.isNot(tok::wide_string_literal)) {
986 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne84021552011-02-28 02:37:51 +0000987 if (StrTok.isNot(tok::eod))
Chris Lattner099dd052009-01-26 05:30:54 +0000988 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000989 return;
990 }
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Peter Collingbourne84021552011-02-28 02:37:51 +0000992 // Verify that there is nothing after the string, other than EOD.
Chris Lattner35410d52009-04-14 05:07:49 +0000993 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000994
Douglas Gregor453091c2010-03-16 22:30:13 +0000995 if (Callbacks) {
996 bool Invalid = false;
997 std::string Str = getSpelling(StrTok, &Invalid);
998 if (!Invalid)
999 Callbacks->Ident(Tok.getLocation(), Str);
1000 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001001}
1002
1003//===----------------------------------------------------------------------===//
1004// Preprocessor Include Directive Handling.
1005//===----------------------------------------------------------------------===//
1006
1007/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1008/// checked and spelled filename, e.g. as an operand of #include. This returns
1009/// true if the input filename was in <>'s or false if it were in ""'s. The
1010/// caller is expected to provide a buffer that is large enough to hold the
1011/// spelling of the filename, but is also expected to handle the case when
1012/// this method decides to use a different buffer.
1013bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001014 StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001015 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +00001016 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Chris Lattner141e71f2008-03-09 01:54:53 +00001018 // Make sure the filename is <x> or "x".
1019 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +00001020 if (Buffer[0] == '<') {
1021 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001022 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001023 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001024 return true;
1025 }
1026 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +00001027 } else if (Buffer[0] == '"') {
1028 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001029 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001030 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001031 return true;
1032 }
1033 isAngled = false;
1034 } else {
1035 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001036 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001037 return true;
1038 }
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner141e71f2008-03-09 01:54:53 +00001040 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +00001041 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001042 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001043 Buffer = StringRef();
Chris Lattnera1394812010-01-10 01:35:12 +00001044 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001045 }
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Chris Lattner141e71f2008-03-09 01:54:53 +00001047 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001048 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001049 return isAngled;
1050}
1051
1052/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1053/// from a macro as multiple tokens, which need to be glued together. This
1054/// occurs for code like:
1055/// #define FOO <a/b.h>
1056/// #include FOO
1057/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1058///
1059/// This code concatenates and consumes tokens up to the '>' token. It returns
1060/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne84021552011-02-28 02:37:51 +00001061/// the EOD marker.
John Thompsona28cc092009-10-30 13:49:06 +00001062bool Preprocessor::ConcatenateIncludeName(
Douglas Gregorecdcb882010-10-20 22:00:55 +00001063 llvm::SmallString<128> &FilenameBuffer,
1064 SourceLocation &End) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001065 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001066
John Thompsona28cc092009-10-30 13:49:06 +00001067 Lex(CurTok);
Peter Collingbourne84021552011-02-28 02:37:51 +00001068 while (CurTok.isNot(tok::eod)) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001069 End = CurTok.getLocation();
1070
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001071 // FIXME: Provide code completion for #includes.
1072 if (CurTok.is(tok::code_completion)) {
1073 Lex(CurTok);
1074 continue;
1075 }
1076
Chris Lattner141e71f2008-03-09 01:54:53 +00001077 // Append the spelling of this token to the buffer. If there was a space
1078 // before it, add it now.
1079 if (CurTok.hasLeadingSpace())
1080 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Chris Lattner141e71f2008-03-09 01:54:53 +00001082 // Get the spelling of the token, directly into FilenameBuffer if possible.
1083 unsigned PreAppendSize = FilenameBuffer.size();
1084 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Chris Lattner141e71f2008-03-09 01:54:53 +00001086 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001087 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Chris Lattner141e71f2008-03-09 01:54:53 +00001089 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1090 if (BufPtr != &FilenameBuffer[PreAppendSize])
1091 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Chris Lattner141e71f2008-03-09 01:54:53 +00001093 // Resize FilenameBuffer to the correct size.
1094 if (CurTok.getLength() != ActualLen)
1095 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Chris Lattner141e71f2008-03-09 01:54:53 +00001097 // If we found the '>' marker, return success.
1098 if (CurTok.is(tok::greater))
1099 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001100
John Thompsona28cc092009-10-30 13:49:06 +00001101 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001102 }
1103
Peter Collingbourne84021552011-02-28 02:37:51 +00001104 // If we hit the eod marker, emit an error and return true so that the caller
1105 // knows the EOD has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001106 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001107 return true;
1108}
1109
1110/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1111/// file to be included from the lexer, then include it! This is a common
1112/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001113/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001114/// specifies the file to start searching from.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001115void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1116 Token &IncludeTok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001117 const DirectoryLookup *LookupFrom,
1118 bool isImport) {
1119
1120 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001121 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Chris Lattner141e71f2008-03-09 01:54:53 +00001123 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001124 llvm::SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001125 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001126 SourceLocation End;
1127
Chris Lattner141e71f2008-03-09 01:54:53 +00001128 switch (FilenameTok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +00001129 case tok::eod:
1130 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattner141e71f2008-03-09 01:54:53 +00001131 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Chris Lattner141e71f2008-03-09 01:54:53 +00001133 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001134 case tok::string_literal:
1135 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregorecdcb882010-10-20 22:00:55 +00001136 End = FilenameTok.getLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001137 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Chris Lattner141e71f2008-03-09 01:54:53 +00001139 case tok::less:
1140 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1141 // case, glue the tokens together into FilenameBuffer and interpret those.
1142 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +00001143 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne84021552011-02-28 02:37:51 +00001144 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001145 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001146 break;
1147 default:
1148 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1149 DiscardUntilEndOfDirective();
1150 return;
1151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001153 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001154 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001155 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1156 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001157 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001158 DiscardUntilEndOfDirective();
1159 return;
1160 }
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Peter Collingbourne84021552011-02-28 02:37:51 +00001162 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001163 // we allow macros that expand to nothing after the filename, because this
1164 // falls into the category of "#include pp-tokens new-line" specified in
1165 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001166 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001167
1168 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001169 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1170 Diag(FilenameTok, diag::err_pp_include_too_deep);
1171 return;
1172 }
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Chris Lattner141e71f2008-03-09 01:54:53 +00001174 // Search include directories.
1175 const DirectoryLookup *CurDir;
Manuel Klimek74124942011-04-26 21:50:03 +00001176 llvm::SmallString<1024> SearchPath;
1177 llvm::SmallString<1024> RelativePath;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001178 // We get the raw path only if we have 'Callbacks' to which we later pass
1179 // the path.
1180 const FileEntry *File = LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +00001181 Filename, isAngled, LookupFrom, CurDir,
1182 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL);
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,
Manuel Klimek74124942011-04-26 21:50:03 +00001187 End, SearchPath, RelativePath);
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001188
Peter Collingbournebb527862011-07-12 19:35:15 +00001189 if (File == 0) {
Eli Friedmanf84139a2011-08-30 23:07:51 +00001190 if (!SuppressIncludeNotFoundError)
1191 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Peter Collingbournebb527862011-07-12 19:35:15 +00001192 return;
1193 }
1194
Chris Lattner72181832008-09-26 20:12:23 +00001195 // The #included file will be considered to be a system header if either it is
1196 // in a system include directory, or if the #includer is a system include
1197 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001198 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001199 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001200 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001202 // Ask HeaderInfo if we should enter this #include file. If not, #including
1203 // this file will have no effect.
1204 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001205 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001206 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001207 return;
1208 }
1209
Chris Lattner141e71f2008-03-09 01:54:53 +00001210 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001211 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1212 FileCharacter);
Peter Collingbourned57b7ff2011-06-30 16:41:03 +00001213 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattner141e71f2008-03-09 01:54:53 +00001214
1215 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001216 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001217}
1218
1219/// HandleIncludeNextDirective - Implements #include_next.
1220///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001221void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1222 Token &IncludeNextTok) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001223 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Chris Lattner141e71f2008-03-09 01:54:53 +00001225 // #include_next is like #include, except that we start searching after
1226 // the current found directory. If we can't do this, issue a
1227 // diagnostic.
1228 const DirectoryLookup *Lookup = CurDirLookup;
1229 if (isInPrimaryFile()) {
1230 Lookup = 0;
1231 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1232 } else if (Lookup == 0) {
1233 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1234 } else {
1235 // Start looking up in the next directory.
1236 ++Lookup;
1237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Douglas Gregorecdcb882010-10-20 22:00:55 +00001239 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattner141e71f2008-03-09 01:54:53 +00001240}
1241
1242/// HandleImportDirective - Implements #import.
1243///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001244void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1245 Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001246 if (!Features.ObjC1) // #import is standard for ObjC.
1247 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Douglas Gregorecdcb882010-10-20 22:00:55 +00001249 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001250}
1251
Chris Lattnerde076652009-04-08 18:46:40 +00001252/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1253/// pseudo directive in the predefines buffer. This handles it by sucking all
1254/// tokens through the preprocessor and discarding them (only keeping the side
1255/// effects on the preprocessor).
Douglas Gregorecdcb882010-10-20 22:00:55 +00001256void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1257 Token &IncludeMacrosTok) {
Chris Lattnerde076652009-04-08 18:46:40 +00001258 // This directive should only occur in the predefines buffer. If not, emit an
1259 // error and reject it.
1260 SourceLocation Loc = IncludeMacrosTok.getLocation();
1261 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1262 Diag(IncludeMacrosTok.getLocation(),
1263 diag::pp_include_macros_out_of_predefines);
1264 DiscardUntilEndOfDirective();
1265 return;
1266 }
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Chris Lattnerfd105112009-04-08 20:53:24 +00001268 // Treat this as a normal #include for checking purposes. If this is
1269 // successful, it will push a new lexer onto the include stack.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001270 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Chris Lattnerfd105112009-04-08 20:53:24 +00001272 Token TmpTok;
1273 do {
1274 Lex(TmpTok);
1275 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1276 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001277}
1278
Chris Lattner141e71f2008-03-09 01:54:53 +00001279//===----------------------------------------------------------------------===//
1280// Preprocessor Macro Directive Handling.
1281//===----------------------------------------------------------------------===//
1282
1283/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1284/// definition has just been read. Lex the rest of the arguments and the
1285/// closing ), updating MI with what we learn. Return true if an error occurs
1286/// parsing the arg list.
1287bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001288 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Chris Lattner141e71f2008-03-09 01:54:53 +00001290 Token Tok;
1291 while (1) {
1292 LexUnexpandedToken(Tok);
1293 switch (Tok.getKind()) {
1294 case tok::r_paren:
1295 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001296 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001297 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001298 // Otherwise we have #define FOO(A,)
1299 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1300 return true;
1301 case tok::ellipsis: // #define X(... -> C99 varargs
Eli Friedman70c7b10c2011-08-22 18:48:28 +00001302 if (!Features.C99 && !Features.CPlusPlus0x)
1303 Diag(Tok, diag::ext_variadic_macro);
Chris Lattner141e71f2008-03-09 01:54:53 +00001304
1305 // Lex the token after the identifier.
1306 LexUnexpandedToken(Tok);
1307 if (Tok.isNot(tok::r_paren)) {
1308 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1309 return true;
1310 }
1311 // Add the __VA_ARGS__ identifier as an argument.
1312 Arguments.push_back(Ident__VA_ARGS__);
1313 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001314 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001315 return false;
Peter Collingbourne84021552011-02-28 02:37:51 +00001316 case tok::eod: // #define X(
Chris Lattner141e71f2008-03-09 01:54:53 +00001317 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1318 return true;
1319 default:
1320 // Handle keywords and identifiers here to accept things like
1321 // #define Foo(for) for.
1322 IdentifierInfo *II = Tok.getIdentifierInfo();
1323 if (II == 0) {
1324 // #define X(1
1325 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1326 return true;
1327 }
1328
1329 // If this is already used as an argument, it is used multiple times (e.g.
1330 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001331 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001332 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001333 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001334 return true;
1335 }
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Chris Lattner141e71f2008-03-09 01:54:53 +00001337 // Add the argument to the macro info.
1338 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Chris Lattner141e71f2008-03-09 01:54:53 +00001340 // Lex the token after the identifier.
1341 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Chris Lattner141e71f2008-03-09 01:54:53 +00001343 switch (Tok.getKind()) {
1344 default: // #define X(A B
1345 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1346 return true;
1347 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001348 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001349 return false;
1350 case tok::comma: // #define X(A,
1351 break;
1352 case tok::ellipsis: // #define X(A... -> GCC extension
1353 // Diagnose extension.
1354 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Chris Lattner141e71f2008-03-09 01:54:53 +00001356 // Lex the token after the identifier.
1357 LexUnexpandedToken(Tok);
1358 if (Tok.isNot(tok::r_paren)) {
1359 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1360 return true;
1361 }
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Chris Lattner141e71f2008-03-09 01:54:53 +00001363 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001364 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001365 return false;
1366 }
1367 }
1368 }
1369}
1370
1371/// HandleDefineDirective - Implements #define. This consumes the entire macro
1372/// line then lets the caller lex the next real token.
1373void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1374 ++NumDefined;
1375
1376 Token MacroNameTok;
1377 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Chris Lattner141e71f2008-03-09 01:54:53 +00001379 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001380 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001381 return;
1382
Chris Lattner2451b522009-04-21 04:46:33 +00001383 Token LastTok = MacroNameTok;
1384
Chris Lattner141e71f2008-03-09 01:54:53 +00001385 // If we are supposed to keep comments in #defines, reenable comment saving
1386 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001387 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Chris Lattner141e71f2008-03-09 01:54:53 +00001389 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001390 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Chris Lattner141e71f2008-03-09 01:54:53 +00001392 Token Tok;
1393 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Chris Lattner141e71f2008-03-09 01:54:53 +00001395 // If this is a function-like macro definition, parse the argument list,
1396 // marking each of the identifiers as being used as macro arguments. Also,
1397 // check other constraints on the first token of the macro body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001398 if (Tok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001399 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001400 } else if (Tok.hasLeadingSpace()) {
1401 // This is a normal token with leading space. Clear the leading space
1402 // marker on the first token to get proper expansion.
1403 Tok.clearFlag(Token::LeadingSpace);
1404 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001405 // This is a function-like macro definition. Read the argument list.
1406 MI->setIsFunctionLike();
1407 if (ReadMacroDefinitionArgList(MI)) {
1408 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001409 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001410 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001411 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001412 DiscardUntilEndOfDirective();
1413 return;
1414 }
1415
Chris Lattner8fde5972009-04-19 18:26:34 +00001416 // If this is a definition of a variadic C99 function-like macro, not using
1417 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Chris Lattner8fde5972009-04-19 18:26:34 +00001419 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1420 // This gets unpoisoned where it is allowed.
1421 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1422 if (MI->isC99Varargs())
1423 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Chris Lattner141e71f2008-03-09 01:54:53 +00001425 // Read the first token after the arg list for down below.
1426 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001427 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001428 // C99 requires whitespace between the macro definition and the body. Emit
1429 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001430 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001431 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001432 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1433 // first character of a replacement list is not a character required by
1434 // subclause 5.2.1, then there shall be white-space separation between the
1435 // identifier and the replacement list.". 5.2.1 lists this set:
1436 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1437 // is irrelevant here.
1438 bool isInvalid = false;
1439 if (Tok.is(tok::at)) // @ is not in the list above.
1440 isInvalid = true;
1441 else if (Tok.is(tok::unknown)) {
1442 // If we have an unknown token, it is something strange like "`". Since
1443 // all of valid characters would have lexed into a single character
1444 // token of some sort, we know this is not a valid case.
1445 isInvalid = true;
1446 }
1447 if (isInvalid)
1448 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1449 else
1450 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001451 }
Chris Lattner2451b522009-04-21 04:46:33 +00001452
Peter Collingbourne84021552011-02-28 02:37:51 +00001453 if (!Tok.is(tok::eod))
Chris Lattner2451b522009-04-21 04:46:33 +00001454 LastTok = Tok;
1455
Chris Lattner141e71f2008-03-09 01:54:53 +00001456 // Read the rest of the macro body.
1457 if (MI->isObjectLike()) {
1458 // Object-like macros are very simple, just read their body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001459 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001460 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001461 MI->AddTokenToBody(Tok);
1462 // Get the next token of the macro.
1463 LexUnexpandedToken(Tok);
1464 }
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Chris Lattner141e71f2008-03-09 01:54:53 +00001466 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001467 // Otherwise, read the body of a function-like macro. While we are at it,
1468 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1469 // parameters in function-like macro expansions.
Peter Collingbourne84021552011-02-28 02:37:51 +00001470 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001471 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001472
Chris Lattner141e71f2008-03-09 01:54:53 +00001473 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001474 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Chris Lattner141e71f2008-03-09 01:54:53 +00001476 // Get the next token of the macro.
1477 LexUnexpandedToken(Tok);
1478 continue;
1479 }
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Chris Lattner141e71f2008-03-09 01:54:53 +00001481 // Get the next token of the macro.
1482 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Chris Lattner32404692009-05-25 17:16:10 +00001484 // Check for a valid macro arg identifier.
1485 if (Tok.getIdentifierInfo() == 0 ||
1486 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1487
1488 // If this is assembler-with-cpp mode, we accept random gibberish after
1489 // the '#' because '#' is often a comment character. However, change
1490 // the kind of the token to tok::unknown so that the preprocessor isn't
1491 // confused.
Peter Collingbourne84021552011-02-28 02:37:51 +00001492 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner32404692009-05-25 17:16:10 +00001493 LastTok.setKind(tok::unknown);
1494 } else {
1495 Diag(Tok, diag::err_pp_stringize_not_parameter);
1496 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Chris Lattner32404692009-05-25 17:16:10 +00001498 // Disable __VA_ARGS__ again.
1499 Ident__VA_ARGS__->setIsPoisoned(true);
1500 return;
1501 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001502 }
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Chris Lattner32404692009-05-25 17:16:10 +00001504 // Things look ok, add the '#' and param name tokens to the macro.
1505 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001506 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001507 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Chris Lattner141e71f2008-03-09 01:54:53 +00001509 // Get the next token of the macro.
1510 LexUnexpandedToken(Tok);
1511 }
1512 }
Mike Stump1eb44332009-09-09 15:08:12 +00001513
1514
Chris Lattner141e71f2008-03-09 01:54:53 +00001515 // Disable __VA_ARGS__ again.
1516 Ident__VA_ARGS__->setIsPoisoned(true);
1517
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001518 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattner141e71f2008-03-09 01:54:53 +00001519 // replacement list.
1520 unsigned NumTokens = MI->getNumTokens();
1521 if (NumTokens != 0) {
1522 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1523 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001524 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001525 return;
1526 }
1527 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1528 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001529 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001530 return;
1531 }
1532 }
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Chris Lattner2451b522009-04-21 04:46:33 +00001534 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Chris Lattner141e71f2008-03-09 01:54:53 +00001536 // Finally, if this identifier already had a macro defined for it, verify that
1537 // the macro bodies are identical and free the old definition.
1538 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001539 // It is very common for system headers to have tons of macro redefinitions
1540 // and for warnings to be disabled in system headers. If this is the case,
1541 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001542 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001543 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001544 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner41c3ae12009-01-16 19:50:11 +00001545 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001546
Chris Lattnerf47724b2010-08-17 15:55:45 +00001547 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001548 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001549 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001550 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001551 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1552 << MacroNameTok.getIdentifierInfo();
1553 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1554 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001555 }
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001556 if (OtherMI->isWarnIfUnused())
1557 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek0ea76722008-12-15 19:56:42 +00001558 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001559 }
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Chris Lattner141e71f2008-03-09 01:54:53 +00001561 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001563 assert(!MI->isUsed());
1564 // If we need warning for not using the macro, add its location in the
1565 // warn-because-unused-macro set. If it gets used it will be removed from set.
1566 if (isInPrimaryFile() && // don't warn for include'd macros.
1567 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1568 MI->getDefinitionLoc()) != Diagnostic::Ignored) {
1569 MI->setIsWarnIfUnused(true);
1570 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1571 }
1572
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001573 // If the callbacks want to know, tell them about the macro definition.
1574 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001575 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001576}
1577
1578/// HandleUndefDirective - Implements #undef.
1579///
1580void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1581 ++NumUndefined;
1582
1583 Token MacroNameTok;
1584 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Chris Lattner141e71f2008-03-09 01:54:53 +00001586 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001587 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001588 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Chris Lattner141e71f2008-03-09 01:54:53 +00001590 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001591 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Chris Lattner141e71f2008-03-09 01:54:53 +00001593 // Okay, we finally have a valid identifier to undef.
1594 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Chris Lattner141e71f2008-03-09 01:54:53 +00001596 // If the macro is not defined, this is a noop undef, just return.
1597 if (MI == 0) return;
1598
Argyrios Kyrtzidis1f8dcfc2011-07-11 20:39:47 +00001599 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattner141e71f2008-03-09 01:54:53 +00001600 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001601
1602 // If the callbacks want to know, tell them about the macro #undef.
1603 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001604 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001605
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001606 if (MI->isWarnIfUnused())
1607 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1608
Chris Lattner141e71f2008-03-09 01:54:53 +00001609 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001610 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001611 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1612}
1613
1614
1615//===----------------------------------------------------------------------===//
1616// Preprocessor Conditional Directive Handling.
1617//===----------------------------------------------------------------------===//
1618
1619/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1620/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1621/// if any tokens have been returned or pp-directives activated before this
1622/// #ifndef has been lexed.
1623///
1624void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1625 bool ReadAnyTokensBeforeDirective) {
1626 ++NumIf;
1627 Token DirectiveTok = Result;
1628
1629 Token MacroNameTok;
1630 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Chris Lattner141e71f2008-03-09 01:54:53 +00001632 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001633 if (MacroNameTok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001634 // Skip code until we get to #endif. This helps with recovery by not
1635 // emitting an error when the #endif is reached.
1636 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1637 /*Foundnonskip*/false, /*FoundElse*/false);
1638 return;
1639 }
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Chris Lattner141e71f2008-03-09 01:54:53 +00001641 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001642 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001643
Chris Lattner13d283d2010-02-12 08:03:27 +00001644 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1645 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001646
Ted Kremenek60e45d42008-11-18 00:34:22 +00001647 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001648 // If the start of a top-level #ifdef and if the macro is not defined,
1649 // inform MIOpt that this might be the start of a proper include guard.
1650 // Otherwise it is some other form of unknown conditional which we can't
1651 // handle.
1652 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001653 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001654 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001655 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001656 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001657 }
1658
Chris Lattner141e71f2008-03-09 01:54:53 +00001659 // If there is a macro, process it.
1660 if (MI) // Mark it used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001661 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Chris Lattner141e71f2008-03-09 01:54:53 +00001663 // Should we include the stuff contained by this directive?
1664 if (!MI == isIfndef) {
1665 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001666 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1667 /*wasskip*/false, /*foundnonskip*/true,
1668 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001669 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001670 // No, skip the contents of this block.
Chris Lattner141e71f2008-03-09 01:54:53 +00001671 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001672 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001673 /*FoundElse*/false);
1674 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001675
1676 if (Callbacks) {
1677 if (isIfndef)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001678 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001679 else
Craig Silverstein2aa92672010-11-19 21:33:15 +00001680 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001681 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001682}
1683
1684/// HandleIfDirective - Implements the #if directive.
1685///
1686void Preprocessor::HandleIfDirective(Token &IfToken,
1687 bool ReadAnyTokensBeforeDirective) {
1688 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Craig Silverstein08985b92010-11-06 01:19:03 +00001690 // Parse and evaluate the conditional expression.
Chris Lattner141e71f2008-03-09 01:54:53 +00001691 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein08985b92010-11-06 01:19:03 +00001692 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1693 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1694 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes0049db62008-06-01 18:31:24 +00001695
1696 // If this condition is equivalent to #ifndef X, and if this is the first
1697 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001698 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001699 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001700 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001701 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001702 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001703 }
1704
Chris Lattner141e71f2008-03-09 01:54:53 +00001705 // Should we include the stuff contained by this directive?
1706 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001707 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001708 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001709 /*foundnonskip*/true, /*foundelse*/false);
1710 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001711 // No, skip the contents of this block.
Mike Stump1eb44332009-09-09 15:08:12 +00001712 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001713 /*FoundElse*/false);
1714 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001715
1716 if (Callbacks)
1717 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001718}
1719
1720/// HandleEndifDirective - Implements the #endif directive.
1721///
1722void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1723 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Chris Lattner141e71f2008-03-09 01:54:53 +00001725 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001726 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Chris Lattner141e71f2008-03-09 01:54:53 +00001728 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001729 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001730 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001731 Diag(EndifToken, diag::err_pp_endif_without_if);
1732 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001733 }
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Chris Lattner141e71f2008-03-09 01:54:53 +00001735 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001736 if (CurPPLexer->getConditionalStackDepth() == 0)
1737 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Ted Kremenek60e45d42008-11-18 00:34:22 +00001739 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001740 "This code should only be reachable in the non-skipping case!");
Craig Silverstein08985b92010-11-06 01:19:03 +00001741
1742 if (Callbacks)
1743 Callbacks->Endif();
Chris Lattner141e71f2008-03-09 01:54:53 +00001744}
1745
Craig Silverstein08985b92010-11-06 01:19:03 +00001746/// HandleElseDirective - Implements the #else directive.
1747///
Chris Lattner141e71f2008-03-09 01:54:53 +00001748void Preprocessor::HandleElseDirective(Token &Result) {
1749 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Chris Lattner141e71f2008-03-09 01:54:53 +00001751 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001752 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Chris Lattner141e71f2008-03-09 01:54:53 +00001754 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001755 if (CurPPLexer->popConditionalLevel(CI)) {
1756 Diag(Result, diag::pp_err_else_without_if);
1757 return;
1758 }
Mike Stump1eb44332009-09-09 15:08:12 +00001759
Chris Lattner141e71f2008-03-09 01:54:53 +00001760 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001761 if (CurPPLexer->getConditionalStackDepth() == 0)
1762 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001763
1764 // If this is a #else with a #else before it, report the error.
1765 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Craig Silverstein08985b92010-11-06 01:19:03 +00001767 // Finally, skip the rest of the contents of this block.
1768 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1769 /*FoundElse*/true);
1770
1771 if (Callbacks)
1772 Callbacks->Else();
Chris Lattner141e71f2008-03-09 01:54:53 +00001773}
1774
Craig Silverstein08985b92010-11-06 01:19:03 +00001775/// HandleElifDirective - Implements the #elif directive.
1776///
Chris Lattner141e71f2008-03-09 01:54:53 +00001777void Preprocessor::HandleElifDirective(Token &ElifToken) {
1778 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Chris Lattner141e71f2008-03-09 01:54:53 +00001780 // #elif directive in a non-skipping conditional... start skipping.
1781 // We don't care what the condition is, because we will always skip it (since
1782 // the block immediately before it was included).
Craig Silverstein08985b92010-11-06 01:19:03 +00001783 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001784 DiscardUntilEndOfDirective();
Craig Silverstein08985b92010-11-06 01:19:03 +00001785 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001786
1787 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001788 if (CurPPLexer->popConditionalLevel(CI)) {
1789 Diag(ElifToken, diag::pp_err_elif_without_if);
1790 return;
1791 }
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Chris Lattner141e71f2008-03-09 01:54:53 +00001793 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001794 if (CurPPLexer->getConditionalStackDepth() == 0)
1795 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Chris Lattner141e71f2008-03-09 01:54:53 +00001797 // If this is a #elif with a #else before it, report the error.
1798 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1799
Craig Silverstein08985b92010-11-06 01:19:03 +00001800 // Finally, skip the rest of the contents of this block.
1801 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1802 /*FoundElse*/CI.FoundElse);
1803
1804 if (Callbacks)
1805 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001806}