blob: 5e3b16e60de9c3a05b641aafaa4de8a4172b7cac [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();
Chris Lattner0301b3f2009-02-20 22:19:20 +000036 } else
37 MI = (MacroInfo*) BP.Allocate<MacroInfo>();
Chris Lattnerf47724b2010-08-17 15:55:45 +000038 return MI;
39}
40
41MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
42 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000043 new (MI) MacroInfo(L);
44 return MI;
45}
46
Chris Lattnerf47724b2010-08-17 15:55:45 +000047MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
48 MacroInfo *MI = AllocateMacroInfo();
49 new (MI) MacroInfo(MacroToClone, BP);
50 return MI;
51}
52
Chris Lattner0301b3f2009-02-20 22:19:20 +000053/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
54/// be reused for allocating new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000055void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Chris Lattner0301b3f2009-02-20 22:19:20 +000056 MICache.push_back(MI);
Chris Lattner2c1ab902010-08-18 16:08:51 +000057 MI->FreeArgumentList();
Chris Lattner0301b3f2009-02-20 22:19:20 +000058}
59
60
Chris Lattner141e71f2008-03-09 01:54:53 +000061/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
62/// current line until the tok::eom token is found.
63void Preprocessor::DiscardUntilEndOfDirective() {
64 Token Tmp;
65 do {
66 LexUnexpandedToken(Tmp);
67 } while (Tmp.isNot(tok::eom));
68}
69
Chris Lattner141e71f2008-03-09 01:54:53 +000070/// ReadMacroName - Lex and validate a macro name, which occurs after a
71/// #define or #undef. This sets the token kind to eom and discards the rest
72/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
73/// this is due to a a #define, 2 if #undef directive, 0 if it is something
74/// else (e.g. #ifdef).
75void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
76 // Read the token, don't allow macro expansion on it.
77 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +000078
Douglas Gregor1fbb4472010-08-24 20:21:13 +000079 if (MacroNameTok.is(tok::code_completion)) {
80 if (CodeComplete)
81 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
82 LexUnexpandedToken(MacroNameTok);
83 return;
84 }
85
Chris Lattner141e71f2008-03-09 01:54:53 +000086 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000087 if (MacroNameTok.is(tok::eom)) {
88 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
89 return;
90 }
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattner141e71f2008-03-09 01:54:53 +000092 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
93 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +000094 bool Invalid = false;
95 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
96 if (Invalid)
97 return;
98
Chris Lattner9485d232008-12-13 20:12:40 +000099 const IdentifierInfo &Info = Identifiers.get(Spelling);
100 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000101 // C++ 2.5p2: Alternative tokens behave the same as its primary token
102 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000103 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +0000104 else
105 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
106 // Fall through on error.
107 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
108 // Error if defining "defined": C99 6.10.8.4.
109 Diag(MacroNameTok, diag::err_defined_macro_name);
110 } else if (isDefineUndef && II->hasMacroDefinition() &&
111 getMacroInfo(II)->isBuiltinMacro()) {
112 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
113 if (isDefineUndef == 1)
114 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
115 else
116 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
117 } else {
118 // Okay, we got a good identifier node. Return it.
119 return;
120 }
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattner141e71f2008-03-09 01:54:53 +0000122 // Invalid macro name, read and discard the rest of the line. Then set the
123 // token kind to tok::eom.
124 MacroNameTok.setKind(tok::eom);
125 return DiscardUntilEndOfDirective();
126}
127
128/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattnerab82f412009-04-17 23:30:53 +0000129/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
130/// true, then we consider macros that expand to zero tokens as being ok.
131void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000132 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000133 // Lex unexpanded tokens for most directives: macros might expand to zero
134 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
135 // #line) allow empty macros.
136 if (EnableMacros)
137 Lex(Tmp);
138 else
139 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Chris Lattner141e71f2008-03-09 01:54:53 +0000141 // There should be no tokens after the directive, but we allow them as an
142 // extension.
143 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
144 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Chris Lattner141e71f2008-03-09 01:54:53 +0000146 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000147 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
148 // because it is more trouble than it is worth to insert /**/ and check that
149 // there is no /**/ in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000150 FixItHint Hint;
Chris Lattner959875a2009-04-14 05:15:20 +0000151 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
Douglas Gregor849b2432010-03-31 17:46:05 +0000152 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
153 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000154 DiscardUntilEndOfDirective();
155 }
156}
157
158
159
160/// SkipExcludedConditionalBlock - We just read a #if or related directive and
161/// decided that the subsequent tokens are in the #if'd out portion of the
162/// file. Lex the rest of the file, until we see an #endif. If
163/// FoundNonSkipPortion is true, then we have already emitted code for part of
164/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
165/// is true, then #else directives are ok, if not, then we have already seen one
166/// so a #else directive is a duplicate. When this returns, the caller can lex
167/// the first valid token.
168void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
169 bool FoundNonSkipPortion,
170 bool FoundElse) {
171 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000172 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000173
Ted Kremenek60e45d42008-11-18 00:34:22 +0000174 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000175 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Ted Kremenek268ee702008-12-12 18:34:08 +0000177 if (CurPTHLexer) {
178 PTHSkipExcludedConditionalBlock();
179 return;
180 }
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattner141e71f2008-03-09 01:54:53 +0000182 // Enter raw mode to disable identifier lookup (and thus macro expansion),
183 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000184 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000185 Token Tok;
186 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000187 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Douglas Gregorf44e8542010-08-24 19:08:16 +0000189 if (Tok.is(tok::code_completion)) {
190 if (CodeComplete)
191 CodeComplete->CodeCompleteInConditionalExclusion();
192 continue;
193 }
194
Chris Lattner141e71f2008-03-09 01:54:53 +0000195 // If this is the end of the buffer, we have an error.
196 if (Tok.is(tok::eof)) {
197 // Emit errors for each unterminated conditional on the stack, including
198 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000199 while (!CurPPLexer->ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000200 if (!isCodeCompletionFile(Tok.getLocation()))
201 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
202 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000203 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000204 }
205
Chris Lattner141e71f2008-03-09 01:54:53 +0000206 // Just return and let the caller lex after this #include.
207 break;
208 }
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Chris Lattner141e71f2008-03-09 01:54:53 +0000210 // If this token is not a preprocessor directive, just skip it.
211 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
212 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Chris Lattner141e71f2008-03-09 01:54:53 +0000214 // We just parsed a # character at the start of a line, so we're in
215 // directive mode. Tell the lexer this so any newlines we see will be
216 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000217 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000218 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000219
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Chris Lattner141e71f2008-03-09 01:54:53 +0000221 // Read the next token, the directive flavor.
222 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Chris Lattner141e71f2008-03-09 01:54:53 +0000224 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
225 // something bogus), skip it.
226 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000227 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000228 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000229 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000230 continue;
231 }
232
233 // If the first letter isn't i or e, it isn't intesting to us. We know that
234 // this is safe in the face of spelling differences, because there is no way
235 // to spell an i/e in a strange way that is another letter. Skipping this
236 // allows us to avoid looking up the identifier info for #define/#undef and
237 // other common directives.
Douglas Gregora5430162010-03-16 20:46:42 +0000238 bool Invalid = false;
239 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation(),
240 &Invalid);
241 if (Invalid)
242 return;
243
Chris Lattner141e71f2008-03-09 01:54:53 +0000244 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000245 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000246 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000247 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000248 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000249 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000250 continue;
251 }
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Chris Lattner141e71f2008-03-09 01:54:53 +0000253 // Get the identifier name without trigraphs or embedded newlines. Note
254 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
255 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000256 char DirectiveBuf[20];
257 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000258 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000259 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000260 } else {
261 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000262 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000263 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000264 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000265 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000266 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000267 continue;
268 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000269 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
270 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000271 }
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000273 if (Directive.startswith("if")) {
274 llvm::StringRef Sub = Directive.substr(2);
275 if (Sub.empty() || // "if"
276 Sub == "def" || // "ifdef"
277 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000278 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
279 // bother parsing the condition.
280 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000281 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000282 /*foundnonskip*/false,
283 /*fnddelse*/false);
284 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000285 } else if (Directive[0] == 'e') {
286 llvm::StringRef Sub = Directive.substr(1);
287 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000288 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000289 PPConditionalInfo CondInfo;
290 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000291 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000292 InCond = InCond; // Silence warning in no-asserts mode.
293 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattner141e71f2008-03-09 01:54:53 +0000295 // If we popped the outermost skipping block, we're done skipping!
296 if (!CondInfo.WasSkipping)
297 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000298 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000299 // #else directive in a skipping conditional. If not in some other
300 // skipping conditional, and if #else hasn't already been seen, enter it
301 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000302 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000303 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Chris Lattner141e71f2008-03-09 01:54:53 +0000305 // If this is a #else with a #else before it, report the error.
306 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Chris Lattner141e71f2008-03-09 01:54:53 +0000308 // Note that we've seen a #else in this conditional.
309 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Chris Lattner141e71f2008-03-09 01:54:53 +0000311 // If the conditional is at the top level, and the #if block wasn't
312 // entered, enter the #else block now.
313 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
314 CondInfo.FoundNonSkip = true;
315 break;
316 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000317 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000318 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000319
320 bool ShouldEnter;
321 // If this is in a skipping block or if we're already handled this #if
322 // block, don't bother parsing the condition.
323 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
324 DiscardUntilEndOfDirective();
325 ShouldEnter = false;
326 } else {
327 // Restore the value of LexingRawMode so that identifiers are
328 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000329 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
330 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000331 IdentifierInfo *IfNDefMacro = 0;
332 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000333 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000334 }
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Chris Lattner141e71f2008-03-09 01:54:53 +0000336 // If this is a #elif with a #else before it, report the error.
337 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner141e71f2008-03-09 01:54:53 +0000339 // If this condition is true, enter it!
340 if (ShouldEnter) {
341 CondInfo.FoundNonSkip = true;
342 break;
343 }
344 }
345 }
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Ted Kremenek60e45d42008-11-18 00:34:22 +0000347 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000348 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000349 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000350 }
351
352 // Finally, if we are out of the conditional (saw an #endif or ran off the end
353 // of the file, just stop skipping and return to lexing whatever came after
354 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000355 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000356}
357
Ted Kremenek268ee702008-12-12 18:34:08 +0000358void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000359
360 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000361 assert(CurPTHLexer);
362 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Ted Kremenek268ee702008-12-12 18:34:08 +0000364 // Skip to the next '#else', '#elif', or #endif.
365 if (CurPTHLexer->SkipBlock()) {
366 // We have reached an #endif. Both the '#' and 'endif' tokens
367 // have been consumed by the PTHLexer. Just pop off the condition level.
368 PPConditionalInfo CondInfo;
369 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
370 InCond = InCond; // Silence warning in no-asserts mode.
371 assert(!InCond && "Can't be skipping if not in a conditional!");
372 break;
373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Ted Kremenek268ee702008-12-12 18:34:08 +0000375 // We have reached a '#else' or '#elif'. Lex the next token to get
376 // the directive flavor.
377 Token Tok;
378 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Ted Kremenek268ee702008-12-12 18:34:08 +0000380 // We can actually look up the IdentifierInfo here since we aren't in
381 // raw mode.
382 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
383
384 if (K == tok::pp_else) {
385 // #else: Enter the else condition. We aren't in a nested condition
386 // since we skip those. We're always in the one matching the last
387 // blocked we skipped.
388 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
389 // Note that we've seen a #else in this conditional.
390 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Ted Kremenek268ee702008-12-12 18:34:08 +0000392 // If the #if block wasn't entered then enter the #else block now.
393 if (!CondInfo.FoundNonSkip) {
394 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000396 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000397 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000398 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000399 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Ted Kremenek268ee702008-12-12 18:34:08 +0000401 break;
402 }
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Ted Kremenek268ee702008-12-12 18:34:08 +0000404 // Otherwise skip this block.
405 continue;
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Ted Kremenek268ee702008-12-12 18:34:08 +0000408 assert(K == tok::pp_elif);
409 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
410
411 // If this is a #elif with a #else before it, report the error.
412 if (CondInfo.FoundElse)
413 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Ted Kremenek268ee702008-12-12 18:34:08 +0000415 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000416 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000417 if (CondInfo.FoundNonSkip)
418 continue;
419
420 // Evaluate the condition of the #elif.
421 IdentifierInfo *IfNDefMacro = 0;
422 CurPTHLexer->ParsingPreprocessorDirective = true;
423 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
424 CurPTHLexer->ParsingPreprocessorDirective = false;
425
426 // If this condition is true, enter it!
427 if (ShouldEnter) {
428 CondInfo.FoundNonSkip = true;
429 break;
430 }
431
432 // Otherwise, skip this block and go to the next one.
433 continue;
434 }
435}
436
Chris Lattner10725092008-03-09 04:17:44 +0000437/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
438/// return null on failure. isAngled indicates whether the file reference is
439/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnera1394812010-01-10 01:35:12 +0000440const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattner10725092008-03-09 04:17:44 +0000441 bool isAngled,
442 const DirectoryLookup *FromDir,
443 const DirectoryLookup *&CurDir) {
444 // If the header lookup mechanism may be relative to the current file, pass in
445 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000446 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000447 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000448 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000449 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000451 // If there is no file entry associated with this file, it must be the
452 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000453 // it won't be scanned for preprocessor directives. If we have the
454 // predefines buffer, resolve #include references (which come from the
455 // -include command line argument) as if they came from the main file, this
456 // affects file lookup etc.
457 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000458 FID = SourceMgr.getMainFileID();
459 CurFileEnt = SourceMgr.getFileEntryForID(FID);
460 }
Chris Lattner10725092008-03-09 04:17:44 +0000461 }
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Chris Lattner10725092008-03-09 04:17:44 +0000463 // Do a standard file entry lookup.
464 CurDir = CurDirLookup;
465 const FileEntry *FE =
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000466 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000467 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Chris Lattner10725092008-03-09 04:17:44 +0000469 // Otherwise, see if this is a subframework header. If so, this is relative
470 // to one of the headers on the #include stack. Walk the list of the current
471 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000472 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000473 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000474 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000475 return FE;
476 }
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Chris Lattner10725092008-03-09 04:17:44 +0000478 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
479 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000480 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000481 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000482 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000483 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000484 return FE;
485 }
486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Chris Lattner10725092008-03-09 04:17:44 +0000488 // Otherwise, we really couldn't find the file.
489 return 0;
490}
491
Chris Lattner141e71f2008-03-09 01:54:53 +0000492
493//===----------------------------------------------------------------------===//
494// Preprocessor Directive Handling.
495//===----------------------------------------------------------------------===//
496
497/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000498/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000499/// lexer/preprocessor state, and advances the lexer(s) so that the next token
500/// read is the correct one.
501void Preprocessor::HandleDirective(Token &Result) {
502 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Chris Lattner141e71f2008-03-09 01:54:53 +0000504 // We just parsed a # character at the start of a line, so we're in directive
505 // mode. Tell the lexer this so any newlines we see will be converted into an
506 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000507 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Chris Lattner141e71f2008-03-09 01:54:53 +0000509 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000510
Chris Lattner141e71f2008-03-09 01:54:53 +0000511 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000512 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000513 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000514 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Chris Lattner42aa16c2009-03-18 21:00:25 +0000516 // Save the '#' token in case we need to return it later.
517 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Chris Lattner141e71f2008-03-09 01:54:53 +0000519 // Read the next token, the directive flavor. This isn't expanded due to
520 // C99 6.10.3p8.
521 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattner141e71f2008-03-09 01:54:53 +0000523 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
524 // #define A(x) #x
525 // A(abc
526 // #warning blah
527 // def)
528 // If so, the user is relying on non-portable behavior, emit a diagnostic.
529 if (InMacroArgs)
530 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Chris Lattner141e71f2008-03-09 01:54:53 +0000532TryAgain:
533 switch (Result.getKind()) {
534 case tok::eom:
535 return; // null directive.
536 case tok::comment:
537 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
538 LexUnexpandedToken(Result);
539 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000540 case tok::code_completion:
541 if (CodeComplete)
542 CodeComplete->CodeCompleteDirective(
543 CurPPLexer->getConditionalStackDepth() > 0);
544 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000545 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000546 if (getLangOptions().AsmPreprocessor)
547 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000548 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000549 default:
550 IdentifierInfo *II = Result.getIdentifierInfo();
551 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Chris Lattner141e71f2008-03-09 01:54:53 +0000553 // Ask what the preprocessor keyword ID is.
554 switch (II->getPPKeywordID()) {
555 default: break;
556 // C99 6.10.1 - Conditional Inclusion.
557 case tok::pp_if:
558 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
559 case tok::pp_ifdef:
560 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
561 case tok::pp_ifndef:
562 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
563 case tok::pp_elif:
564 return HandleElifDirective(Result);
565 case tok::pp_else:
566 return HandleElseDirective(Result);
567 case tok::pp_endif:
568 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattner141e71f2008-03-09 01:54:53 +0000570 // C99 6.10.2 - Source File Inclusion.
571 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000572 return HandleIncludeDirective(Result); // Handle #include.
573 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000574 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Chris Lattner141e71f2008-03-09 01:54:53 +0000576 // C99 6.10.3 - Macro Replacement.
577 case tok::pp_define:
578 return HandleDefineDirective(Result);
579 case tok::pp_undef:
580 return HandleUndefDirective(Result);
581
582 // C99 6.10.4 - Line Control.
583 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000584 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner141e71f2008-03-09 01:54:53 +0000586 // C99 6.10.5 - Error Directive.
587 case tok::pp_error:
588 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattner141e71f2008-03-09 01:54:53 +0000590 // C99 6.10.6 - Pragma Directive.
591 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000592 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Chris Lattner141e71f2008-03-09 01:54:53 +0000594 // GNU Extensions.
595 case tok::pp_import:
596 return HandleImportDirective(Result);
597 case tok::pp_include_next:
598 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Chris Lattner141e71f2008-03-09 01:54:53 +0000600 case tok::pp_warning:
601 Diag(Result, diag::ext_pp_warning_directive);
602 return HandleUserDiagnosticDirective(Result, true);
603 case tok::pp_ident:
604 return HandleIdentSCCSDirective(Result);
605 case tok::pp_sccs:
606 return HandleIdentSCCSDirective(Result);
607 case tok::pp_assert:
608 //isExtension = true; // FIXME: implement #assert
609 break;
610 case tok::pp_unassert:
611 //isExtension = true; // FIXME: implement #unassert
612 break;
613 }
614 break;
615 }
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Chris Lattner42aa16c2009-03-18 21:00:25 +0000617 // If this is a .S file, treat unknown # directives as non-preprocessor
618 // directives. This is important because # may be a comment or introduce
619 // various pseudo-ops. Just return the # token and push back the following
620 // token to be lexed next time.
621 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000622 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000623 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000624 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000625 Toks[1] = Result;
626 // Enter this token stream so that we re-lex the tokens. Make sure to
627 // enable macro expansion, in case the token after the # is an identifier
628 // that is expanded.
629 EnterTokenStream(Toks, 2, false, true);
630 return;
631 }
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattner141e71f2008-03-09 01:54:53 +0000633 // If we reached here, the preprocessing token is not valid!
634 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Chris Lattner141e71f2008-03-09 01:54:53 +0000636 // Read the rest of the PP line.
637 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattner141e71f2008-03-09 01:54:53 +0000639 // Okay, we're done parsing the directive.
640}
641
Chris Lattner478a18e2009-01-26 06:19:46 +0000642/// GetLineValue - Convert a numeric token into an unsigned value, emitting
643/// Diagnostic DiagID if it is invalid, and returning the value in Val.
644static bool GetLineValue(Token &DigitTok, unsigned &Val,
645 unsigned DiagID, Preprocessor &PP) {
646 if (DigitTok.isNot(tok::numeric_constant)) {
647 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Chris Lattner478a18e2009-01-26 06:19:46 +0000649 if (DigitTok.isNot(tok::eom))
650 PP.DiscardUntilEndOfDirective();
651 return true;
652 }
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Chris Lattner478a18e2009-01-26 06:19:46 +0000654 llvm::SmallString<64> IntegerBuffer;
655 IntegerBuffer.resize(DigitTok.getLength());
656 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000657 bool Invalid = false;
658 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
659 if (Invalid)
660 return true;
661
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000662 // Verify that we have a simple digit-sequence, and compute the value. This
663 // is always a simple digit string computed in decimal, so we do this manually
664 // here.
665 Val = 0;
666 for (unsigned i = 0; i != ActualLength; ++i) {
667 if (!isdigit(DigitTokBegin[i])) {
668 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
669 diag::err_pp_line_digit_sequence);
670 PP.DiscardUntilEndOfDirective();
671 return true;
672 }
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000674 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
675 if (NextVal < Val) { // overflow.
676 PP.Diag(DigitTok, DiagID);
677 PP.DiscardUntilEndOfDirective();
678 return true;
679 }
680 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000681 }
Mike Stump1eb44332009-09-09 15:08:12 +0000682
683 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000684 if (Val == 0) {
685 PP.Diag(DigitTok, DiagID);
686 PP.DiscardUntilEndOfDirective();
687 return true;
688 }
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000690 if (DigitTokBegin[0] == '0')
691 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Chris Lattner478a18e2009-01-26 06:19:46 +0000693 return false;
694}
695
Mike Stump1eb44332009-09-09 15:08:12 +0000696/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000697/// acceptable forms are:
698/// # line digit-sequence
699/// # line digit-sequence "s-char-sequence"
700void Preprocessor::HandleLineDirective(Token &Tok) {
701 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
702 // expanded.
703 Token DigitTok;
704 Lex(DigitTok);
705
Chris Lattner359cc442009-01-26 05:29:08 +0000706 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000707 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000708 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000709 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000710
Chris Lattner478a18e2009-01-26 06:19:46 +0000711 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
712 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000713 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
714 if (LineNo >= LineLimit)
715 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattner5b9a5042009-01-26 07:57:50 +0000717 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000718 Token StrTok;
719 Lex(StrTok);
720
721 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
722 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000723 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000724 ; // ok
725 else if (StrTok.isNot(tok::string_literal)) {
726 Diag(StrTok, diag::err_pp_line_invalid_filename);
727 DiscardUntilEndOfDirective();
728 return;
729 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000730 // Parse and validate the string, converting it into a unique ID.
731 StringLiteralParser Literal(&StrTok, 1, *this);
732 assert(!Literal.AnyWide && "Didn't allow wide strings in");
733 if (Literal.hadError)
734 return DiscardUntilEndOfDirective();
735 if (Literal.Pascal) {
736 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
737 return DiscardUntilEndOfDirective();
738 }
739 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
740 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Chris Lattnerab82f412009-04-17 23:30:53 +0000742 // Verify that there is nothing after the string, other than EOM. Because
743 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
744 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000745 }
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Chris Lattner4c4ea172009-02-03 21:52:55 +0000747 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Chris Lattner16629382009-03-27 17:13:49 +0000749 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000750 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
751 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000752 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000753}
754
Chris Lattner478a18e2009-01-26 06:19:46 +0000755/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
756/// marker directive.
757static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
758 bool &IsSystemHeader, bool &IsExternCHeader,
759 Preprocessor &PP) {
760 unsigned FlagVal;
761 Token FlagTok;
762 PP.Lex(FlagTok);
763 if (FlagTok.is(tok::eom)) return false;
764 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
765 return true;
766
767 if (FlagVal == 1) {
768 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattner478a18e2009-01-26 06:19:46 +0000770 PP.Lex(FlagTok);
771 if (FlagTok.is(tok::eom)) return false;
772 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
773 return true;
774 } else if (FlagVal == 2) {
775 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Chris Lattner137b6a62009-02-04 06:25:26 +0000777 SourceManager &SM = PP.getSourceManager();
778 // If we are leaving the current presumed file, check to make sure the
779 // presumed include stack isn't empty!
780 FileID CurFileID =
781 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
782 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Chris Lattner137b6a62009-02-04 06:25:26 +0000784 // If there is no include loc (main file) or if the include loc is in a
785 // different physical file, then we aren't in a "1" line marker flag region.
786 SourceLocation IncLoc = PLoc.getIncludeLoc();
787 if (IncLoc.isInvalid() ||
788 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
789 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
790 PP.DiscardUntilEndOfDirective();
791 return true;
792 }
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Chris Lattner478a18e2009-01-26 06:19:46 +0000794 PP.Lex(FlagTok);
795 if (FlagTok.is(tok::eom)) return false;
796 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
797 return true;
798 }
799
800 // We must have 3 if there are still flags.
801 if (FlagVal != 3) {
802 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000803 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000804 return true;
805 }
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Chris Lattner478a18e2009-01-26 06:19:46 +0000807 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Chris Lattner478a18e2009-01-26 06:19:46 +0000809 PP.Lex(FlagTok);
810 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000811 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000812 return true;
813
814 // We must have 4 if there is yet another flag.
815 if (FlagVal != 4) {
816 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000817 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000818 return true;
819 }
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Chris Lattner478a18e2009-01-26 06:19:46 +0000821 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Chris Lattner478a18e2009-01-26 06:19:46 +0000823 PP.Lex(FlagTok);
824 if (FlagTok.is(tok::eom)) return false;
825
826 // There are no more valid flags here.
827 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000828 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000829 return true;
830}
831
832/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
833/// one of the following forms:
834///
835/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000836/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000837/// # 42 "file" ('1' | '2')? '3' '4'?
838///
839void Preprocessor::HandleDigitDirective(Token &DigitTok) {
840 // Validate the number and convert it to an unsigned. GNU does not have a
841 // line # limit other than it fit in 32-bits.
842 unsigned LineNo;
843 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
844 *this))
845 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Chris Lattner478a18e2009-01-26 06:19:46 +0000847 Token StrTok;
848 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Chris Lattner478a18e2009-01-26 06:19:46 +0000850 bool IsFileEntry = false, IsFileExit = false;
851 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000852 int FilenameID = -1;
853
Chris Lattner478a18e2009-01-26 06:19:46 +0000854 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
855 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000856 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000857 ; // ok
858 else if (StrTok.isNot(tok::string_literal)) {
859 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000860 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000861 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000862 // Parse and validate the string, converting it into a unique ID.
863 StringLiteralParser Literal(&StrTok, 1, *this);
864 assert(!Literal.AnyWide && "Didn't allow wide strings in");
865 if (Literal.hadError)
866 return DiscardUntilEndOfDirective();
867 if (Literal.Pascal) {
868 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
869 return DiscardUntilEndOfDirective();
870 }
871 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
872 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Chris Lattner478a18e2009-01-26 06:19:46 +0000874 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000875 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000876 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000877 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000878 }
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Chris Lattner9d79eba2009-02-04 05:21:58 +0000880 // Create a line note with this information.
881 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000882 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000883 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Chris Lattner16629382009-03-27 17:13:49 +0000885 // If the preprocessor has callbacks installed, notify them of the #line
886 // change. This is used so that the line marker comes out in -E mode for
887 // example.
888 if (Callbacks) {
889 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
890 if (IsFileEntry)
891 Reason = PPCallbacks::EnterFile;
892 else if (IsFileExit)
893 Reason = PPCallbacks::ExitFile;
894 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
895 if (IsExternCHeader)
896 FileKind = SrcMgr::C_ExternCSystem;
897 else if (IsSystemHeader)
898 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner86d0ef72010-04-14 04:28:50 +0000900 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000901 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000902}
903
904
Chris Lattner099dd052009-01-26 05:30:54 +0000905/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
906///
Mike Stump1eb44332009-09-09 15:08:12 +0000907void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000908 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000909 // PTH doesn't emit #warning or #error directives.
910 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000911 return CurPTHLexer->DiscardToEndOfLine();
912
Chris Lattner141e71f2008-03-09 01:54:53 +0000913 // Read the rest of the line raw. We do this because we don't want macros
914 // to be expanded and we don't require that the tokens be valid preprocessing
915 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
916 // collapse multiple consequtive white space between tokens, but this isn't
917 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000918 std::string Message = CurLexer->ReadToEndOfLine();
919 if (isWarning)
920 Diag(Tok, diag::pp_hash_warning) << Message;
921 else
922 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000923}
924
925/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
926///
927void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
928 // Yes, this directive is an extension.
929 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Chris Lattner141e71f2008-03-09 01:54:53 +0000931 // Read the string argument.
932 Token StrTok;
933 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattner141e71f2008-03-09 01:54:53 +0000935 // If the token kind isn't a string, it's a malformed directive.
936 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000937 StrTok.isNot(tok::wide_string_literal)) {
938 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000939 if (StrTok.isNot(tok::eom))
940 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000941 return;
942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Chris Lattner141e71f2008-03-09 01:54:53 +0000944 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000945 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000946
Douglas Gregor453091c2010-03-16 22:30:13 +0000947 if (Callbacks) {
948 bool Invalid = false;
949 std::string Str = getSpelling(StrTok, &Invalid);
950 if (!Invalid)
951 Callbacks->Ident(Tok.getLocation(), Str);
952 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000953}
954
955//===----------------------------------------------------------------------===//
956// Preprocessor Include Directive Handling.
957//===----------------------------------------------------------------------===//
958
959/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
960/// checked and spelled filename, e.g. as an operand of #include. This returns
961/// true if the input filename was in <>'s or false if it were in ""'s. The
962/// caller is expected to provide a buffer that is large enough to hold the
963/// spelling of the filename, but is also expected to handle the case when
964/// this method decides to use a different buffer.
965bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000966 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000967 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000968 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattner141e71f2008-03-09 01:54:53 +0000970 // Make sure the filename is <x> or "x".
971 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000972 if (Buffer[0] == '<') {
973 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000974 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000975 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000976 return true;
977 }
978 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +0000979 } else if (Buffer[0] == '"') {
980 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000981 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000982 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000983 return true;
984 }
985 isAngled = false;
986 } else {
987 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000988 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000989 return true;
990 }
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner141e71f2008-03-09 01:54:53 +0000992 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +0000993 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000994 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000995 Buffer = llvm::StringRef();
996 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000997 }
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner141e71f2008-03-09 01:54:53 +0000999 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001000 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001001 return isAngled;
1002}
1003
1004/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1005/// from a macro as multiple tokens, which need to be glued together. This
1006/// occurs for code like:
1007/// #define FOO <a/b.h>
1008/// #include FOO
1009/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1010///
1011/// This code concatenates and consumes tokens up to the '>' token. It returns
1012/// false if the > was found, otherwise it returns true if it finds and consumes
1013/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +00001014bool Preprocessor::ConcatenateIncludeName(
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001015 llvm::SmallString<128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001016 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001017
John Thompsona28cc092009-10-30 13:49:06 +00001018 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001019 while (CurTok.isNot(tok::eom)) {
1020 // Append the spelling of this token to the buffer. If there was a space
1021 // before it, add it now.
1022 if (CurTok.hasLeadingSpace())
1023 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Chris Lattner141e71f2008-03-09 01:54:53 +00001025 // Get the spelling of the token, directly into FilenameBuffer if possible.
1026 unsigned PreAppendSize = FilenameBuffer.size();
1027 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Chris Lattner141e71f2008-03-09 01:54:53 +00001029 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001030 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Chris Lattner141e71f2008-03-09 01:54:53 +00001032 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1033 if (BufPtr != &FilenameBuffer[PreAppendSize])
1034 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Chris Lattner141e71f2008-03-09 01:54:53 +00001036 // Resize FilenameBuffer to the correct size.
1037 if (CurTok.getLength() != ActualLen)
1038 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner141e71f2008-03-09 01:54:53 +00001040 // If we found the '>' marker, return success.
1041 if (CurTok.is(tok::greater))
1042 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001043
John Thompsona28cc092009-10-30 13:49:06 +00001044 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001045 }
1046
1047 // If we hit the eom marker, emit an error and return true so that the caller
1048 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001049 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001050 return true;
1051}
1052
1053/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1054/// file to be included from the lexer, then include it! This is a common
1055/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001056/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001057/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001058void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1059 const DirectoryLookup *LookupFrom,
1060 bool isImport) {
1061
1062 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001063 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Chris Lattner141e71f2008-03-09 01:54:53 +00001065 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001066 llvm::SmallString<128> FilenameBuffer;
1067 llvm::StringRef Filename;
Chris Lattner141e71f2008-03-09 01:54:53 +00001068
1069 switch (FilenameTok.getKind()) {
1070 case tok::eom:
1071 // If the token kind is EOM, the error has already been diagnosed.
1072 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Chris Lattner141e71f2008-03-09 01:54:53 +00001074 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001075 case tok::string_literal:
1076 Filename = getSpelling(FilenameTok, FilenameBuffer);
Chris Lattner141e71f2008-03-09 01:54:53 +00001077 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Chris Lattner141e71f2008-03-09 01:54:53 +00001079 case tok::less:
1080 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1081 // case, glue the tokens together into FilenameBuffer and interpret those.
1082 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001083 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001084 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001085 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001086 break;
1087 default:
1088 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1089 DiscardUntilEndOfDirective();
1090 return;
1091 }
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001093 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001094 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001095 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1096 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001097 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001098 DiscardUntilEndOfDirective();
1099 return;
1100 }
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001102 // Verify that there is nothing after the filename, other than EOM. Note that
1103 // we allow macros that expand to nothing after the filename, because this
1104 // falls into the category of "#include pp-tokens new-line" specified in
1105 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001106 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001107
1108 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001109 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1110 Diag(FilenameTok, diag::err_pp_include_too_deep);
1111 return;
1112 }
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Chris Lattner141e71f2008-03-09 01:54:53 +00001114 // Search include directories.
1115 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +00001116 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001117 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001118 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001119 return;
1120 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001121
Chris Lattner72181832008-09-26 20:12:23 +00001122 // The #included file will be considered to be a system header if either it is
1123 // in a system include directory, or if the #includer is a system include
1124 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001125 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001126 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001127 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001129 // Ask HeaderInfo if we should enter this #include file. If not, #including
1130 // this file will have no effect.
1131 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001132 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001133 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001134 return;
1135 }
1136
Chris Lattner141e71f2008-03-09 01:54:53 +00001137 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001138 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1139 FileCharacter);
1140 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001141 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001142 return;
1143 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001144
1145 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001146 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001147}
1148
1149/// HandleIncludeNextDirective - Implements #include_next.
1150///
1151void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1152 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Chris Lattner141e71f2008-03-09 01:54:53 +00001154 // #include_next is like #include, except that we start searching after
1155 // the current found directory. If we can't do this, issue a
1156 // diagnostic.
1157 const DirectoryLookup *Lookup = CurDirLookup;
1158 if (isInPrimaryFile()) {
1159 Lookup = 0;
1160 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1161 } else if (Lookup == 0) {
1162 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1163 } else {
1164 // Start looking up in the next directory.
1165 ++Lookup;
1166 }
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Chris Lattner141e71f2008-03-09 01:54:53 +00001168 return HandleIncludeDirective(IncludeNextTok, Lookup);
1169}
1170
1171/// HandleImportDirective - Implements #import.
1172///
1173void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001174 if (!Features.ObjC1) // #import is standard for ObjC.
1175 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Chris Lattner141e71f2008-03-09 01:54:53 +00001177 return HandleIncludeDirective(ImportTok, 0, true);
1178}
1179
Chris Lattnerde076652009-04-08 18:46:40 +00001180/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1181/// pseudo directive in the predefines buffer. This handles it by sucking all
1182/// tokens through the preprocessor and discarding them (only keeping the side
1183/// effects on the preprocessor).
1184void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1185 // This directive should only occur in the predefines buffer. If not, emit an
1186 // error and reject it.
1187 SourceLocation Loc = IncludeMacrosTok.getLocation();
1188 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1189 Diag(IncludeMacrosTok.getLocation(),
1190 diag::pp_include_macros_out_of_predefines);
1191 DiscardUntilEndOfDirective();
1192 return;
1193 }
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Chris Lattnerfd105112009-04-08 20:53:24 +00001195 // Treat this as a normal #include for checking purposes. If this is
1196 // successful, it will push a new lexer onto the include stack.
1197 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Chris Lattnerfd105112009-04-08 20:53:24 +00001199 Token TmpTok;
1200 do {
1201 Lex(TmpTok);
1202 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1203 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001204}
1205
Chris Lattner141e71f2008-03-09 01:54:53 +00001206//===----------------------------------------------------------------------===//
1207// Preprocessor Macro Directive Handling.
1208//===----------------------------------------------------------------------===//
1209
1210/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1211/// definition has just been read. Lex the rest of the arguments and the
1212/// closing ), updating MI with what we learn. Return true if an error occurs
1213/// parsing the arg list.
1214bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1215 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Chris Lattner141e71f2008-03-09 01:54:53 +00001217 Token Tok;
1218 while (1) {
1219 LexUnexpandedToken(Tok);
1220 switch (Tok.getKind()) {
1221 case tok::r_paren:
1222 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001223 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001224 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001225 // Otherwise we have #define FOO(A,)
1226 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1227 return true;
1228 case tok::ellipsis: // #define X(... -> C99 varargs
1229 // Warn if use of C99 feature in non-C99 mode.
1230 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1231
1232 // Lex the token after the identifier.
1233 LexUnexpandedToken(Tok);
1234 if (Tok.isNot(tok::r_paren)) {
1235 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1236 return true;
1237 }
1238 // Add the __VA_ARGS__ identifier as an argument.
1239 Arguments.push_back(Ident__VA_ARGS__);
1240 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001241 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001242 return false;
1243 case tok::eom: // #define X(
1244 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1245 return true;
1246 default:
1247 // Handle keywords and identifiers here to accept things like
1248 // #define Foo(for) for.
1249 IdentifierInfo *II = Tok.getIdentifierInfo();
1250 if (II == 0) {
1251 // #define X(1
1252 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1253 return true;
1254 }
1255
1256 // If this is already used as an argument, it is used multiple times (e.g.
1257 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001258 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001259 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001260 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001261 return true;
1262 }
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Chris Lattner141e71f2008-03-09 01:54:53 +00001264 // Add the argument to the macro info.
1265 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Chris Lattner141e71f2008-03-09 01:54:53 +00001267 // Lex the token after the identifier.
1268 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Chris Lattner141e71f2008-03-09 01:54:53 +00001270 switch (Tok.getKind()) {
1271 default: // #define X(A B
1272 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1273 return true;
1274 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001275 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001276 return false;
1277 case tok::comma: // #define X(A,
1278 break;
1279 case tok::ellipsis: // #define X(A... -> GCC extension
1280 // Diagnose extension.
1281 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Chris Lattner141e71f2008-03-09 01:54:53 +00001283 // Lex the token after the identifier.
1284 LexUnexpandedToken(Tok);
1285 if (Tok.isNot(tok::r_paren)) {
1286 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1287 return true;
1288 }
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Chris Lattner141e71f2008-03-09 01:54:53 +00001290 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001291 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001292 return false;
1293 }
1294 }
1295 }
1296}
1297
1298/// HandleDefineDirective - Implements #define. This consumes the entire macro
1299/// line then lets the caller lex the next real token.
1300void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1301 ++NumDefined;
1302
1303 Token MacroNameTok;
1304 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Chris Lattner141e71f2008-03-09 01:54:53 +00001306 // Error reading macro name? If so, diagnostic already issued.
1307 if (MacroNameTok.is(tok::eom))
1308 return;
1309
Chris Lattner2451b522009-04-21 04:46:33 +00001310 Token LastTok = MacroNameTok;
1311
Chris Lattner141e71f2008-03-09 01:54:53 +00001312 // If we are supposed to keep comments in #defines, reenable comment saving
1313 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001314 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Chris Lattner141e71f2008-03-09 01:54:53 +00001316 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001317 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Chris Lattner141e71f2008-03-09 01:54:53 +00001319 Token Tok;
1320 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Chris Lattner141e71f2008-03-09 01:54:53 +00001322 // If this is a function-like macro definition, parse the argument list,
1323 // marking each of the identifiers as being used as macro arguments. Also,
1324 // check other constraints on the first token of the macro body.
1325 if (Tok.is(tok::eom)) {
1326 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001327 } else if (Tok.hasLeadingSpace()) {
1328 // This is a normal token with leading space. Clear the leading space
1329 // marker on the first token to get proper expansion.
1330 Tok.clearFlag(Token::LeadingSpace);
1331 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001332 // This is a function-like macro definition. Read the argument list.
1333 MI->setIsFunctionLike();
1334 if (ReadMacroDefinitionArgList(MI)) {
1335 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001336 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001337 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001338 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001339 DiscardUntilEndOfDirective();
1340 return;
1341 }
1342
Chris Lattner8fde5972009-04-19 18:26:34 +00001343 // If this is a definition of a variadic C99 function-like macro, not using
1344 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Chris Lattner8fde5972009-04-19 18:26:34 +00001346 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1347 // This gets unpoisoned where it is allowed.
1348 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1349 if (MI->isC99Varargs())
1350 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Chris Lattner141e71f2008-03-09 01:54:53 +00001352 // Read the first token after the arg list for down below.
1353 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001354 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001355 // C99 requires whitespace between the macro definition and the body. Emit
1356 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001357 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001358 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001359 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1360 // first character of a replacement list is not a character required by
1361 // subclause 5.2.1, then there shall be white-space separation between the
1362 // identifier and the replacement list.". 5.2.1 lists this set:
1363 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1364 // is irrelevant here.
1365 bool isInvalid = false;
1366 if (Tok.is(tok::at)) // @ is not in the list above.
1367 isInvalid = true;
1368 else if (Tok.is(tok::unknown)) {
1369 // If we have an unknown token, it is something strange like "`". Since
1370 // all of valid characters would have lexed into a single character
1371 // token of some sort, we know this is not a valid case.
1372 isInvalid = true;
1373 }
1374 if (isInvalid)
1375 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1376 else
1377 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001378 }
Chris Lattner2451b522009-04-21 04:46:33 +00001379
1380 if (!Tok.is(tok::eom))
1381 LastTok = Tok;
1382
Chris Lattner141e71f2008-03-09 01:54:53 +00001383 // Read the rest of the macro body.
1384 if (MI->isObjectLike()) {
1385 // Object-like macros are very simple, just read their body.
1386 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001387 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001388 MI->AddTokenToBody(Tok);
1389 // Get the next token of the macro.
1390 LexUnexpandedToken(Tok);
1391 }
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Chris Lattner141e71f2008-03-09 01:54:53 +00001393 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001394 // Otherwise, read the body of a function-like macro. While we are at it,
1395 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1396 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001397 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001398 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001399
Chris Lattner141e71f2008-03-09 01:54:53 +00001400 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001401 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Chris Lattner141e71f2008-03-09 01:54:53 +00001403 // Get the next token of the macro.
1404 LexUnexpandedToken(Tok);
1405 continue;
1406 }
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Chris Lattner141e71f2008-03-09 01:54:53 +00001408 // Get the next token of the macro.
1409 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Chris Lattner32404692009-05-25 17:16:10 +00001411 // Check for a valid macro arg identifier.
1412 if (Tok.getIdentifierInfo() == 0 ||
1413 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1414
1415 // If this is assembler-with-cpp mode, we accept random gibberish after
1416 // the '#' because '#' is often a comment character. However, change
1417 // the kind of the token to tok::unknown so that the preprocessor isn't
1418 // confused.
1419 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1420 LastTok.setKind(tok::unknown);
1421 } else {
1422 Diag(Tok, diag::err_pp_stringize_not_parameter);
1423 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Chris Lattner32404692009-05-25 17:16:10 +00001425 // Disable __VA_ARGS__ again.
1426 Ident__VA_ARGS__->setIsPoisoned(true);
1427 return;
1428 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001429 }
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Chris Lattner32404692009-05-25 17:16:10 +00001431 // Things look ok, add the '#' and param name tokens to the macro.
1432 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001433 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001434 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Chris Lattner141e71f2008-03-09 01:54:53 +00001436 // Get the next token of the macro.
1437 LexUnexpandedToken(Tok);
1438 }
1439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
1441
Chris Lattner141e71f2008-03-09 01:54:53 +00001442 // Disable __VA_ARGS__ again.
1443 Ident__VA_ARGS__->setIsPoisoned(true);
1444
1445 // Check that there is no paste (##) operator at the begining or end of the
1446 // replacement list.
1447 unsigned NumTokens = MI->getNumTokens();
1448 if (NumTokens != 0) {
1449 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1450 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001451 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001452 return;
1453 }
1454 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1455 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001456 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001457 return;
1458 }
1459 }
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Chris Lattner141e71f2008-03-09 01:54:53 +00001461 // If this is the primary source file, remember that this macro hasn't been
1462 // used yet.
1463 if (isInPrimaryFile())
1464 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001465
1466 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Chris Lattner141e71f2008-03-09 01:54:53 +00001468 // Finally, if this identifier already had a macro defined for it, verify that
1469 // the macro bodies are identical and free the old definition.
1470 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001471 // It is very common for system headers to have tons of macro redefinitions
1472 // and for warnings to be disabled in system headers. If this is the case,
1473 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001474 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001475 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1476 if (!OtherMI->isUsed())
1477 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001478
Chris Lattnerf47724b2010-08-17 15:55:45 +00001479 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001480 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001481 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001482 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001483 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1484 << MacroNameTok.getIdentifierInfo();
1485 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1486 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001487 }
Ted Kremenek0ea76722008-12-15 19:56:42 +00001488 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001489 }
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Chris Lattner141e71f2008-03-09 01:54:53 +00001491 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001493 // If the callbacks want to know, tell them about the macro definition.
1494 if (Callbacks)
1495 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001496}
1497
1498/// HandleUndefDirective - Implements #undef.
1499///
1500void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1501 ++NumUndefined;
1502
1503 Token MacroNameTok;
1504 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Chris Lattner141e71f2008-03-09 01:54:53 +00001506 // Error reading macro name? If so, diagnostic already issued.
1507 if (MacroNameTok.is(tok::eom))
1508 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Chris Lattner141e71f2008-03-09 01:54:53 +00001510 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001511 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Chris Lattner141e71f2008-03-09 01:54:53 +00001513 // Okay, we finally have a valid identifier to undef.
1514 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Chris Lattner141e71f2008-03-09 01:54:53 +00001516 // If the macro is not defined, this is a noop undef, just return.
1517 if (MI == 0) return;
1518
1519 if (!MI->isUsed())
1520 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001521
1522 // If the callbacks want to know, tell them about the macro #undef.
1523 if (Callbacks)
Benjamin Kramer2f054492010-08-07 22:27:00 +00001524 Callbacks->MacroUndefined(MacroNameTok.getLocation(),
1525 MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001526
Chris Lattner141e71f2008-03-09 01:54:53 +00001527 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001528 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001529 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1530}
1531
1532
1533//===----------------------------------------------------------------------===//
1534// Preprocessor Conditional Directive Handling.
1535//===----------------------------------------------------------------------===//
1536
1537/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1538/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1539/// if any tokens have been returned or pp-directives activated before this
1540/// #ifndef has been lexed.
1541///
1542void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1543 bool ReadAnyTokensBeforeDirective) {
1544 ++NumIf;
1545 Token DirectiveTok = Result;
1546
1547 Token MacroNameTok;
1548 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Chris Lattner141e71f2008-03-09 01:54:53 +00001550 // Error reading macro name? If so, diagnostic already issued.
1551 if (MacroNameTok.is(tok::eom)) {
1552 // Skip code until we get to #endif. This helps with recovery by not
1553 // emitting an error when the #endif is reached.
1554 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1555 /*Foundnonskip*/false, /*FoundElse*/false);
1556 return;
1557 }
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Chris Lattner141e71f2008-03-09 01:54:53 +00001559 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001560 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001561
Chris Lattner13d283d2010-02-12 08:03:27 +00001562 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1563 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001564
Ted Kremenek60e45d42008-11-18 00:34:22 +00001565 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001566 // If the start of a top-level #ifdef and if the macro is not defined,
1567 // inform MIOpt that this might be the start of a proper include guard.
1568 // Otherwise it is some other form of unknown conditional which we can't
1569 // handle.
1570 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001571 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001572 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001573 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001574 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001575 }
1576
Chris Lattner141e71f2008-03-09 01:54:53 +00001577 // If there is a macro, process it.
1578 if (MI) // Mark it used.
1579 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Chris Lattner141e71f2008-03-09 01:54:53 +00001581 // Should we include the stuff contained by this directive?
1582 if (!MI == isIfndef) {
1583 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001584 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1585 /*wasskip*/false, /*foundnonskip*/true,
1586 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001587 } else {
1588 // No, skip the contents of this block and return the first token after it.
1589 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001590 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001591 /*FoundElse*/false);
1592 }
1593}
1594
1595/// HandleIfDirective - Implements the #if directive.
1596///
1597void Preprocessor::HandleIfDirective(Token &IfToken,
1598 bool ReadAnyTokensBeforeDirective) {
1599 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Chris Lattner141e71f2008-03-09 01:54:53 +00001601 // Parse and evaluation the conditional expression.
1602 IdentifierInfo *IfNDefMacro = 0;
1603 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Nuno Lopes0049db62008-06-01 18:31:24 +00001605
1606 // If this condition is equivalent to #ifndef X, and if this is the first
1607 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001608 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001609 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001610 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001611 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001612 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001613 }
1614
Chris Lattner141e71f2008-03-09 01:54:53 +00001615 // Should we include the stuff contained by this directive?
1616 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001617 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001618 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001619 /*foundnonskip*/true, /*foundelse*/false);
1620 } else {
1621 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001622 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001623 /*FoundElse*/false);
1624 }
1625}
1626
1627/// HandleEndifDirective - Implements the #endif directive.
1628///
1629void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1630 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Chris Lattner141e71f2008-03-09 01:54:53 +00001632 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001633 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Chris Lattner141e71f2008-03-09 01:54:53 +00001635 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001636 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001637 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001638 Diag(EndifToken, diag::err_pp_endif_without_if);
1639 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Chris Lattner141e71f2008-03-09 01:54:53 +00001642 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001643 if (CurPPLexer->getConditionalStackDepth() == 0)
1644 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Ted Kremenek60e45d42008-11-18 00:34:22 +00001646 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001647 "This code should only be reachable in the non-skipping case!");
1648}
1649
1650
1651void Preprocessor::HandleElseDirective(Token &Result) {
1652 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Chris Lattner141e71f2008-03-09 01:54:53 +00001654 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001655 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Chris Lattner141e71f2008-03-09 01:54:53 +00001657 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001658 if (CurPPLexer->popConditionalLevel(CI)) {
1659 Diag(Result, diag::pp_err_else_without_if);
1660 return;
1661 }
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Chris Lattner141e71f2008-03-09 01:54:53 +00001663 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001664 if (CurPPLexer->getConditionalStackDepth() == 0)
1665 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001666
1667 // If this is a #else with a #else before it, report the error.
1668 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Chris Lattner141e71f2008-03-09 01:54:53 +00001670 // Finally, skip the rest of the contents of this block and return the first
1671 // token after it.
1672 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1673 /*FoundElse*/true);
1674}
1675
1676void Preprocessor::HandleElifDirective(Token &ElifToken) {
1677 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Chris Lattner141e71f2008-03-09 01:54:53 +00001679 // #elif directive in a non-skipping conditional... start skipping.
1680 // We don't care what the condition is, because we will always skip it (since
1681 // the block immediately before it was included).
1682 DiscardUntilEndOfDirective();
1683
1684 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001685 if (CurPPLexer->popConditionalLevel(CI)) {
1686 Diag(ElifToken, diag::pp_err_elif_without_if);
1687 return;
1688 }
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Chris Lattner141e71f2008-03-09 01:54:53 +00001690 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001691 if (CurPPLexer->getConditionalStackDepth() == 0)
1692 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Chris Lattner141e71f2008-03-09 01:54:53 +00001694 // If this is a #elif with a #else before it, report the error.
1695 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1696
1697 // Finally, skip the rest of the contents of this block and return the first
1698 // token after it.
1699 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1700 /*FoundElse*/CI.FoundElse);
1701}