blob: e0729f123f0e983cb7bb543b9e8887bdcb4ab3e9 [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"
Chris Lattner6e290142009-11-30 04:18:44 +000020#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000022#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000023using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// Utility Methods for Preprocessor Directive Handling.
27//===----------------------------------------------------------------------===//
28
Chris Lattnerf47724b2010-08-17 15:55:45 +000029MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenek0ea76722008-12-15 19:56:42 +000030 MacroInfo *MI;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Ted Kremenek0ea76722008-12-15 19:56:42 +000032 if (!MICache.empty()) {
33 MI = MICache.back();
34 MICache.pop_back();
Chris Lattner0301b3f2009-02-20 22:19:20 +000035 } else
36 MI = (MacroInfo*) BP.Allocate<MacroInfo>();
Chris Lattnerf47724b2010-08-17 15:55:45 +000037 return MI;
38}
39
40MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
41 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000042 new (MI) MacroInfo(L);
43 return MI;
44}
45
Chris Lattnerf47724b2010-08-17 15:55:45 +000046MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
47 MacroInfo *MI = AllocateMacroInfo();
48 new (MI) MacroInfo(MacroToClone, BP);
49 return MI;
50}
51
Chris Lattner0301b3f2009-02-20 22:19:20 +000052/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
53/// be reused for allocating new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000054void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Chris Lattner0301b3f2009-02-20 22:19:20 +000055 MICache.push_back(MI);
Chris Lattner2c1ab902010-08-18 16:08:51 +000056 MI->FreeArgumentList();
Chris Lattner0301b3f2009-02-20 22:19:20 +000057}
58
59
Chris Lattner141e71f2008-03-09 01:54:53 +000060/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
61/// current line until the tok::eom token is found.
62void Preprocessor::DiscardUntilEndOfDirective() {
63 Token Tmp;
64 do {
65 LexUnexpandedToken(Tmp);
66 } while (Tmp.isNot(tok::eom));
67}
68
Chris Lattner141e71f2008-03-09 01:54:53 +000069/// ReadMacroName - Lex and validate a macro name, which occurs after a
70/// #define or #undef. This sets the token kind to eom and discards the rest
71/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
72/// this is due to a a #define, 2 if #undef directive, 0 if it is something
73/// else (e.g. #ifdef).
74void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
75 // Read the token, don't allow macro expansion on it.
76 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Chris Lattner141e71f2008-03-09 01:54:53 +000078 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000079 if (MacroNameTok.is(tok::eom)) {
80 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
81 return;
82 }
Mike Stump1eb44332009-09-09 15:08:12 +000083
Chris Lattner141e71f2008-03-09 01:54:53 +000084 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
85 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +000086 bool Invalid = false;
87 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
88 if (Invalid)
89 return;
90
Chris Lattner9485d232008-12-13 20:12:40 +000091 const IdentifierInfo &Info = Identifiers.get(Spelling);
92 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +000093 // C++ 2.5p2: Alternative tokens behave the same as its primary token
94 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +000095 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000096 else
97 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
98 // Fall through on error.
99 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
100 // Error if defining "defined": C99 6.10.8.4.
101 Diag(MacroNameTok, diag::err_defined_macro_name);
102 } else if (isDefineUndef && II->hasMacroDefinition() &&
103 getMacroInfo(II)->isBuiltinMacro()) {
104 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
105 if (isDefineUndef == 1)
106 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
107 else
108 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
109 } else {
110 // Okay, we got a good identifier node. Return it.
111 return;
112 }
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Chris Lattner141e71f2008-03-09 01:54:53 +0000114 // Invalid macro name, read and discard the rest of the line. Then set the
115 // token kind to tok::eom.
116 MacroNameTok.setKind(tok::eom);
117 return DiscardUntilEndOfDirective();
118}
119
120/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattnerab82f412009-04-17 23:30:53 +0000121/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
122/// true, then we consider macros that expand to zero tokens as being ok.
123void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000124 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000125 // Lex unexpanded tokens for most directives: macros might expand to zero
126 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
127 // #line) allow empty macros.
128 if (EnableMacros)
129 Lex(Tmp);
130 else
131 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Chris Lattner141e71f2008-03-09 01:54:53 +0000133 // There should be no tokens after the directive, but we allow them as an
134 // extension.
135 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
136 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Chris Lattner141e71f2008-03-09 01:54:53 +0000138 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000139 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
140 // because it is more trouble than it is worth to insert /**/ and check that
141 // there is no /**/ in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000142 FixItHint Hint;
Chris Lattner959875a2009-04-14 05:15:20 +0000143 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
Douglas Gregor849b2432010-03-31 17:46:05 +0000144 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
145 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000146 DiscardUntilEndOfDirective();
147 }
148}
149
150
151
152/// SkipExcludedConditionalBlock - We just read a #if or related directive and
153/// decided that the subsequent tokens are in the #if'd out portion of the
154/// file. Lex the rest of the file, until we see an #endif. If
155/// FoundNonSkipPortion is true, then we have already emitted code for part of
156/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
157/// is true, then #else directives are ok, if not, then we have already seen one
158/// so a #else directive is a duplicate. When this returns, the caller can lex
159/// the first valid token.
160void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
161 bool FoundNonSkipPortion,
162 bool FoundElse) {
163 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000164 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000165
Ted Kremenek60e45d42008-11-18 00:34:22 +0000166 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000167 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Ted Kremenek268ee702008-12-12 18:34:08 +0000169 if (CurPTHLexer) {
170 PTHSkipExcludedConditionalBlock();
171 return;
172 }
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Chris Lattner141e71f2008-03-09 01:54:53 +0000174 // Enter raw mode to disable identifier lookup (and thus macro expansion),
175 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000176 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000177 Token Tok;
178 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000179 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Douglas Gregorf44e8542010-08-24 19:08:16 +0000181 if (Tok.is(tok::code_completion)) {
182 if (CodeComplete)
183 CodeComplete->CodeCompleteInConditionalExclusion();
184 continue;
185 }
186
Chris Lattner141e71f2008-03-09 01:54:53 +0000187 // If this is the end of the buffer, we have an error.
188 if (Tok.is(tok::eof)) {
189 // Emit errors for each unterminated conditional on the stack, including
190 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000191 while (!CurPPLexer->ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000192 if (!isCodeCompletionFile(Tok.getLocation()))
193 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
194 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000195 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000196 }
197
Chris Lattner141e71f2008-03-09 01:54:53 +0000198 // Just return and let the caller lex after this #include.
199 break;
200 }
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Chris Lattner141e71f2008-03-09 01:54:53 +0000202 // If this token is not a preprocessor directive, just skip it.
203 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
204 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Chris Lattner141e71f2008-03-09 01:54:53 +0000206 // We just parsed a # character at the start of a line, so we're in
207 // directive mode. Tell the lexer this so any newlines we see will be
208 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000209 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000210 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000211
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattner141e71f2008-03-09 01:54:53 +0000213 // Read the next token, the directive flavor.
214 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Chris Lattner141e71f2008-03-09 01:54:53 +0000216 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
217 // something bogus), skip it.
218 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000219 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000220 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000221 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000222 continue;
223 }
224
225 // If the first letter isn't i or e, it isn't intesting to us. We know that
226 // this is safe in the face of spelling differences, because there is no way
227 // to spell an i/e in a strange way that is another letter. Skipping this
228 // allows us to avoid looking up the identifier info for #define/#undef and
229 // other common directives.
Douglas Gregora5430162010-03-16 20:46:42 +0000230 bool Invalid = false;
231 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation(),
232 &Invalid);
233 if (Invalid)
234 return;
235
Chris Lattner141e71f2008-03-09 01:54:53 +0000236 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000237 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000238 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000239 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000240 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000241 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000242 continue;
243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattner141e71f2008-03-09 01:54:53 +0000245 // Get the identifier name without trigraphs or embedded newlines. Note
246 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
247 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000248 char DirectiveBuf[20];
249 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000250 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000251 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000252 } else {
253 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000254 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000255 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000256 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000257 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000258 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000259 continue;
260 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000261 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
262 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000263 }
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000265 if (Directive.startswith("if")) {
266 llvm::StringRef Sub = Directive.substr(2);
267 if (Sub.empty() || // "if"
268 Sub == "def" || // "ifdef"
269 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000270 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
271 // bother parsing the condition.
272 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000273 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000274 /*foundnonskip*/false,
275 /*fnddelse*/false);
276 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000277 } else if (Directive[0] == 'e') {
278 llvm::StringRef Sub = Directive.substr(1);
279 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000280 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000281 PPConditionalInfo CondInfo;
282 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000283 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000284 InCond = InCond; // Silence warning in no-asserts mode.
285 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Chris Lattner141e71f2008-03-09 01:54:53 +0000287 // If we popped the outermost skipping block, we're done skipping!
288 if (!CondInfo.WasSkipping)
289 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000290 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000291 // #else directive in a skipping conditional. If not in some other
292 // skipping conditional, and if #else hasn't already been seen, enter it
293 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000294 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000295 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Chris Lattner141e71f2008-03-09 01:54:53 +0000297 // If this is a #else with a #else before it, report the error.
298 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattner141e71f2008-03-09 01:54:53 +0000300 // Note that we've seen a #else in this conditional.
301 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 // If the conditional is at the top level, and the #if block wasn't
304 // entered, enter the #else block now.
305 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
306 CondInfo.FoundNonSkip = true;
307 break;
308 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000309 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000310 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000311
312 bool ShouldEnter;
313 // If this is in a skipping block or if we're already handled this #if
314 // block, don't bother parsing the condition.
315 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
316 DiscardUntilEndOfDirective();
317 ShouldEnter = false;
318 } else {
319 // Restore the value of LexingRawMode so that identifiers are
320 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000321 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
322 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000323 IdentifierInfo *IfNDefMacro = 0;
324 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000325 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Chris Lattner141e71f2008-03-09 01:54:53 +0000328 // If this is a #elif with a #else before it, report the error.
329 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Chris Lattner141e71f2008-03-09 01:54:53 +0000331 // If this condition is true, enter it!
332 if (ShouldEnter) {
333 CondInfo.FoundNonSkip = true;
334 break;
335 }
336 }
337 }
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Ted Kremenek60e45d42008-11-18 00:34:22 +0000339 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000340 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000341 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000342 }
343
344 // Finally, if we are out of the conditional (saw an #endif or ran off the end
345 // of the file, just stop skipping and return to lexing whatever came after
346 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000347 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000348}
349
Ted Kremenek268ee702008-12-12 18:34:08 +0000350void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000351
352 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000353 assert(CurPTHLexer);
354 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Ted Kremenek268ee702008-12-12 18:34:08 +0000356 // Skip to the next '#else', '#elif', or #endif.
357 if (CurPTHLexer->SkipBlock()) {
358 // We have reached an #endif. Both the '#' and 'endif' tokens
359 // have been consumed by the PTHLexer. Just pop off the condition level.
360 PPConditionalInfo CondInfo;
361 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
362 InCond = InCond; // Silence warning in no-asserts mode.
363 assert(!InCond && "Can't be skipping if not in a conditional!");
364 break;
365 }
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Ted Kremenek268ee702008-12-12 18:34:08 +0000367 // We have reached a '#else' or '#elif'. Lex the next token to get
368 // the directive flavor.
369 Token Tok;
370 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Ted Kremenek268ee702008-12-12 18:34:08 +0000372 // We can actually look up the IdentifierInfo here since we aren't in
373 // raw mode.
374 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
375
376 if (K == tok::pp_else) {
377 // #else: Enter the else condition. We aren't in a nested condition
378 // since we skip those. We're always in the one matching the last
379 // blocked we skipped.
380 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
381 // Note that we've seen a #else in this conditional.
382 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Ted Kremenek268ee702008-12-12 18:34:08 +0000384 // If the #if block wasn't entered then enter the #else block now.
385 if (!CondInfo.FoundNonSkip) {
386 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000388 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000389 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000390 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000391 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Ted Kremenek268ee702008-12-12 18:34:08 +0000393 break;
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Ted Kremenek268ee702008-12-12 18:34:08 +0000396 // Otherwise skip this block.
397 continue;
398 }
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Ted Kremenek268ee702008-12-12 18:34:08 +0000400 assert(K == tok::pp_elif);
401 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
402
403 // If this is a #elif with a #else before it, report the error.
404 if (CondInfo.FoundElse)
405 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Ted Kremenek268ee702008-12-12 18:34:08 +0000407 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000408 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000409 if (CondInfo.FoundNonSkip)
410 continue;
411
412 // Evaluate the condition of the #elif.
413 IdentifierInfo *IfNDefMacro = 0;
414 CurPTHLexer->ParsingPreprocessorDirective = true;
415 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
416 CurPTHLexer->ParsingPreprocessorDirective = false;
417
418 // If this condition is true, enter it!
419 if (ShouldEnter) {
420 CondInfo.FoundNonSkip = true;
421 break;
422 }
423
424 // Otherwise, skip this block and go to the next one.
425 continue;
426 }
427}
428
Chris Lattner10725092008-03-09 04:17:44 +0000429/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
430/// return null on failure. isAngled indicates whether the file reference is
431/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnera1394812010-01-10 01:35:12 +0000432const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattner10725092008-03-09 04:17:44 +0000433 bool isAngled,
434 const DirectoryLookup *FromDir,
435 const DirectoryLookup *&CurDir) {
436 // If the header lookup mechanism may be relative to the current file, pass in
437 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000438 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000439 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000440 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000441 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000443 // If there is no file entry associated with this file, it must be the
444 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000445 // it won't be scanned for preprocessor directives. If we have the
446 // predefines buffer, resolve #include references (which come from the
447 // -include command line argument) as if they came from the main file, this
448 // affects file lookup etc.
449 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000450 FID = SourceMgr.getMainFileID();
451 CurFileEnt = SourceMgr.getFileEntryForID(FID);
452 }
Chris Lattner10725092008-03-09 04:17:44 +0000453 }
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Chris Lattner10725092008-03-09 04:17:44 +0000455 // Do a standard file entry lookup.
456 CurDir = CurDirLookup;
457 const FileEntry *FE =
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000458 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000459 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattner10725092008-03-09 04:17:44 +0000461 // Otherwise, see if this is a subframework header. If so, this is relative
462 // to one of the headers on the #include stack. Walk the list of the current
463 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000464 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000465 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000466 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000467 return FE;
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Chris Lattner10725092008-03-09 04:17:44 +0000470 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
471 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000472 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000473 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000474 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000475 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000476 return FE;
477 }
478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner10725092008-03-09 04:17:44 +0000480 // Otherwise, we really couldn't find the file.
481 return 0;
482}
483
Chris Lattner141e71f2008-03-09 01:54:53 +0000484
485//===----------------------------------------------------------------------===//
486// Preprocessor Directive Handling.
487//===----------------------------------------------------------------------===//
488
489/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000490/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000491/// lexer/preprocessor state, and advances the lexer(s) so that the next token
492/// read is the correct one.
493void Preprocessor::HandleDirective(Token &Result) {
494 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Chris Lattner141e71f2008-03-09 01:54:53 +0000496 // We just parsed a # character at the start of a line, so we're in directive
497 // mode. Tell the lexer this so any newlines we see will be converted into an
498 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000499 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Chris Lattner141e71f2008-03-09 01:54:53 +0000501 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000502
Chris Lattner141e71f2008-03-09 01:54:53 +0000503 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000504 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000505 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000506 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Chris Lattner42aa16c2009-03-18 21:00:25 +0000508 // Save the '#' token in case we need to return it later.
509 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattner141e71f2008-03-09 01:54:53 +0000511 // Read the next token, the directive flavor. This isn't expanded due to
512 // C99 6.10.3p8.
513 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Chris Lattner141e71f2008-03-09 01:54:53 +0000515 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
516 // #define A(x) #x
517 // A(abc
518 // #warning blah
519 // def)
520 // If so, the user is relying on non-portable behavior, emit a diagnostic.
521 if (InMacroArgs)
522 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Chris Lattner141e71f2008-03-09 01:54:53 +0000524TryAgain:
525 switch (Result.getKind()) {
526 case tok::eom:
527 return; // null directive.
528 case tok::comment:
529 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
530 LexUnexpandedToken(Result);
531 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000532 case tok::code_completion:
533 if (CodeComplete)
534 CodeComplete->CodeCompleteDirective(
535 CurPPLexer->getConditionalStackDepth() > 0);
536 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000537 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000538 if (getLangOptions().AsmPreprocessor)
539 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000540 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000541 default:
542 IdentifierInfo *II = Result.getIdentifierInfo();
543 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner141e71f2008-03-09 01:54:53 +0000545 // Ask what the preprocessor keyword ID is.
546 switch (II->getPPKeywordID()) {
547 default: break;
548 // C99 6.10.1 - Conditional Inclusion.
549 case tok::pp_if:
550 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
551 case tok::pp_ifdef:
552 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
553 case tok::pp_ifndef:
554 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
555 case tok::pp_elif:
556 return HandleElifDirective(Result);
557 case tok::pp_else:
558 return HandleElseDirective(Result);
559 case tok::pp_endif:
560 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Chris Lattner141e71f2008-03-09 01:54:53 +0000562 // C99 6.10.2 - Source File Inclusion.
563 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000564 return HandleIncludeDirective(Result); // Handle #include.
565 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000566 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Chris Lattner141e71f2008-03-09 01:54:53 +0000568 // C99 6.10.3 - Macro Replacement.
569 case tok::pp_define:
570 return HandleDefineDirective(Result);
571 case tok::pp_undef:
572 return HandleUndefDirective(Result);
573
574 // C99 6.10.4 - Line Control.
575 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000576 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattner141e71f2008-03-09 01:54:53 +0000578 // C99 6.10.5 - Error Directive.
579 case tok::pp_error:
580 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Chris Lattner141e71f2008-03-09 01:54:53 +0000582 // C99 6.10.6 - Pragma Directive.
583 case tok::pp_pragma:
584 return HandlePragmaDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner141e71f2008-03-09 01:54:53 +0000586 // GNU Extensions.
587 case tok::pp_import:
588 return HandleImportDirective(Result);
589 case tok::pp_include_next:
590 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattner141e71f2008-03-09 01:54:53 +0000592 case tok::pp_warning:
593 Diag(Result, diag::ext_pp_warning_directive);
594 return HandleUserDiagnosticDirective(Result, true);
595 case tok::pp_ident:
596 return HandleIdentSCCSDirective(Result);
597 case tok::pp_sccs:
598 return HandleIdentSCCSDirective(Result);
599 case tok::pp_assert:
600 //isExtension = true; // FIXME: implement #assert
601 break;
602 case tok::pp_unassert:
603 //isExtension = true; // FIXME: implement #unassert
604 break;
605 }
606 break;
607 }
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattner42aa16c2009-03-18 21:00:25 +0000609 // If this is a .S file, treat unknown # directives as non-preprocessor
610 // directives. This is important because # may be a comment or introduce
611 // various pseudo-ops. Just return the # token and push back the following
612 // token to be lexed next time.
613 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000614 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000615 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000616 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000617 Toks[1] = Result;
618 // Enter this token stream so that we re-lex the tokens. Make sure to
619 // enable macro expansion, in case the token after the # is an identifier
620 // that is expanded.
621 EnterTokenStream(Toks, 2, false, true);
622 return;
623 }
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Chris Lattner141e71f2008-03-09 01:54:53 +0000625 // If we reached here, the preprocessing token is not valid!
626 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Chris Lattner141e71f2008-03-09 01:54:53 +0000628 // Read the rest of the PP line.
629 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Chris Lattner141e71f2008-03-09 01:54:53 +0000631 // Okay, we're done parsing the directive.
632}
633
Chris Lattner478a18e2009-01-26 06:19:46 +0000634/// GetLineValue - Convert a numeric token into an unsigned value, emitting
635/// Diagnostic DiagID if it is invalid, and returning the value in Val.
636static bool GetLineValue(Token &DigitTok, unsigned &Val,
637 unsigned DiagID, Preprocessor &PP) {
638 if (DigitTok.isNot(tok::numeric_constant)) {
639 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Chris Lattner478a18e2009-01-26 06:19:46 +0000641 if (DigitTok.isNot(tok::eom))
642 PP.DiscardUntilEndOfDirective();
643 return true;
644 }
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Chris Lattner478a18e2009-01-26 06:19:46 +0000646 llvm::SmallString<64> IntegerBuffer;
647 IntegerBuffer.resize(DigitTok.getLength());
648 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000649 bool Invalid = false;
650 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
651 if (Invalid)
652 return true;
653
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000654 // Verify that we have a simple digit-sequence, and compute the value. This
655 // is always a simple digit string computed in decimal, so we do this manually
656 // here.
657 Val = 0;
658 for (unsigned i = 0; i != ActualLength; ++i) {
659 if (!isdigit(DigitTokBegin[i])) {
660 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
661 diag::err_pp_line_digit_sequence);
662 PP.DiscardUntilEndOfDirective();
663 return true;
664 }
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000666 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
667 if (NextVal < Val) { // overflow.
668 PP.Diag(DigitTok, DiagID);
669 PP.DiscardUntilEndOfDirective();
670 return true;
671 }
672 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000673 }
Mike Stump1eb44332009-09-09 15:08:12 +0000674
675 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000676 if (Val == 0) {
677 PP.Diag(DigitTok, DiagID);
678 PP.DiscardUntilEndOfDirective();
679 return true;
680 }
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000682 if (DigitTokBegin[0] == '0')
683 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattner478a18e2009-01-26 06:19:46 +0000685 return false;
686}
687
Mike Stump1eb44332009-09-09 15:08:12 +0000688/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000689/// acceptable forms are:
690/// # line digit-sequence
691/// # line digit-sequence "s-char-sequence"
692void Preprocessor::HandleLineDirective(Token &Tok) {
693 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
694 // expanded.
695 Token DigitTok;
696 Lex(DigitTok);
697
Chris Lattner359cc442009-01-26 05:29:08 +0000698 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000699 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000700 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000701 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000702
Chris Lattner478a18e2009-01-26 06:19:46 +0000703 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
704 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000705 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
706 if (LineNo >= LineLimit)
707 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattner5b9a5042009-01-26 07:57:50 +0000709 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000710 Token StrTok;
711 Lex(StrTok);
712
713 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
714 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000715 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000716 ; // ok
717 else if (StrTok.isNot(tok::string_literal)) {
718 Diag(StrTok, diag::err_pp_line_invalid_filename);
719 DiscardUntilEndOfDirective();
720 return;
721 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000722 // Parse and validate the string, converting it into a unique ID.
723 StringLiteralParser Literal(&StrTok, 1, *this);
724 assert(!Literal.AnyWide && "Didn't allow wide strings in");
725 if (Literal.hadError)
726 return DiscardUntilEndOfDirective();
727 if (Literal.Pascal) {
728 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
729 return DiscardUntilEndOfDirective();
730 }
731 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
732 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Chris Lattnerab82f412009-04-17 23:30:53 +0000734 // Verify that there is nothing after the string, other than EOM. Because
735 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
736 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000737 }
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Chris Lattner4c4ea172009-02-03 21:52:55 +0000739 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Chris Lattner16629382009-03-27 17:13:49 +0000741 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000742 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
743 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000744 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000745}
746
Chris Lattner478a18e2009-01-26 06:19:46 +0000747/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
748/// marker directive.
749static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
750 bool &IsSystemHeader, bool &IsExternCHeader,
751 Preprocessor &PP) {
752 unsigned FlagVal;
753 Token FlagTok;
754 PP.Lex(FlagTok);
755 if (FlagTok.is(tok::eom)) return false;
756 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
757 return true;
758
759 if (FlagVal == 1) {
760 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattner478a18e2009-01-26 06:19:46 +0000762 PP.Lex(FlagTok);
763 if (FlagTok.is(tok::eom)) return false;
764 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
765 return true;
766 } else if (FlagVal == 2) {
767 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Chris Lattner137b6a62009-02-04 06:25:26 +0000769 SourceManager &SM = PP.getSourceManager();
770 // If we are leaving the current presumed file, check to make sure the
771 // presumed include stack isn't empty!
772 FileID CurFileID =
773 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
774 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Chris Lattner137b6a62009-02-04 06:25:26 +0000776 // If there is no include loc (main file) or if the include loc is in a
777 // different physical file, then we aren't in a "1" line marker flag region.
778 SourceLocation IncLoc = PLoc.getIncludeLoc();
779 if (IncLoc.isInvalid() ||
780 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
781 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
782 PP.DiscardUntilEndOfDirective();
783 return true;
784 }
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Chris Lattner478a18e2009-01-26 06:19:46 +0000786 PP.Lex(FlagTok);
787 if (FlagTok.is(tok::eom)) return false;
788 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
789 return true;
790 }
791
792 // We must have 3 if there are still flags.
793 if (FlagVal != 3) {
794 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000795 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000796 return true;
797 }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Chris Lattner478a18e2009-01-26 06:19:46 +0000799 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Chris Lattner478a18e2009-01-26 06:19:46 +0000801 PP.Lex(FlagTok);
802 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000803 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000804 return true;
805
806 // We must have 4 if there is yet another flag.
807 if (FlagVal != 4) {
808 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000809 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000810 return true;
811 }
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Chris Lattner478a18e2009-01-26 06:19:46 +0000813 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Chris Lattner478a18e2009-01-26 06:19:46 +0000815 PP.Lex(FlagTok);
816 if (FlagTok.is(tok::eom)) return false;
817
818 // There are no more valid flags here.
819 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000820 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000821 return true;
822}
823
824/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
825/// one of the following forms:
826///
827/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000828/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000829/// # 42 "file" ('1' | '2')? '3' '4'?
830///
831void Preprocessor::HandleDigitDirective(Token &DigitTok) {
832 // Validate the number and convert it to an unsigned. GNU does not have a
833 // line # limit other than it fit in 32-bits.
834 unsigned LineNo;
835 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
836 *this))
837 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Chris Lattner478a18e2009-01-26 06:19:46 +0000839 Token StrTok;
840 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Chris Lattner478a18e2009-01-26 06:19:46 +0000842 bool IsFileEntry = false, IsFileExit = false;
843 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000844 int FilenameID = -1;
845
Chris Lattner478a18e2009-01-26 06:19:46 +0000846 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
847 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000848 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000849 ; // ok
850 else if (StrTok.isNot(tok::string_literal)) {
851 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000852 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000853 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000854 // Parse and validate the string, converting it into a unique ID.
855 StringLiteralParser Literal(&StrTok, 1, *this);
856 assert(!Literal.AnyWide && "Didn't allow wide strings in");
857 if (Literal.hadError)
858 return DiscardUntilEndOfDirective();
859 if (Literal.Pascal) {
860 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
861 return DiscardUntilEndOfDirective();
862 }
863 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
864 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Chris Lattner478a18e2009-01-26 06:19:46 +0000866 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000867 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000868 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000869 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000870 }
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Chris Lattner9d79eba2009-02-04 05:21:58 +0000872 // Create a line note with this information.
873 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000874 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000875 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Chris Lattner16629382009-03-27 17:13:49 +0000877 // If the preprocessor has callbacks installed, notify them of the #line
878 // change. This is used so that the line marker comes out in -E mode for
879 // example.
880 if (Callbacks) {
881 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
882 if (IsFileEntry)
883 Reason = PPCallbacks::EnterFile;
884 else if (IsFileExit)
885 Reason = PPCallbacks::ExitFile;
886 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
887 if (IsExternCHeader)
888 FileKind = SrcMgr::C_ExternCSystem;
889 else if (IsSystemHeader)
890 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Chris Lattner86d0ef72010-04-14 04:28:50 +0000892 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000893 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000894}
895
896
Chris Lattner099dd052009-01-26 05:30:54 +0000897/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
898///
Mike Stump1eb44332009-09-09 15:08:12 +0000899void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000900 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000901 // PTH doesn't emit #warning or #error directives.
902 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000903 return CurPTHLexer->DiscardToEndOfLine();
904
Chris Lattner141e71f2008-03-09 01:54:53 +0000905 // Read the rest of the line raw. We do this because we don't want macros
906 // to be expanded and we don't require that the tokens be valid preprocessing
907 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
908 // collapse multiple consequtive white space between tokens, but this isn't
909 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000910 std::string Message = CurLexer->ReadToEndOfLine();
911 if (isWarning)
912 Diag(Tok, diag::pp_hash_warning) << Message;
913 else
914 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000915}
916
917/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
918///
919void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
920 // Yes, this directive is an extension.
921 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Chris Lattner141e71f2008-03-09 01:54:53 +0000923 // Read the string argument.
924 Token StrTok;
925 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Chris Lattner141e71f2008-03-09 01:54:53 +0000927 // If the token kind isn't a string, it's a malformed directive.
928 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000929 StrTok.isNot(tok::wide_string_literal)) {
930 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000931 if (StrTok.isNot(tok::eom))
932 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000933 return;
934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattner141e71f2008-03-09 01:54:53 +0000936 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000937 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000938
Douglas Gregor453091c2010-03-16 22:30:13 +0000939 if (Callbacks) {
940 bool Invalid = false;
941 std::string Str = getSpelling(StrTok, &Invalid);
942 if (!Invalid)
943 Callbacks->Ident(Tok.getLocation(), Str);
944 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000945}
946
947//===----------------------------------------------------------------------===//
948// Preprocessor Include Directive Handling.
949//===----------------------------------------------------------------------===//
950
951/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
952/// checked and spelled filename, e.g. as an operand of #include. This returns
953/// true if the input filename was in <>'s or false if it were in ""'s. The
954/// caller is expected to provide a buffer that is large enough to hold the
955/// spelling of the filename, but is also expected to handle the case when
956/// this method decides to use a different buffer.
957bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000958 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000959 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000960 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Chris Lattner141e71f2008-03-09 01:54:53 +0000962 // Make sure the filename is <x> or "x".
963 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000964 if (Buffer[0] == '<') {
965 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000966 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000967 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000968 return true;
969 }
970 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +0000971 } else if (Buffer[0] == '"') {
972 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000973 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000974 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000975 return true;
976 }
977 isAngled = false;
978 } else {
979 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000980 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000981 return true;
982 }
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Chris Lattner141e71f2008-03-09 01:54:53 +0000984 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +0000985 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000986 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000987 Buffer = llvm::StringRef();
988 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattner141e71f2008-03-09 01:54:53 +0000991 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +0000992 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +0000993 return isAngled;
994}
995
996/// ConcatenateIncludeName - Handle cases where the #include name is expanded
997/// from a macro as multiple tokens, which need to be glued together. This
998/// occurs for code like:
999/// #define FOO <a/b.h>
1000/// #include FOO
1001/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1002///
1003/// This code concatenates and consumes tokens up to the '>' token. It returns
1004/// false if the > was found, otherwise it returns true if it finds and consumes
1005/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +00001006bool Preprocessor::ConcatenateIncludeName(
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001007 llvm::SmallString<128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001008 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001009
John Thompsona28cc092009-10-30 13:49:06 +00001010 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001011 while (CurTok.isNot(tok::eom)) {
1012 // Append the spelling of this token to the buffer. If there was a space
1013 // before it, add it now.
1014 if (CurTok.hasLeadingSpace())
1015 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattner141e71f2008-03-09 01:54:53 +00001017 // Get the spelling of the token, directly into FilenameBuffer if possible.
1018 unsigned PreAppendSize = FilenameBuffer.size();
1019 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Chris Lattner141e71f2008-03-09 01:54:53 +00001021 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001022 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Chris Lattner141e71f2008-03-09 01:54:53 +00001024 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1025 if (BufPtr != &FilenameBuffer[PreAppendSize])
1026 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Chris Lattner141e71f2008-03-09 01:54:53 +00001028 // Resize FilenameBuffer to the correct size.
1029 if (CurTok.getLength() != ActualLen)
1030 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Chris Lattner141e71f2008-03-09 01:54:53 +00001032 // If we found the '>' marker, return success.
1033 if (CurTok.is(tok::greater))
1034 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
John Thompsona28cc092009-10-30 13:49:06 +00001036 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001037 }
1038
1039 // If we hit the eom marker, emit an error and return true so that the caller
1040 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001041 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001042 return true;
1043}
1044
1045/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1046/// file to be included from the lexer, then include it! This is a common
1047/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001048/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001049/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001050void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1051 const DirectoryLookup *LookupFrom,
1052 bool isImport) {
1053
1054 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001055 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Chris Lattner141e71f2008-03-09 01:54:53 +00001057 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001058 llvm::SmallString<128> FilenameBuffer;
1059 llvm::StringRef Filename;
Chris Lattner141e71f2008-03-09 01:54:53 +00001060
1061 switch (FilenameTok.getKind()) {
1062 case tok::eom:
1063 // If the token kind is EOM, the error has already been diagnosed.
1064 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Chris Lattner141e71f2008-03-09 01:54:53 +00001066 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001067 case tok::string_literal:
1068 Filename = getSpelling(FilenameTok, FilenameBuffer);
Chris Lattner141e71f2008-03-09 01:54:53 +00001069 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattner141e71f2008-03-09 01:54:53 +00001071 case tok::less:
1072 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1073 // case, glue the tokens together into FilenameBuffer and interpret those.
1074 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001075 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001076 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001077 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001078 break;
1079 default:
1080 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1081 DiscardUntilEndOfDirective();
1082 return;
1083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001085 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001086 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001087 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1088 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001089 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001090 DiscardUntilEndOfDirective();
1091 return;
1092 }
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001094 // Verify that there is nothing after the filename, other than EOM. Note that
1095 // we allow macros that expand to nothing after the filename, because this
1096 // falls into the category of "#include pp-tokens new-line" specified in
1097 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001098 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001099
1100 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001101 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1102 Diag(FilenameTok, diag::err_pp_include_too_deep);
1103 return;
1104 }
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Chris Lattner141e71f2008-03-09 01:54:53 +00001106 // Search include directories.
1107 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +00001108 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001109 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001110 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001111 return;
1112 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001113
Chris Lattner72181832008-09-26 20:12:23 +00001114 // The #included file will be considered to be a system header if either it is
1115 // in a system include directory, or if the #includer is a system include
1116 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001117 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001118 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001119 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001121 // Ask HeaderInfo if we should enter this #include file. If not, #including
1122 // this file will have no effect.
1123 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001124 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001125 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001126 return;
1127 }
1128
Chris Lattner141e71f2008-03-09 01:54:53 +00001129 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001130 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1131 FileCharacter);
1132 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001133 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001134 return;
1135 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001136
1137 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001138 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001139}
1140
1141/// HandleIncludeNextDirective - Implements #include_next.
1142///
1143void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1144 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Chris Lattner141e71f2008-03-09 01:54:53 +00001146 // #include_next is like #include, except that we start searching after
1147 // the current found directory. If we can't do this, issue a
1148 // diagnostic.
1149 const DirectoryLookup *Lookup = CurDirLookup;
1150 if (isInPrimaryFile()) {
1151 Lookup = 0;
1152 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1153 } else if (Lookup == 0) {
1154 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1155 } else {
1156 // Start looking up in the next directory.
1157 ++Lookup;
1158 }
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Chris Lattner141e71f2008-03-09 01:54:53 +00001160 return HandleIncludeDirective(IncludeNextTok, Lookup);
1161}
1162
1163/// HandleImportDirective - Implements #import.
1164///
1165void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001166 if (!Features.ObjC1) // #import is standard for ObjC.
1167 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Chris Lattner141e71f2008-03-09 01:54:53 +00001169 return HandleIncludeDirective(ImportTok, 0, true);
1170}
1171
Chris Lattnerde076652009-04-08 18:46:40 +00001172/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1173/// pseudo directive in the predefines buffer. This handles it by sucking all
1174/// tokens through the preprocessor and discarding them (only keeping the side
1175/// effects on the preprocessor).
1176void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1177 // This directive should only occur in the predefines buffer. If not, emit an
1178 // error and reject it.
1179 SourceLocation Loc = IncludeMacrosTok.getLocation();
1180 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1181 Diag(IncludeMacrosTok.getLocation(),
1182 diag::pp_include_macros_out_of_predefines);
1183 DiscardUntilEndOfDirective();
1184 return;
1185 }
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chris Lattnerfd105112009-04-08 20:53:24 +00001187 // Treat this as a normal #include for checking purposes. If this is
1188 // successful, it will push a new lexer onto the include stack.
1189 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Chris Lattnerfd105112009-04-08 20:53:24 +00001191 Token TmpTok;
1192 do {
1193 Lex(TmpTok);
1194 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1195 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001196}
1197
Chris Lattner141e71f2008-03-09 01:54:53 +00001198//===----------------------------------------------------------------------===//
1199// Preprocessor Macro Directive Handling.
1200//===----------------------------------------------------------------------===//
1201
1202/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1203/// definition has just been read. Lex the rest of the arguments and the
1204/// closing ), updating MI with what we learn. Return true if an error occurs
1205/// parsing the arg list.
1206bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1207 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Chris Lattner141e71f2008-03-09 01:54:53 +00001209 Token Tok;
1210 while (1) {
1211 LexUnexpandedToken(Tok);
1212 switch (Tok.getKind()) {
1213 case tok::r_paren:
1214 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001215 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001216 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001217 // Otherwise we have #define FOO(A,)
1218 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1219 return true;
1220 case tok::ellipsis: // #define X(... -> C99 varargs
1221 // Warn if use of C99 feature in non-C99 mode.
1222 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1223
1224 // Lex the token after the identifier.
1225 LexUnexpandedToken(Tok);
1226 if (Tok.isNot(tok::r_paren)) {
1227 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1228 return true;
1229 }
1230 // Add the __VA_ARGS__ identifier as an argument.
1231 Arguments.push_back(Ident__VA_ARGS__);
1232 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001233 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001234 return false;
1235 case tok::eom: // #define X(
1236 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1237 return true;
1238 default:
1239 // Handle keywords and identifiers here to accept things like
1240 // #define Foo(for) for.
1241 IdentifierInfo *II = Tok.getIdentifierInfo();
1242 if (II == 0) {
1243 // #define X(1
1244 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1245 return true;
1246 }
1247
1248 // If this is already used as an argument, it is used multiple times (e.g.
1249 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001250 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001251 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001252 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001253 return true;
1254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Chris Lattner141e71f2008-03-09 01:54:53 +00001256 // Add the argument to the macro info.
1257 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Chris Lattner141e71f2008-03-09 01:54:53 +00001259 // Lex the token after the identifier.
1260 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Chris Lattner141e71f2008-03-09 01:54:53 +00001262 switch (Tok.getKind()) {
1263 default: // #define X(A B
1264 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1265 return true;
1266 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001267 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001268 return false;
1269 case tok::comma: // #define X(A,
1270 break;
1271 case tok::ellipsis: // #define X(A... -> GCC extension
1272 // Diagnose extension.
1273 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Chris Lattner141e71f2008-03-09 01:54:53 +00001275 // Lex the token after the identifier.
1276 LexUnexpandedToken(Tok);
1277 if (Tok.isNot(tok::r_paren)) {
1278 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1279 return true;
1280 }
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Chris Lattner141e71f2008-03-09 01:54:53 +00001282 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001283 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001284 return false;
1285 }
1286 }
1287 }
1288}
1289
1290/// HandleDefineDirective - Implements #define. This consumes the entire macro
1291/// line then lets the caller lex the next real token.
1292void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1293 ++NumDefined;
1294
1295 Token MacroNameTok;
1296 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Chris Lattner141e71f2008-03-09 01:54:53 +00001298 // Error reading macro name? If so, diagnostic already issued.
1299 if (MacroNameTok.is(tok::eom))
1300 return;
1301
Chris Lattner2451b522009-04-21 04:46:33 +00001302 Token LastTok = MacroNameTok;
1303
Chris Lattner141e71f2008-03-09 01:54:53 +00001304 // If we are supposed to keep comments in #defines, reenable comment saving
1305 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001306 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001307
Chris Lattner141e71f2008-03-09 01:54:53 +00001308 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001309 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Chris Lattner141e71f2008-03-09 01:54:53 +00001311 Token Tok;
1312 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Chris Lattner141e71f2008-03-09 01:54:53 +00001314 // If this is a function-like macro definition, parse the argument list,
1315 // marking each of the identifiers as being used as macro arguments. Also,
1316 // check other constraints on the first token of the macro body.
1317 if (Tok.is(tok::eom)) {
1318 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001319 } else if (Tok.hasLeadingSpace()) {
1320 // This is a normal token with leading space. Clear the leading space
1321 // marker on the first token to get proper expansion.
1322 Tok.clearFlag(Token::LeadingSpace);
1323 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001324 // This is a function-like macro definition. Read the argument list.
1325 MI->setIsFunctionLike();
1326 if (ReadMacroDefinitionArgList(MI)) {
1327 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001328 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001329 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001330 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001331 DiscardUntilEndOfDirective();
1332 return;
1333 }
1334
Chris Lattner8fde5972009-04-19 18:26:34 +00001335 // If this is a definition of a variadic C99 function-like macro, not using
1336 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Chris Lattner8fde5972009-04-19 18:26:34 +00001338 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1339 // This gets unpoisoned where it is allowed.
1340 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1341 if (MI->isC99Varargs())
1342 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Chris Lattner141e71f2008-03-09 01:54:53 +00001344 // Read the first token after the arg list for down below.
1345 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001346 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001347 // C99 requires whitespace between the macro definition and the body. Emit
1348 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001349 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001350 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001351 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1352 // first character of a replacement list is not a character required by
1353 // subclause 5.2.1, then there shall be white-space separation between the
1354 // identifier and the replacement list.". 5.2.1 lists this set:
1355 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1356 // is irrelevant here.
1357 bool isInvalid = false;
1358 if (Tok.is(tok::at)) // @ is not in the list above.
1359 isInvalid = true;
1360 else if (Tok.is(tok::unknown)) {
1361 // If we have an unknown token, it is something strange like "`". Since
1362 // all of valid characters would have lexed into a single character
1363 // token of some sort, we know this is not a valid case.
1364 isInvalid = true;
1365 }
1366 if (isInvalid)
1367 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1368 else
1369 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001370 }
Chris Lattner2451b522009-04-21 04:46:33 +00001371
1372 if (!Tok.is(tok::eom))
1373 LastTok = Tok;
1374
Chris Lattner141e71f2008-03-09 01:54:53 +00001375 // Read the rest of the macro body.
1376 if (MI->isObjectLike()) {
1377 // Object-like macros are very simple, just read their body.
1378 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001379 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001380 MI->AddTokenToBody(Tok);
1381 // Get the next token of the macro.
1382 LexUnexpandedToken(Tok);
1383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Chris Lattner141e71f2008-03-09 01:54:53 +00001385 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001386 // Otherwise, read the body of a function-like macro. While we are at it,
1387 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1388 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001389 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001390 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001391
Chris Lattner141e71f2008-03-09 01:54:53 +00001392 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001393 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Chris Lattner141e71f2008-03-09 01:54:53 +00001395 // Get the next token of the macro.
1396 LexUnexpandedToken(Tok);
1397 continue;
1398 }
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Chris Lattner141e71f2008-03-09 01:54:53 +00001400 // Get the next token of the macro.
1401 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Chris Lattner32404692009-05-25 17:16:10 +00001403 // Check for a valid macro arg identifier.
1404 if (Tok.getIdentifierInfo() == 0 ||
1405 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1406
1407 // If this is assembler-with-cpp mode, we accept random gibberish after
1408 // the '#' because '#' is often a comment character. However, change
1409 // the kind of the token to tok::unknown so that the preprocessor isn't
1410 // confused.
1411 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1412 LastTok.setKind(tok::unknown);
1413 } else {
1414 Diag(Tok, diag::err_pp_stringize_not_parameter);
1415 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Chris Lattner32404692009-05-25 17:16:10 +00001417 // Disable __VA_ARGS__ again.
1418 Ident__VA_ARGS__->setIsPoisoned(true);
1419 return;
1420 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001421 }
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Chris Lattner32404692009-05-25 17:16:10 +00001423 // Things look ok, add the '#' and param name tokens to the macro.
1424 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001425 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001426 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Chris Lattner141e71f2008-03-09 01:54:53 +00001428 // Get the next token of the macro.
1429 LexUnexpandedToken(Tok);
1430 }
1431 }
Mike Stump1eb44332009-09-09 15:08:12 +00001432
1433
Chris Lattner141e71f2008-03-09 01:54:53 +00001434 // Disable __VA_ARGS__ again.
1435 Ident__VA_ARGS__->setIsPoisoned(true);
1436
1437 // Check that there is no paste (##) operator at the begining or end of the
1438 // replacement list.
1439 unsigned NumTokens = MI->getNumTokens();
1440 if (NumTokens != 0) {
1441 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1442 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001443 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001444 return;
1445 }
1446 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1447 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001448 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001449 return;
1450 }
1451 }
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Chris Lattner141e71f2008-03-09 01:54:53 +00001453 // If this is the primary source file, remember that this macro hasn't been
1454 // used yet.
1455 if (isInPrimaryFile())
1456 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001457
1458 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Chris Lattner141e71f2008-03-09 01:54:53 +00001460 // Finally, if this identifier already had a macro defined for it, verify that
1461 // the macro bodies are identical and free the old definition.
1462 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001463 // It is very common for system headers to have tons of macro redefinitions
1464 // and for warnings to be disabled in system headers. If this is the case,
1465 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001466 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001467 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1468 if (!OtherMI->isUsed())
1469 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001470
Chris Lattnerf47724b2010-08-17 15:55:45 +00001471 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001472 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001473 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001474 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001475 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1476 << MacroNameTok.getIdentifierInfo();
1477 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1478 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001479 }
Ted Kremenek0ea76722008-12-15 19:56:42 +00001480 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001481 }
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Chris Lattner141e71f2008-03-09 01:54:53 +00001483 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001485 // If the callbacks want to know, tell them about the macro definition.
1486 if (Callbacks)
1487 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001488}
1489
1490/// HandleUndefDirective - Implements #undef.
1491///
1492void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1493 ++NumUndefined;
1494
1495 Token MacroNameTok;
1496 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Chris Lattner141e71f2008-03-09 01:54:53 +00001498 // Error reading macro name? If so, diagnostic already issued.
1499 if (MacroNameTok.is(tok::eom))
1500 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Chris Lattner141e71f2008-03-09 01:54:53 +00001502 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001503 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Chris Lattner141e71f2008-03-09 01:54:53 +00001505 // Okay, we finally have a valid identifier to undef.
1506 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Chris Lattner141e71f2008-03-09 01:54:53 +00001508 // If the macro is not defined, this is a noop undef, just return.
1509 if (MI == 0) return;
1510
1511 if (!MI->isUsed())
1512 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001513
1514 // If the callbacks want to know, tell them about the macro #undef.
1515 if (Callbacks)
Benjamin Kramer2f054492010-08-07 22:27:00 +00001516 Callbacks->MacroUndefined(MacroNameTok.getLocation(),
1517 MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001518
Chris Lattner141e71f2008-03-09 01:54:53 +00001519 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001520 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001521 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1522}
1523
1524
1525//===----------------------------------------------------------------------===//
1526// Preprocessor Conditional Directive Handling.
1527//===----------------------------------------------------------------------===//
1528
1529/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1530/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1531/// if any tokens have been returned or pp-directives activated before this
1532/// #ifndef has been lexed.
1533///
1534void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1535 bool ReadAnyTokensBeforeDirective) {
1536 ++NumIf;
1537 Token DirectiveTok = Result;
1538
1539 Token MacroNameTok;
1540 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Chris Lattner141e71f2008-03-09 01:54:53 +00001542 // Error reading macro name? If so, diagnostic already issued.
1543 if (MacroNameTok.is(tok::eom)) {
1544 // Skip code until we get to #endif. This helps with recovery by not
1545 // emitting an error when the #endif is reached.
1546 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1547 /*Foundnonskip*/false, /*FoundElse*/false);
1548 return;
1549 }
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Chris Lattner141e71f2008-03-09 01:54:53 +00001551 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001552 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001553
Chris Lattner13d283d2010-02-12 08:03:27 +00001554 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1555 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001556
Ted Kremenek60e45d42008-11-18 00:34:22 +00001557 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001558 // If the start of a top-level #ifdef and if the macro is not defined,
1559 // inform MIOpt that this might be the start of a proper include guard.
1560 // Otherwise it is some other form of unknown conditional which we can't
1561 // handle.
1562 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001563 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001564 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001565 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001566 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001567 }
1568
Chris Lattner141e71f2008-03-09 01:54:53 +00001569 // If there is a macro, process it.
1570 if (MI) // Mark it used.
1571 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Chris Lattner141e71f2008-03-09 01:54:53 +00001573 // Should we include the stuff contained by this directive?
1574 if (!MI == isIfndef) {
1575 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001576 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1577 /*wasskip*/false, /*foundnonskip*/true,
1578 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001579 } else {
1580 // No, skip the contents of this block and return the first token after it.
1581 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001582 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001583 /*FoundElse*/false);
1584 }
1585}
1586
1587/// HandleIfDirective - Implements the #if directive.
1588///
1589void Preprocessor::HandleIfDirective(Token &IfToken,
1590 bool ReadAnyTokensBeforeDirective) {
1591 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Chris Lattner141e71f2008-03-09 01:54:53 +00001593 // Parse and evaluation the conditional expression.
1594 IdentifierInfo *IfNDefMacro = 0;
1595 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Nuno Lopes0049db62008-06-01 18:31:24 +00001597
1598 // If this condition is equivalent to #ifndef X, and if this is the first
1599 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001600 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001601 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001602 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001603 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001604 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001605 }
1606
Chris Lattner141e71f2008-03-09 01:54:53 +00001607 // Should we include the stuff contained by this directive?
1608 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001609 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001610 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001611 /*foundnonskip*/true, /*foundelse*/false);
1612 } else {
1613 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001614 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001615 /*FoundElse*/false);
1616 }
1617}
1618
1619/// HandleEndifDirective - Implements the #endif directive.
1620///
1621void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1622 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Chris Lattner141e71f2008-03-09 01:54:53 +00001624 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001625 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Chris Lattner141e71f2008-03-09 01:54:53 +00001627 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001628 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001629 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001630 Diag(EndifToken, diag::err_pp_endif_without_if);
1631 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001632 }
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Chris Lattner141e71f2008-03-09 01:54:53 +00001634 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001635 if (CurPPLexer->getConditionalStackDepth() == 0)
1636 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Ted Kremenek60e45d42008-11-18 00:34:22 +00001638 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001639 "This code should only be reachable in the non-skipping case!");
1640}
1641
1642
1643void Preprocessor::HandleElseDirective(Token &Result) {
1644 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Chris Lattner141e71f2008-03-09 01:54:53 +00001646 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001647 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Chris Lattner141e71f2008-03-09 01:54:53 +00001649 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001650 if (CurPPLexer->popConditionalLevel(CI)) {
1651 Diag(Result, diag::pp_err_else_without_if);
1652 return;
1653 }
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Chris Lattner141e71f2008-03-09 01:54:53 +00001655 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001656 if (CurPPLexer->getConditionalStackDepth() == 0)
1657 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001658
1659 // If this is a #else with a #else before it, report the error.
1660 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Chris Lattner141e71f2008-03-09 01:54:53 +00001662 // Finally, skip the rest of the contents of this block and return the first
1663 // token after it.
1664 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1665 /*FoundElse*/true);
1666}
1667
1668void Preprocessor::HandleElifDirective(Token &ElifToken) {
1669 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Chris Lattner141e71f2008-03-09 01:54:53 +00001671 // #elif directive in a non-skipping conditional... start skipping.
1672 // We don't care what the condition is, because we will always skip it (since
1673 // the block immediately before it was included).
1674 DiscardUntilEndOfDirective();
1675
1676 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001677 if (CurPPLexer->popConditionalLevel(CI)) {
1678 Diag(ElifToken, diag::pp_err_elif_without_if);
1679 return;
1680 }
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Chris Lattner141e71f2008-03-09 01:54:53 +00001682 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001683 if (CurPPLexer->getConditionalStackDepth() == 0)
1684 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Chris Lattner141e71f2008-03-09 01:54:53 +00001686 // If this is a #elif with a #else before it, report the error.
1687 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1688
1689 // Finally, skip the rest of the contents of this block and return the first
1690 // token after it.
1691 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1692 /*FoundElse*/CI.FoundElse);
1693}