blob: ffdc6ae5894e67023193f3cdfa0556ce5a5a3325 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Chris Lattner359cc442009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf44e8542010-08-24 19:08:16 +000019#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor80c60f72010-09-09 22:45:38 +000020#include "clang/Lex/Pragma.h"
Chris Lattner6e290142009-11-30 04:18:44 +000021#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000023#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000024using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Utility Methods for Preprocessor Directive Handling.
28//===----------------------------------------------------------------------===//
29
Chris Lattnerf47724b2010-08-17 15:55:45 +000030MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenek0ea76722008-12-15 19:56:42 +000031 MacroInfo *MI;
Mike Stump1eb44332009-09-09 15:08:12 +000032
Ted Kremenek0ea76722008-12-15 19:56:42 +000033 if (!MICache.empty()) {
34 MI = MICache.back();
35 MICache.pop_back();
Ted Kremenekaf8fa252010-10-19 18:16:54 +000036 } else {
37 MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>();
38 MIChain->Next = MIChainHead;
39 MIChainHead = MIChain;
40 MI = &(MIChainHead->MI);
41 }
Chris Lattnerf47724b2010-08-17 15:55:45 +000042 return MI;
43}
44
45MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
46 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000047 new (MI) MacroInfo(L);
48 return MI;
49}
50
Chris Lattnerf47724b2010-08-17 15:55:45 +000051MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
52 MacroInfo *MI = AllocateMacroInfo();
53 new (MI) MacroInfo(MacroToClone, BP);
54 return MI;
55}
56
Chris Lattner0301b3f2009-02-20 22:19:20 +000057/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
58/// be reused for allocating new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000059void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Chris Lattner0301b3f2009-02-20 22:19:20 +000060 MICache.push_back(MI);
Chris Lattner2c1ab902010-08-18 16:08:51 +000061 MI->FreeArgumentList();
Chris Lattner0301b3f2009-02-20 22:19:20 +000062}
63
64
Chris Lattner141e71f2008-03-09 01:54:53 +000065/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
66/// current line until the tok::eom token is found.
67void Preprocessor::DiscardUntilEndOfDirective() {
68 Token Tmp;
69 do {
70 LexUnexpandedToken(Tmp);
71 } while (Tmp.isNot(tok::eom));
72}
73
Chris Lattner141e71f2008-03-09 01:54:53 +000074/// ReadMacroName - Lex and validate a macro name, which occurs after a
75/// #define or #undef. This sets the token kind to eom and discards the rest
76/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
77/// this is due to a a #define, 2 if #undef directive, 0 if it is something
78/// else (e.g. #ifdef).
79void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
80 // Read the token, don't allow macro expansion on it.
81 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +000082
Douglas Gregor1fbb4472010-08-24 20:21:13 +000083 if (MacroNameTok.is(tok::code_completion)) {
84 if (CodeComplete)
85 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
86 LexUnexpandedToken(MacroNameTok);
87 return;
88 }
89
Chris Lattner141e71f2008-03-09 01:54:53 +000090 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000091 if (MacroNameTok.is(tok::eom)) {
92 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
93 return;
94 }
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattner141e71f2008-03-09 01:54:53 +000096 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
97 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +000098 bool Invalid = false;
99 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
100 if (Invalid)
101 return;
102
Chris Lattner9485d232008-12-13 20:12:40 +0000103 const IdentifierInfo &Info = Identifiers.get(Spelling);
104 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000105 // C++ 2.5p2: Alternative tokens behave the same as its primary token
106 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000107 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +0000108 else
109 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
110 // Fall through on error.
111 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
112 // Error if defining "defined": C99 6.10.8.4.
113 Diag(MacroNameTok, diag::err_defined_macro_name);
114 } else if (isDefineUndef && II->hasMacroDefinition() &&
115 getMacroInfo(II)->isBuiltinMacro()) {
116 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
117 if (isDefineUndef == 1)
118 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
119 else
120 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
121 } else {
122 // Okay, we got a good identifier node. Return it.
123 return;
124 }
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Chris Lattner141e71f2008-03-09 01:54:53 +0000126 // Invalid macro name, read and discard the rest of the line. Then set the
127 // token kind to tok::eom.
128 MacroNameTok.setKind(tok::eom);
129 return DiscardUntilEndOfDirective();
130}
131
132/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattnerab82f412009-04-17 23:30:53 +0000133/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
134/// true, then we consider macros that expand to zero tokens as being ok.
135void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000136 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000137 // Lex unexpanded tokens for most directives: macros might expand to zero
138 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
139 // #line) allow empty macros.
140 if (EnableMacros)
141 Lex(Tmp);
142 else
143 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Chris Lattner141e71f2008-03-09 01:54:53 +0000145 // There should be no tokens after the directive, but we allow them as an
146 // extension.
147 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
148 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Chris Lattner141e71f2008-03-09 01:54:53 +0000150 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000151 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
152 // because it is more trouble than it is worth to insert /**/ and check that
153 // there is no /**/ in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000154 FixItHint Hint;
Chris Lattner959875a2009-04-14 05:15:20 +0000155 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
Douglas Gregor849b2432010-03-31 17:46:05 +0000156 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
157 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000158 DiscardUntilEndOfDirective();
159 }
160}
161
162
163
164/// SkipExcludedConditionalBlock - We just read a #if or related directive and
165/// decided that the subsequent tokens are in the #if'd out portion of the
166/// file. Lex the rest of the file, until we see an #endif. If
167/// FoundNonSkipPortion is true, then we have already emitted code for part of
168/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
169/// is true, then #else directives are ok, if not, then we have already seen one
170/// so a #else directive is a duplicate. When this returns, the caller can lex
171/// the first valid token.
172void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
173 bool FoundNonSkipPortion,
174 bool FoundElse) {
175 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000176 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000177
Ted Kremenek60e45d42008-11-18 00:34:22 +0000178 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000179 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Ted Kremenek268ee702008-12-12 18:34:08 +0000181 if (CurPTHLexer) {
182 PTHSkipExcludedConditionalBlock();
183 return;
184 }
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattner141e71f2008-03-09 01:54:53 +0000186 // Enter raw mode to disable identifier lookup (and thus macro expansion),
187 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000188 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000189 Token Tok;
190 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000191 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Douglas Gregorf44e8542010-08-24 19:08:16 +0000193 if (Tok.is(tok::code_completion)) {
194 if (CodeComplete)
195 CodeComplete->CodeCompleteInConditionalExclusion();
196 continue;
197 }
198
Chris Lattner141e71f2008-03-09 01:54:53 +0000199 // If this is the end of the buffer, we have an error.
200 if (Tok.is(tok::eof)) {
201 // Emit errors for each unterminated conditional on the stack, including
202 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000203 while (!CurPPLexer->ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000204 if (!isCodeCompletionFile(Tok.getLocation()))
205 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
206 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000207 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000208 }
209
Chris Lattner141e71f2008-03-09 01:54:53 +0000210 // Just return and let the caller lex after this #include.
211 break;
212 }
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Chris Lattner141e71f2008-03-09 01:54:53 +0000214 // If this token is not a preprocessor directive, just skip it.
215 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
216 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Chris Lattner141e71f2008-03-09 01:54:53 +0000218 // We just parsed a # character at the start of a line, so we're in
219 // directive mode. Tell the lexer this so any newlines we see will be
220 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000221 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000222 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000223
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattner141e71f2008-03-09 01:54:53 +0000225 // Read the next token, the directive flavor.
226 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattner141e71f2008-03-09 01:54:53 +0000228 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
229 // something bogus), skip it.
230 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000231 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000232 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000233 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000234 continue;
235 }
236
237 // If the first letter isn't i or e, it isn't intesting to us. We know that
238 // this is safe in the face of spelling differences, because there is no way
239 // to spell an i/e in a strange way that is another letter. Skipping this
240 // allows us to avoid looking up the identifier info for #define/#undef and
241 // other common directives.
Douglas Gregora5430162010-03-16 20:46:42 +0000242 bool Invalid = false;
243 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation(),
244 &Invalid);
245 if (Invalid)
246 return;
247
Chris Lattner141e71f2008-03-09 01:54:53 +0000248 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000249 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000250 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000251 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000252 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000253 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000254 continue;
255 }
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Chris Lattner141e71f2008-03-09 01:54:53 +0000257 // Get the identifier name without trigraphs or embedded newlines. Note
258 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
259 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000260 char DirectiveBuf[20];
261 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000262 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000263 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000264 } else {
265 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000266 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000267 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000268 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000269 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000270 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000271 continue;
272 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000273 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
274 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000275 }
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000277 if (Directive.startswith("if")) {
278 llvm::StringRef Sub = Directive.substr(2);
279 if (Sub.empty() || // "if"
280 Sub == "def" || // "ifdef"
281 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000282 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
283 // bother parsing the condition.
284 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000285 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000286 /*foundnonskip*/false,
287 /*fnddelse*/false);
288 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000289 } else if (Directive[0] == 'e') {
290 llvm::StringRef Sub = Directive.substr(1);
291 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000292 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000293 PPConditionalInfo CondInfo;
294 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000295 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000296 InCond = InCond; // Silence warning in no-asserts mode.
297 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattner141e71f2008-03-09 01:54:53 +0000299 // If we popped the outermost skipping block, we're done skipping!
300 if (!CondInfo.WasSkipping)
301 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000302 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 // #else directive in a skipping conditional. If not in some other
304 // skipping conditional, and if #else hasn't already been seen, enter it
305 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000306 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000307 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattner141e71f2008-03-09 01:54:53 +0000309 // If this is a #else with a #else before it, report the error.
310 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattner141e71f2008-03-09 01:54:53 +0000312 // Note that we've seen a #else in this conditional.
313 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Chris Lattner141e71f2008-03-09 01:54:53 +0000315 // If the conditional is at the top level, and the #if block wasn't
316 // entered, enter the #else block now.
317 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
318 CondInfo.FoundNonSkip = true;
319 break;
320 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000321 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000322 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000323
324 bool ShouldEnter;
325 // If this is in a skipping block or if we're already handled this #if
326 // block, don't bother parsing the condition.
327 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
328 DiscardUntilEndOfDirective();
329 ShouldEnter = false;
330 } else {
331 // Restore the value of LexingRawMode so that identifiers are
332 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000333 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
334 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000335 IdentifierInfo *IfNDefMacro = 0;
336 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000337 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000338 }
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Chris Lattner141e71f2008-03-09 01:54:53 +0000340 // If this is a #elif with a #else before it, report the error.
341 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Chris Lattner141e71f2008-03-09 01:54:53 +0000343 // If this condition is true, enter it!
344 if (ShouldEnter) {
345 CondInfo.FoundNonSkip = true;
346 break;
347 }
348 }
349 }
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Ted Kremenek60e45d42008-11-18 00:34:22 +0000351 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000352 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000353 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000354 }
355
356 // Finally, if we are out of the conditional (saw an #endif or ran off the end
357 // of the file, just stop skipping and return to lexing whatever came after
358 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000359 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000360}
361
Ted Kremenek268ee702008-12-12 18:34:08 +0000362void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000363
364 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000365 assert(CurPTHLexer);
366 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Ted Kremenek268ee702008-12-12 18:34:08 +0000368 // Skip to the next '#else', '#elif', or #endif.
369 if (CurPTHLexer->SkipBlock()) {
370 // We have reached an #endif. Both the '#' and 'endif' tokens
371 // have been consumed by the PTHLexer. Just pop off the condition level.
372 PPConditionalInfo CondInfo;
373 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
374 InCond = InCond; // Silence warning in no-asserts mode.
375 assert(!InCond && "Can't be skipping if not in a conditional!");
376 break;
377 }
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Ted Kremenek268ee702008-12-12 18:34:08 +0000379 // We have reached a '#else' or '#elif'. Lex the next token to get
380 // the directive flavor.
381 Token Tok;
382 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Ted Kremenek268ee702008-12-12 18:34:08 +0000384 // We can actually look up the IdentifierInfo here since we aren't in
385 // raw mode.
386 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
387
388 if (K == tok::pp_else) {
389 // #else: Enter the else condition. We aren't in a nested condition
390 // since we skip those. We're always in the one matching the last
391 // blocked we skipped.
392 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
393 // Note that we've seen a #else in this conditional.
394 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Ted Kremenek268ee702008-12-12 18:34:08 +0000396 // If the #if block wasn't entered then enter the #else block now.
397 if (!CondInfo.FoundNonSkip) {
398 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000400 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000401 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000402 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000403 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Ted Kremenek268ee702008-12-12 18:34:08 +0000405 break;
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Ted Kremenek268ee702008-12-12 18:34:08 +0000408 // Otherwise skip this block.
409 continue;
410 }
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Ted Kremenek268ee702008-12-12 18:34:08 +0000412 assert(K == tok::pp_elif);
413 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
414
415 // If this is a #elif with a #else before it, report the error.
416 if (CondInfo.FoundElse)
417 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Ted Kremenek268ee702008-12-12 18:34:08 +0000419 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000420 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000421 if (CondInfo.FoundNonSkip)
422 continue;
423
424 // Evaluate the condition of the #elif.
425 IdentifierInfo *IfNDefMacro = 0;
426 CurPTHLexer->ParsingPreprocessorDirective = true;
427 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
428 CurPTHLexer->ParsingPreprocessorDirective = false;
429
430 // If this condition is true, enter it!
431 if (ShouldEnter) {
432 CondInfo.FoundNonSkip = true;
433 break;
434 }
435
436 // Otherwise, skip this block and go to the next one.
437 continue;
438 }
439}
440
Chris Lattner10725092008-03-09 04:17:44 +0000441/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
442/// return null on failure. isAngled indicates whether the file reference is
443/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnera1394812010-01-10 01:35:12 +0000444const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattner10725092008-03-09 04:17:44 +0000445 bool isAngled,
446 const DirectoryLookup *FromDir,
447 const DirectoryLookup *&CurDir) {
448 // If the header lookup mechanism may be relative to the current file, pass in
449 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000450 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000451 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000452 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000453 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000455 // If there is no file entry associated with this file, it must be the
456 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000457 // it won't be scanned for preprocessor directives. If we have the
458 // predefines buffer, resolve #include references (which come from the
459 // -include command line argument) as if they came from the main file, this
460 // affects file lookup etc.
461 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000462 FID = SourceMgr.getMainFileID();
463 CurFileEnt = SourceMgr.getFileEntryForID(FID);
464 }
Chris Lattner10725092008-03-09 04:17:44 +0000465 }
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Chris Lattner10725092008-03-09 04:17:44 +0000467 // Do a standard file entry lookup.
468 CurDir = CurDirLookup;
469 const FileEntry *FE =
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000470 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000471 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Chris Lattner10725092008-03-09 04:17:44 +0000473 // Otherwise, see if this is a subframework header. If so, this is relative
474 // to one of the headers on the #include stack. Walk the list of the current
475 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000476 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000477 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000478 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000479 return FE;
480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Chris Lattner10725092008-03-09 04:17:44 +0000482 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
483 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000484 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000485 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000486 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000487 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000488 return FE;
489 }
490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Chris Lattner10725092008-03-09 04:17:44 +0000492 // Otherwise, we really couldn't find the file.
493 return 0;
494}
495
Chris Lattner141e71f2008-03-09 01:54:53 +0000496
497//===----------------------------------------------------------------------===//
498// Preprocessor Directive Handling.
499//===----------------------------------------------------------------------===//
500
501/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000502/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000503/// lexer/preprocessor state, and advances the lexer(s) so that the next token
504/// read is the correct one.
505void Preprocessor::HandleDirective(Token &Result) {
506 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Chris Lattner141e71f2008-03-09 01:54:53 +0000508 // We just parsed a # character at the start of a line, so we're in directive
509 // mode. Tell the lexer this so any newlines we see will be converted into an
510 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000511 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattner141e71f2008-03-09 01:54:53 +0000513 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000514
Chris Lattner141e71f2008-03-09 01:54:53 +0000515 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000516 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000517 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000518 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Chris Lattner42aa16c2009-03-18 21:00:25 +0000520 // Save the '#' token in case we need to return it later.
521 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattner141e71f2008-03-09 01:54:53 +0000523 // Read the next token, the directive flavor. This isn't expanded due to
524 // C99 6.10.3p8.
525 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner141e71f2008-03-09 01:54:53 +0000527 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
528 // #define A(x) #x
529 // A(abc
530 // #warning blah
531 // def)
532 // If so, the user is relying on non-portable behavior, emit a diagnostic.
533 if (InMacroArgs)
534 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Chris Lattner141e71f2008-03-09 01:54:53 +0000536TryAgain:
537 switch (Result.getKind()) {
538 case tok::eom:
539 return; // null directive.
540 case tok::comment:
541 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
542 LexUnexpandedToken(Result);
543 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000544 case tok::code_completion:
545 if (CodeComplete)
546 CodeComplete->CodeCompleteDirective(
547 CurPPLexer->getConditionalStackDepth() > 0);
548 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000549 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000550 if (getLangOptions().AsmPreprocessor)
551 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000552 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000553 default:
554 IdentifierInfo *II = Result.getIdentifierInfo();
555 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Chris Lattner141e71f2008-03-09 01:54:53 +0000557 // Ask what the preprocessor keyword ID is.
558 switch (II->getPPKeywordID()) {
559 default: break;
560 // C99 6.10.1 - Conditional Inclusion.
561 case tok::pp_if:
562 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
563 case tok::pp_ifdef:
564 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
565 case tok::pp_ifndef:
566 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
567 case tok::pp_elif:
568 return HandleElifDirective(Result);
569 case tok::pp_else:
570 return HandleElseDirective(Result);
571 case tok::pp_endif:
572 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Chris Lattner141e71f2008-03-09 01:54:53 +0000574 // C99 6.10.2 - Source File Inclusion.
575 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000576 return HandleIncludeDirective(Result); // Handle #include.
577 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000578 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Chris Lattner141e71f2008-03-09 01:54:53 +0000580 // C99 6.10.3 - Macro Replacement.
581 case tok::pp_define:
582 return HandleDefineDirective(Result);
583 case tok::pp_undef:
584 return HandleUndefDirective(Result);
585
586 // C99 6.10.4 - Line Control.
587 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000588 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattner141e71f2008-03-09 01:54:53 +0000590 // C99 6.10.5 - Error Directive.
591 case tok::pp_error:
592 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Chris Lattner141e71f2008-03-09 01:54:53 +0000594 // C99 6.10.6 - Pragma Directive.
595 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000596 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Chris Lattner141e71f2008-03-09 01:54:53 +0000598 // GNU Extensions.
599 case tok::pp_import:
600 return HandleImportDirective(Result);
601 case tok::pp_include_next:
602 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Chris Lattner141e71f2008-03-09 01:54:53 +0000604 case tok::pp_warning:
605 Diag(Result, diag::ext_pp_warning_directive);
606 return HandleUserDiagnosticDirective(Result, true);
607 case tok::pp_ident:
608 return HandleIdentSCCSDirective(Result);
609 case tok::pp_sccs:
610 return HandleIdentSCCSDirective(Result);
611 case tok::pp_assert:
612 //isExtension = true; // FIXME: implement #assert
613 break;
614 case tok::pp_unassert:
615 //isExtension = true; // FIXME: implement #unassert
616 break;
617 }
618 break;
619 }
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattner42aa16c2009-03-18 21:00:25 +0000621 // If this is a .S file, treat unknown # directives as non-preprocessor
622 // directives. This is important because # may be a comment or introduce
623 // various pseudo-ops. Just return the # token and push back the following
624 // token to be lexed next time.
625 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000626 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000627 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000628 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000629 Toks[1] = Result;
630 // Enter this token stream so that we re-lex the tokens. Make sure to
631 // enable macro expansion, in case the token after the # is an identifier
632 // that is expanded.
633 EnterTokenStream(Toks, 2, false, true);
634 return;
635 }
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Chris Lattner141e71f2008-03-09 01:54:53 +0000637 // If we reached here, the preprocessing token is not valid!
638 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Chris Lattner141e71f2008-03-09 01:54:53 +0000640 // Read the rest of the PP line.
641 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Chris Lattner141e71f2008-03-09 01:54:53 +0000643 // Okay, we're done parsing the directive.
644}
645
Chris Lattner478a18e2009-01-26 06:19:46 +0000646/// GetLineValue - Convert a numeric token into an unsigned value, emitting
647/// Diagnostic DiagID if it is invalid, and returning the value in Val.
648static bool GetLineValue(Token &DigitTok, unsigned &Val,
649 unsigned DiagID, Preprocessor &PP) {
650 if (DigitTok.isNot(tok::numeric_constant)) {
651 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Chris Lattner478a18e2009-01-26 06:19:46 +0000653 if (DigitTok.isNot(tok::eom))
654 PP.DiscardUntilEndOfDirective();
655 return true;
656 }
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattner478a18e2009-01-26 06:19:46 +0000658 llvm::SmallString<64> IntegerBuffer;
659 IntegerBuffer.resize(DigitTok.getLength());
660 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000661 bool Invalid = false;
662 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
663 if (Invalid)
664 return true;
665
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000666 // Verify that we have a simple digit-sequence, and compute the value. This
667 // is always a simple digit string computed in decimal, so we do this manually
668 // here.
669 Val = 0;
670 for (unsigned i = 0; i != ActualLength; ++i) {
671 if (!isdigit(DigitTokBegin[i])) {
672 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
673 diag::err_pp_line_digit_sequence);
674 PP.DiscardUntilEndOfDirective();
675 return true;
676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000678 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
679 if (NextVal < Val) { // overflow.
680 PP.Diag(DigitTok, DiagID);
681 PP.DiscardUntilEndOfDirective();
682 return true;
683 }
684 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000685 }
Mike Stump1eb44332009-09-09 15:08:12 +0000686
687 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000688 if (Val == 0) {
689 PP.Diag(DigitTok, DiagID);
690 PP.DiscardUntilEndOfDirective();
691 return true;
692 }
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000694 if (DigitTokBegin[0] == '0')
695 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattner478a18e2009-01-26 06:19:46 +0000697 return false;
698}
699
Mike Stump1eb44332009-09-09 15:08:12 +0000700/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000701/// acceptable forms are:
702/// # line digit-sequence
703/// # line digit-sequence "s-char-sequence"
704void Preprocessor::HandleLineDirective(Token &Tok) {
705 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
706 // expanded.
707 Token DigitTok;
708 Lex(DigitTok);
709
Chris Lattner359cc442009-01-26 05:29:08 +0000710 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000711 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000712 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000713 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000714
Chris Lattner478a18e2009-01-26 06:19:46 +0000715 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
716 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000717 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
718 if (LineNo >= LineLimit)
719 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Chris Lattner5b9a5042009-01-26 07:57:50 +0000721 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000722 Token StrTok;
723 Lex(StrTok);
724
725 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
726 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000727 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000728 ; // ok
729 else if (StrTok.isNot(tok::string_literal)) {
730 Diag(StrTok, diag::err_pp_line_invalid_filename);
731 DiscardUntilEndOfDirective();
732 return;
733 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000734 // Parse and validate the string, converting it into a unique ID.
735 StringLiteralParser Literal(&StrTok, 1, *this);
736 assert(!Literal.AnyWide && "Didn't allow wide strings in");
737 if (Literal.hadError)
738 return DiscardUntilEndOfDirective();
739 if (Literal.Pascal) {
740 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
741 return DiscardUntilEndOfDirective();
742 }
743 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
744 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Chris Lattnerab82f412009-04-17 23:30:53 +0000746 // Verify that there is nothing after the string, other than EOM. Because
747 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
748 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000749 }
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Chris Lattner4c4ea172009-02-03 21:52:55 +0000751 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Chris Lattner16629382009-03-27 17:13:49 +0000753 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000754 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
755 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000756 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000757}
758
Chris Lattner478a18e2009-01-26 06:19:46 +0000759/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
760/// marker directive.
761static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
762 bool &IsSystemHeader, bool &IsExternCHeader,
763 Preprocessor &PP) {
764 unsigned FlagVal;
765 Token FlagTok;
766 PP.Lex(FlagTok);
767 if (FlagTok.is(tok::eom)) return false;
768 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
769 return true;
770
771 if (FlagVal == 1) {
772 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Chris Lattner478a18e2009-01-26 06:19:46 +0000774 PP.Lex(FlagTok);
775 if (FlagTok.is(tok::eom)) return false;
776 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
777 return true;
778 } else if (FlagVal == 2) {
779 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Chris Lattner137b6a62009-02-04 06:25:26 +0000781 SourceManager &SM = PP.getSourceManager();
782 // If we are leaving the current presumed file, check to make sure the
783 // presumed include stack isn't empty!
784 FileID CurFileID =
785 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
786 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Chris Lattner137b6a62009-02-04 06:25:26 +0000788 // If there is no include loc (main file) or if the include loc is in a
789 // different physical file, then we aren't in a "1" line marker flag region.
790 SourceLocation IncLoc = PLoc.getIncludeLoc();
791 if (IncLoc.isInvalid() ||
792 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
793 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
794 PP.DiscardUntilEndOfDirective();
795 return true;
796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattner478a18e2009-01-26 06:19:46 +0000798 PP.Lex(FlagTok);
799 if (FlagTok.is(tok::eom)) return false;
800 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
801 return true;
802 }
803
804 // We must have 3 if there are still flags.
805 if (FlagVal != 3) {
806 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000807 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000808 return true;
809 }
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Chris Lattner478a18e2009-01-26 06:19:46 +0000811 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Chris Lattner478a18e2009-01-26 06:19:46 +0000813 PP.Lex(FlagTok);
814 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000815 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000816 return true;
817
818 // We must have 4 if there is yet another flag.
819 if (FlagVal != 4) {
820 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000821 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000822 return true;
823 }
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Chris Lattner478a18e2009-01-26 06:19:46 +0000825 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Chris Lattner478a18e2009-01-26 06:19:46 +0000827 PP.Lex(FlagTok);
828 if (FlagTok.is(tok::eom)) return false;
829
830 // There are no more valid flags here.
831 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000832 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000833 return true;
834}
835
836/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
837/// one of the following forms:
838///
839/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000840/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000841/// # 42 "file" ('1' | '2')? '3' '4'?
842///
843void Preprocessor::HandleDigitDirective(Token &DigitTok) {
844 // Validate the number and convert it to an unsigned. GNU does not have a
845 // line # limit other than it fit in 32-bits.
846 unsigned LineNo;
847 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
848 *this))
849 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Chris Lattner478a18e2009-01-26 06:19:46 +0000851 Token StrTok;
852 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Chris Lattner478a18e2009-01-26 06:19:46 +0000854 bool IsFileEntry = false, IsFileExit = false;
855 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000856 int FilenameID = -1;
857
Chris Lattner478a18e2009-01-26 06:19:46 +0000858 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
859 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000860 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000861 ; // ok
862 else if (StrTok.isNot(tok::string_literal)) {
863 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000864 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000865 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000866 // Parse and validate the string, converting it into a unique ID.
867 StringLiteralParser Literal(&StrTok, 1, *this);
868 assert(!Literal.AnyWide && "Didn't allow wide strings in");
869 if (Literal.hadError)
870 return DiscardUntilEndOfDirective();
871 if (Literal.Pascal) {
872 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
873 return DiscardUntilEndOfDirective();
874 }
875 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
876 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Chris Lattner478a18e2009-01-26 06:19:46 +0000878 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000879 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000880 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000881 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000882 }
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattner9d79eba2009-02-04 05:21:58 +0000884 // Create a line note with this information.
885 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000886 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000887 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Chris Lattner16629382009-03-27 17:13:49 +0000889 // If the preprocessor has callbacks installed, notify them of the #line
890 // change. This is used so that the line marker comes out in -E mode for
891 // example.
892 if (Callbacks) {
893 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
894 if (IsFileEntry)
895 Reason = PPCallbacks::EnterFile;
896 else if (IsFileExit)
897 Reason = PPCallbacks::ExitFile;
898 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
899 if (IsExternCHeader)
900 FileKind = SrcMgr::C_ExternCSystem;
901 else if (IsSystemHeader)
902 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner86d0ef72010-04-14 04:28:50 +0000904 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000905 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000906}
907
908
Chris Lattner099dd052009-01-26 05:30:54 +0000909/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
910///
Mike Stump1eb44332009-09-09 15:08:12 +0000911void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000912 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000913 // PTH doesn't emit #warning or #error directives.
914 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000915 return CurPTHLexer->DiscardToEndOfLine();
916
Chris Lattner141e71f2008-03-09 01:54:53 +0000917 // Read the rest of the line raw. We do this because we don't want macros
918 // to be expanded and we don't require that the tokens be valid preprocessing
919 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
920 // collapse multiple consequtive white space between tokens, but this isn't
921 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000922 std::string Message = CurLexer->ReadToEndOfLine();
923 if (isWarning)
924 Diag(Tok, diag::pp_hash_warning) << Message;
925 else
926 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000927}
928
929/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
930///
931void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
932 // Yes, this directive is an extension.
933 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattner141e71f2008-03-09 01:54:53 +0000935 // Read the string argument.
936 Token StrTok;
937 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner141e71f2008-03-09 01:54:53 +0000939 // If the token kind isn't a string, it's a malformed directive.
940 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000941 StrTok.isNot(tok::wide_string_literal)) {
942 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000943 if (StrTok.isNot(tok::eom))
944 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000945 return;
946 }
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Chris Lattner141e71f2008-03-09 01:54:53 +0000948 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000949 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000950
Douglas Gregor453091c2010-03-16 22:30:13 +0000951 if (Callbacks) {
952 bool Invalid = false;
953 std::string Str = getSpelling(StrTok, &Invalid);
954 if (!Invalid)
955 Callbacks->Ident(Tok.getLocation(), Str);
956 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000957}
958
959//===----------------------------------------------------------------------===//
960// Preprocessor Include Directive Handling.
961//===----------------------------------------------------------------------===//
962
963/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
964/// checked and spelled filename, e.g. as an operand of #include. This returns
965/// true if the input filename was in <>'s or false if it were in ""'s. The
966/// caller is expected to provide a buffer that is large enough to hold the
967/// spelling of the filename, but is also expected to handle the case when
968/// this method decides to use a different buffer.
969bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000970 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000971 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000972 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Chris Lattner141e71f2008-03-09 01:54:53 +0000974 // Make sure the filename is <x> or "x".
975 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000976 if (Buffer[0] == '<') {
977 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000978 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000979 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000980 return true;
981 }
982 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +0000983 } else if (Buffer[0] == '"') {
984 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000985 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000986 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000987 return true;
988 }
989 isAngled = false;
990 } else {
991 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000992 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000993 return true;
994 }
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Chris Lattner141e71f2008-03-09 01:54:53 +0000996 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +0000997 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000998 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000999 Buffer = llvm::StringRef();
1000 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001001 }
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Chris Lattner141e71f2008-03-09 01:54:53 +00001003 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001004 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001005 return isAngled;
1006}
1007
1008/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1009/// from a macro as multiple tokens, which need to be glued together. This
1010/// occurs for code like:
1011/// #define FOO <a/b.h>
1012/// #include FOO
1013/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1014///
1015/// This code concatenates and consumes tokens up to the '>' token. It returns
1016/// false if the > was found, otherwise it returns true if it finds and consumes
1017/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +00001018bool Preprocessor::ConcatenateIncludeName(
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001019 llvm::SmallString<128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001020 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001021
John Thompsona28cc092009-10-30 13:49:06 +00001022 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001023 while (CurTok.isNot(tok::eom)) {
1024 // Append the spelling of this token to the buffer. If there was a space
1025 // before it, add it now.
1026 if (CurTok.hasLeadingSpace())
1027 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Chris Lattner141e71f2008-03-09 01:54:53 +00001029 // Get the spelling of the token, directly into FilenameBuffer if possible.
1030 unsigned PreAppendSize = FilenameBuffer.size();
1031 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Chris Lattner141e71f2008-03-09 01:54:53 +00001033 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001034 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Chris Lattner141e71f2008-03-09 01:54:53 +00001036 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1037 if (BufPtr != &FilenameBuffer[PreAppendSize])
1038 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner141e71f2008-03-09 01:54:53 +00001040 // Resize FilenameBuffer to the correct size.
1041 if (CurTok.getLength() != ActualLen)
1042 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Chris Lattner141e71f2008-03-09 01:54:53 +00001044 // If we found the '>' marker, return success.
1045 if (CurTok.is(tok::greater))
1046 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001047
John Thompsona28cc092009-10-30 13:49:06 +00001048 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001049 }
1050
1051 // If we hit the eom marker, emit an error and return true so that the caller
1052 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001053 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001054 return true;
1055}
1056
1057/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1058/// file to be included from the lexer, then include it! This is a common
1059/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001060/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001061/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001062void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1063 const DirectoryLookup *LookupFrom,
1064 bool isImport) {
1065
1066 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001067 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Chris Lattner141e71f2008-03-09 01:54:53 +00001069 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001070 llvm::SmallString<128> FilenameBuffer;
1071 llvm::StringRef Filename;
Chris Lattner141e71f2008-03-09 01:54:53 +00001072
1073 switch (FilenameTok.getKind()) {
1074 case tok::eom:
1075 // If the token kind is EOM, the error has already been diagnosed.
1076 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Chris Lattner141e71f2008-03-09 01:54:53 +00001078 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001079 case tok::string_literal:
1080 Filename = getSpelling(FilenameTok, FilenameBuffer);
Chris Lattner141e71f2008-03-09 01:54:53 +00001081 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Chris Lattner141e71f2008-03-09 01:54:53 +00001083 case tok::less:
1084 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1085 // case, glue the tokens together into FilenameBuffer and interpret those.
1086 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001087 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001088 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001089 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001090 break;
1091 default:
1092 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1093 DiscardUntilEndOfDirective();
1094 return;
1095 }
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001097 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001098 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001099 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1100 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001101 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001102 DiscardUntilEndOfDirective();
1103 return;
1104 }
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001106 // Verify that there is nothing after the filename, other than EOM. Note that
1107 // we allow macros that expand to nothing after the filename, because this
1108 // falls into the category of "#include pp-tokens new-line" specified in
1109 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001110 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001111
1112 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001113 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1114 Diag(FilenameTok, diag::err_pp_include_too_deep);
1115 return;
1116 }
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Chris Lattner141e71f2008-03-09 01:54:53 +00001118 // Search include directories.
1119 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +00001120 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001121 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001122 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001123 return;
1124 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001125
Chris Lattner72181832008-09-26 20:12:23 +00001126 // The #included file will be considered to be a system header if either it is
1127 // in a system include directory, or if the #includer is a system include
1128 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001129 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001130 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001131 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001133 // Ask HeaderInfo if we should enter this #include file. If not, #including
1134 // this file will have no effect.
1135 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001136 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001137 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001138 return;
1139 }
1140
Chris Lattner141e71f2008-03-09 01:54:53 +00001141 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001142 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1143 FileCharacter);
1144 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001145 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001146 return;
1147 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001148
1149 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001150 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001151}
1152
1153/// HandleIncludeNextDirective - Implements #include_next.
1154///
1155void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1156 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Chris Lattner141e71f2008-03-09 01:54:53 +00001158 // #include_next is like #include, except that we start searching after
1159 // the current found directory. If we can't do this, issue a
1160 // diagnostic.
1161 const DirectoryLookup *Lookup = CurDirLookup;
1162 if (isInPrimaryFile()) {
1163 Lookup = 0;
1164 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1165 } else if (Lookup == 0) {
1166 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1167 } else {
1168 // Start looking up in the next directory.
1169 ++Lookup;
1170 }
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Chris Lattner141e71f2008-03-09 01:54:53 +00001172 return HandleIncludeDirective(IncludeNextTok, Lookup);
1173}
1174
1175/// HandleImportDirective - Implements #import.
1176///
1177void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001178 if (!Features.ObjC1) // #import is standard for ObjC.
1179 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Chris Lattner141e71f2008-03-09 01:54:53 +00001181 return HandleIncludeDirective(ImportTok, 0, true);
1182}
1183
Chris Lattnerde076652009-04-08 18:46:40 +00001184/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1185/// pseudo directive in the predefines buffer. This handles it by sucking all
1186/// tokens through the preprocessor and discarding them (only keeping the side
1187/// effects on the preprocessor).
1188void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1189 // This directive should only occur in the predefines buffer. If not, emit an
1190 // error and reject it.
1191 SourceLocation Loc = IncludeMacrosTok.getLocation();
1192 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1193 Diag(IncludeMacrosTok.getLocation(),
1194 diag::pp_include_macros_out_of_predefines);
1195 DiscardUntilEndOfDirective();
1196 return;
1197 }
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Chris Lattnerfd105112009-04-08 20:53:24 +00001199 // Treat this as a normal #include for checking purposes. If this is
1200 // successful, it will push a new lexer onto the include stack.
1201 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Chris Lattnerfd105112009-04-08 20:53:24 +00001203 Token TmpTok;
1204 do {
1205 Lex(TmpTok);
1206 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1207 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001208}
1209
Chris Lattner141e71f2008-03-09 01:54:53 +00001210//===----------------------------------------------------------------------===//
1211// Preprocessor Macro Directive Handling.
1212//===----------------------------------------------------------------------===//
1213
1214/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1215/// definition has just been read. Lex the rest of the arguments and the
1216/// closing ), updating MI with what we learn. Return true if an error occurs
1217/// parsing the arg list.
1218bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1219 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Chris Lattner141e71f2008-03-09 01:54:53 +00001221 Token Tok;
1222 while (1) {
1223 LexUnexpandedToken(Tok);
1224 switch (Tok.getKind()) {
1225 case tok::r_paren:
1226 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001227 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001228 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001229 // Otherwise we have #define FOO(A,)
1230 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1231 return true;
1232 case tok::ellipsis: // #define X(... -> C99 varargs
1233 // Warn if use of C99 feature in non-C99 mode.
1234 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1235
1236 // Lex the token after the identifier.
1237 LexUnexpandedToken(Tok);
1238 if (Tok.isNot(tok::r_paren)) {
1239 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1240 return true;
1241 }
1242 // Add the __VA_ARGS__ identifier as an argument.
1243 Arguments.push_back(Ident__VA_ARGS__);
1244 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001245 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001246 return false;
1247 case tok::eom: // #define X(
1248 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1249 return true;
1250 default:
1251 // Handle keywords and identifiers here to accept things like
1252 // #define Foo(for) for.
1253 IdentifierInfo *II = Tok.getIdentifierInfo();
1254 if (II == 0) {
1255 // #define X(1
1256 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1257 return true;
1258 }
1259
1260 // If this is already used as an argument, it is used multiple times (e.g.
1261 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001262 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001263 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001264 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001265 return true;
1266 }
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Chris Lattner141e71f2008-03-09 01:54:53 +00001268 // Add the argument to the macro info.
1269 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Chris Lattner141e71f2008-03-09 01:54:53 +00001271 // Lex the token after the identifier.
1272 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Chris Lattner141e71f2008-03-09 01:54:53 +00001274 switch (Tok.getKind()) {
1275 default: // #define X(A B
1276 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1277 return true;
1278 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001279 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001280 return false;
1281 case tok::comma: // #define X(A,
1282 break;
1283 case tok::ellipsis: // #define X(A... -> GCC extension
1284 // Diagnose extension.
1285 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Chris Lattner141e71f2008-03-09 01:54:53 +00001287 // Lex the token after the identifier.
1288 LexUnexpandedToken(Tok);
1289 if (Tok.isNot(tok::r_paren)) {
1290 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1291 return true;
1292 }
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Chris Lattner141e71f2008-03-09 01:54:53 +00001294 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001295 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001296 return false;
1297 }
1298 }
1299 }
1300}
1301
1302/// HandleDefineDirective - Implements #define. This consumes the entire macro
1303/// line then lets the caller lex the next real token.
1304void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1305 ++NumDefined;
1306
1307 Token MacroNameTok;
1308 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Chris Lattner141e71f2008-03-09 01:54:53 +00001310 // Error reading macro name? If so, diagnostic already issued.
1311 if (MacroNameTok.is(tok::eom))
1312 return;
1313
Chris Lattner2451b522009-04-21 04:46:33 +00001314 Token LastTok = MacroNameTok;
1315
Chris Lattner141e71f2008-03-09 01:54:53 +00001316 // If we are supposed to keep comments in #defines, reenable comment saving
1317 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001318 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Chris Lattner141e71f2008-03-09 01:54:53 +00001320 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001321 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Chris Lattner141e71f2008-03-09 01:54:53 +00001323 Token Tok;
1324 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Chris Lattner141e71f2008-03-09 01:54:53 +00001326 // If this is a function-like macro definition, parse the argument list,
1327 // marking each of the identifiers as being used as macro arguments. Also,
1328 // check other constraints on the first token of the macro body.
1329 if (Tok.is(tok::eom)) {
1330 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001331 } else if (Tok.hasLeadingSpace()) {
1332 // This is a normal token with leading space. Clear the leading space
1333 // marker on the first token to get proper expansion.
1334 Tok.clearFlag(Token::LeadingSpace);
1335 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001336 // This is a function-like macro definition. Read the argument list.
1337 MI->setIsFunctionLike();
1338 if (ReadMacroDefinitionArgList(MI)) {
1339 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001340 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001341 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001342 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001343 DiscardUntilEndOfDirective();
1344 return;
1345 }
1346
Chris Lattner8fde5972009-04-19 18:26:34 +00001347 // If this is a definition of a variadic C99 function-like macro, not using
1348 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Chris Lattner8fde5972009-04-19 18:26:34 +00001350 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1351 // This gets unpoisoned where it is allowed.
1352 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1353 if (MI->isC99Varargs())
1354 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Chris Lattner141e71f2008-03-09 01:54:53 +00001356 // Read the first token after the arg list for down below.
1357 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001358 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001359 // C99 requires whitespace between the macro definition and the body. Emit
1360 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001361 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001362 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001363 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1364 // first character of a replacement list is not a character required by
1365 // subclause 5.2.1, then there shall be white-space separation between the
1366 // identifier and the replacement list.". 5.2.1 lists this set:
1367 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1368 // is irrelevant here.
1369 bool isInvalid = false;
1370 if (Tok.is(tok::at)) // @ is not in the list above.
1371 isInvalid = true;
1372 else if (Tok.is(tok::unknown)) {
1373 // If we have an unknown token, it is something strange like "`". Since
1374 // all of valid characters would have lexed into a single character
1375 // token of some sort, we know this is not a valid case.
1376 isInvalid = true;
1377 }
1378 if (isInvalid)
1379 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1380 else
1381 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001382 }
Chris Lattner2451b522009-04-21 04:46:33 +00001383
1384 if (!Tok.is(tok::eom))
1385 LastTok = Tok;
1386
Chris Lattner141e71f2008-03-09 01:54:53 +00001387 // Read the rest of the macro body.
1388 if (MI->isObjectLike()) {
1389 // Object-like macros are very simple, just read their body.
1390 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001391 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001392 MI->AddTokenToBody(Tok);
1393 // Get the next token of the macro.
1394 LexUnexpandedToken(Tok);
1395 }
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Chris Lattner141e71f2008-03-09 01:54:53 +00001397 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001398 // Otherwise, read the body of a function-like macro. While we are at it,
1399 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1400 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001401 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001402 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001403
Chris Lattner141e71f2008-03-09 01:54:53 +00001404 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001405 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Chris Lattner141e71f2008-03-09 01:54:53 +00001407 // Get the next token of the macro.
1408 LexUnexpandedToken(Tok);
1409 continue;
1410 }
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Chris Lattner141e71f2008-03-09 01:54:53 +00001412 // Get the next token of the macro.
1413 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Chris Lattner32404692009-05-25 17:16:10 +00001415 // Check for a valid macro arg identifier.
1416 if (Tok.getIdentifierInfo() == 0 ||
1417 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1418
1419 // If this is assembler-with-cpp mode, we accept random gibberish after
1420 // the '#' because '#' is often a comment character. However, change
1421 // the kind of the token to tok::unknown so that the preprocessor isn't
1422 // confused.
1423 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1424 LastTok.setKind(tok::unknown);
1425 } else {
1426 Diag(Tok, diag::err_pp_stringize_not_parameter);
1427 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Chris Lattner32404692009-05-25 17:16:10 +00001429 // Disable __VA_ARGS__ again.
1430 Ident__VA_ARGS__->setIsPoisoned(true);
1431 return;
1432 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001433 }
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Chris Lattner32404692009-05-25 17:16:10 +00001435 // Things look ok, add the '#' and param name tokens to the macro.
1436 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001437 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001438 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Chris Lattner141e71f2008-03-09 01:54:53 +00001440 // Get the next token of the macro.
1441 LexUnexpandedToken(Tok);
1442 }
1443 }
Mike Stump1eb44332009-09-09 15:08:12 +00001444
1445
Chris Lattner141e71f2008-03-09 01:54:53 +00001446 // Disable __VA_ARGS__ again.
1447 Ident__VA_ARGS__->setIsPoisoned(true);
1448
1449 // Check that there is no paste (##) operator at the begining or end of the
1450 // replacement list.
1451 unsigned NumTokens = MI->getNumTokens();
1452 if (NumTokens != 0) {
1453 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1454 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001455 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001456 return;
1457 }
1458 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1459 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001460 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001461 return;
1462 }
1463 }
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Chris Lattner141e71f2008-03-09 01:54:53 +00001465 // If this is the primary source file, remember that this macro hasn't been
1466 // used yet.
1467 if (isInPrimaryFile())
1468 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001469
1470 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Chris Lattner141e71f2008-03-09 01:54:53 +00001472 // Finally, if this identifier already had a macro defined for it, verify that
1473 // the macro bodies are identical and free the old definition.
1474 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001475 // It is very common for system headers to have tons of macro redefinitions
1476 // and for warnings to be disabled in system headers. If this is the case,
1477 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001478 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001479 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1480 if (!OtherMI->isUsed())
1481 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001482
Chris Lattnerf47724b2010-08-17 15:55:45 +00001483 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001484 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001485 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001486 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001487 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1488 << MacroNameTok.getIdentifierInfo();
1489 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1490 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001491 }
Ted Kremenek0ea76722008-12-15 19:56:42 +00001492 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001493 }
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Chris Lattner141e71f2008-03-09 01:54:53 +00001495 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001497 // If the callbacks want to know, tell them about the macro definition.
1498 if (Callbacks)
1499 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001500}
1501
1502/// HandleUndefDirective - Implements #undef.
1503///
1504void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1505 ++NumUndefined;
1506
1507 Token MacroNameTok;
1508 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Chris Lattner141e71f2008-03-09 01:54:53 +00001510 // Error reading macro name? If so, diagnostic already issued.
1511 if (MacroNameTok.is(tok::eom))
1512 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Chris Lattner141e71f2008-03-09 01:54:53 +00001514 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001515 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Chris Lattner141e71f2008-03-09 01:54:53 +00001517 // Okay, we finally have a valid identifier to undef.
1518 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Chris Lattner141e71f2008-03-09 01:54:53 +00001520 // If the macro is not defined, this is a noop undef, just return.
1521 if (MI == 0) return;
1522
1523 if (!MI->isUsed())
1524 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001525
1526 // If the callbacks want to know, tell them about the macro #undef.
1527 if (Callbacks)
Benjamin Kramer2f054492010-08-07 22:27:00 +00001528 Callbacks->MacroUndefined(MacroNameTok.getLocation(),
1529 MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001530
Chris Lattner141e71f2008-03-09 01:54:53 +00001531 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001532 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001533 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1534}
1535
1536
1537//===----------------------------------------------------------------------===//
1538// Preprocessor Conditional Directive Handling.
1539//===----------------------------------------------------------------------===//
1540
1541/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1542/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1543/// if any tokens have been returned or pp-directives activated before this
1544/// #ifndef has been lexed.
1545///
1546void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1547 bool ReadAnyTokensBeforeDirective) {
1548 ++NumIf;
1549 Token DirectiveTok = Result;
1550
1551 Token MacroNameTok;
1552 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Chris Lattner141e71f2008-03-09 01:54:53 +00001554 // Error reading macro name? If so, diagnostic already issued.
1555 if (MacroNameTok.is(tok::eom)) {
1556 // Skip code until we get to #endif. This helps with recovery by not
1557 // emitting an error when the #endif is reached.
1558 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1559 /*Foundnonskip*/false, /*FoundElse*/false);
1560 return;
1561 }
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Chris Lattner141e71f2008-03-09 01:54:53 +00001563 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001564 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001565
Chris Lattner13d283d2010-02-12 08:03:27 +00001566 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1567 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001568
Ted Kremenek60e45d42008-11-18 00:34:22 +00001569 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001570 // If the start of a top-level #ifdef and if the macro is not defined,
1571 // inform MIOpt that this might be the start of a proper include guard.
1572 // Otherwise it is some other form of unknown conditional which we can't
1573 // handle.
1574 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001575 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001576 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001577 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001578 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001579 }
1580
Chris Lattner141e71f2008-03-09 01:54:53 +00001581 // If there is a macro, process it.
1582 if (MI) // Mark it used.
1583 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Chris Lattner141e71f2008-03-09 01:54:53 +00001585 // Should we include the stuff contained by this directive?
1586 if (!MI == isIfndef) {
1587 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001588 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1589 /*wasskip*/false, /*foundnonskip*/true,
1590 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001591 } else {
1592 // No, skip the contents of this block and return the first token after it.
1593 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001594 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001595 /*FoundElse*/false);
1596 }
1597}
1598
1599/// HandleIfDirective - Implements the #if directive.
1600///
1601void Preprocessor::HandleIfDirective(Token &IfToken,
1602 bool ReadAnyTokensBeforeDirective) {
1603 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Chris Lattner141e71f2008-03-09 01:54:53 +00001605 // Parse and evaluation the conditional expression.
1606 IdentifierInfo *IfNDefMacro = 0;
1607 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Nuno Lopes0049db62008-06-01 18:31:24 +00001609
1610 // If this condition is equivalent to #ifndef X, and if this is the first
1611 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001612 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001613 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001614 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001615 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001616 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001617 }
1618
Chris Lattner141e71f2008-03-09 01:54:53 +00001619 // Should we include the stuff contained by this directive?
1620 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001621 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001622 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001623 /*foundnonskip*/true, /*foundelse*/false);
1624 } else {
1625 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001626 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001627 /*FoundElse*/false);
1628 }
1629}
1630
1631/// HandleEndifDirective - Implements the #endif directive.
1632///
1633void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1634 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Chris Lattner141e71f2008-03-09 01:54:53 +00001636 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001637 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Chris Lattner141e71f2008-03-09 01:54:53 +00001639 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001640 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001641 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001642 Diag(EndifToken, diag::err_pp_endif_without_if);
1643 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001644 }
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Chris Lattner141e71f2008-03-09 01:54:53 +00001646 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001647 if (CurPPLexer->getConditionalStackDepth() == 0)
1648 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Ted Kremenek60e45d42008-11-18 00:34:22 +00001650 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001651 "This code should only be reachable in the non-skipping case!");
1652}
1653
1654
1655void Preprocessor::HandleElseDirective(Token &Result) {
1656 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Chris Lattner141e71f2008-03-09 01:54:53 +00001658 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001659 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Chris Lattner141e71f2008-03-09 01:54:53 +00001661 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001662 if (CurPPLexer->popConditionalLevel(CI)) {
1663 Diag(Result, diag::pp_err_else_without_if);
1664 return;
1665 }
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Chris Lattner141e71f2008-03-09 01:54:53 +00001667 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001668 if (CurPPLexer->getConditionalStackDepth() == 0)
1669 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001670
1671 // If this is a #else with a #else before it, report the error.
1672 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Chris Lattner141e71f2008-03-09 01:54:53 +00001674 // Finally, skip the rest of the contents of this block and return the first
1675 // token after it.
1676 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1677 /*FoundElse*/true);
1678}
1679
1680void Preprocessor::HandleElifDirective(Token &ElifToken) {
1681 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Chris Lattner141e71f2008-03-09 01:54:53 +00001683 // #elif directive in a non-skipping conditional... start skipping.
1684 // We don't care what the condition is, because we will always skip it (since
1685 // the block immediately before it was included).
1686 DiscardUntilEndOfDirective();
1687
1688 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001689 if (CurPPLexer->popConditionalLevel(CI)) {
1690 Diag(ElifToken, diag::pp_err_elif_without_if);
1691 return;
1692 }
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Chris Lattner141e71f2008-03-09 01:54:53 +00001694 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001695 if (CurPPLexer->getConditionalStackDepth() == 0)
1696 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Chris Lattner141e71f2008-03-09 01:54:53 +00001698 // If this is a #elif with a #else before it, report the error.
1699 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1700
1701 // Finally, skip the rest of the contents of this block and return the first
1702 // token after it.
1703 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1704 /*FoundElse*/CI.FoundElse);
1705}