blob: 8da7def9ed4d2303fdc3fcc89a3d01a265b0bcdd [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Chris Lattner359cc442009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf44e8542010-08-24 19:08:16 +000019#include "clang/Lex/CodeCompletionHandler.h"
Chris Lattner6e290142009-11-30 04:18:44 +000020#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000022#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000023using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// Utility Methods for Preprocessor Directive Handling.
27//===----------------------------------------------------------------------===//
28
Chris Lattnerf47724b2010-08-17 15:55:45 +000029MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenek0ea76722008-12-15 19:56:42 +000030 MacroInfo *MI;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Ted Kremenek0ea76722008-12-15 19:56:42 +000032 if (!MICache.empty()) {
33 MI = MICache.back();
34 MICache.pop_back();
Chris Lattner0301b3f2009-02-20 22:19:20 +000035 } else
36 MI = (MacroInfo*) BP.Allocate<MacroInfo>();
Chris Lattnerf47724b2010-08-17 15:55:45 +000037 return MI;
38}
39
40MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
41 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000042 new (MI) MacroInfo(L);
43 return MI;
44}
45
Chris Lattnerf47724b2010-08-17 15:55:45 +000046MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
47 MacroInfo *MI = AllocateMacroInfo();
48 new (MI) MacroInfo(MacroToClone, BP);
49 return MI;
50}
51
Chris Lattner0301b3f2009-02-20 22:19:20 +000052/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
53/// be reused for allocating new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000054void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Chris Lattner0301b3f2009-02-20 22:19:20 +000055 MICache.push_back(MI);
Chris Lattner2c1ab902010-08-18 16:08:51 +000056 MI->FreeArgumentList();
Chris Lattner0301b3f2009-02-20 22:19:20 +000057}
58
59
Chris Lattner141e71f2008-03-09 01:54:53 +000060/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
61/// current line until the tok::eom token is found.
62void Preprocessor::DiscardUntilEndOfDirective() {
63 Token Tmp;
64 do {
65 LexUnexpandedToken(Tmp);
66 } while (Tmp.isNot(tok::eom));
67}
68
Chris Lattner141e71f2008-03-09 01:54:53 +000069/// ReadMacroName - Lex and validate a macro name, which occurs after a
70/// #define or #undef. This sets the token kind to eom and discards the rest
71/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
72/// this is due to a a #define, 2 if #undef directive, 0 if it is something
73/// else (e.g. #ifdef).
74void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
75 // Read the token, don't allow macro expansion on it.
76 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Douglas Gregor1fbb4472010-08-24 20:21:13 +000078 if (MacroNameTok.is(tok::code_completion)) {
79 if (CodeComplete)
80 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
81 LexUnexpandedToken(MacroNameTok);
82 return;
83 }
84
Chris Lattner141e71f2008-03-09 01:54:53 +000085 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000086 if (MacroNameTok.is(tok::eom)) {
87 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
88 return;
89 }
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattner141e71f2008-03-09 01:54:53 +000091 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
92 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +000093 bool Invalid = false;
94 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
95 if (Invalid)
96 return;
97
Chris Lattner9485d232008-12-13 20:12:40 +000098 const IdentifierInfo &Info = Identifiers.get(Spelling);
99 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000100 // C++ 2.5p2: Alternative tokens behave the same as its primary token
101 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000102 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +0000103 else
104 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
105 // Fall through on error.
106 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
107 // Error if defining "defined": C99 6.10.8.4.
108 Diag(MacroNameTok, diag::err_defined_macro_name);
109 } else if (isDefineUndef && II->hasMacroDefinition() &&
110 getMacroInfo(II)->isBuiltinMacro()) {
111 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
112 if (isDefineUndef == 1)
113 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
114 else
115 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
116 } else {
117 // Okay, we got a good identifier node. Return it.
118 return;
119 }
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattner141e71f2008-03-09 01:54:53 +0000121 // Invalid macro name, read and discard the rest of the line. Then set the
122 // token kind to tok::eom.
123 MacroNameTok.setKind(tok::eom);
124 return DiscardUntilEndOfDirective();
125}
126
127/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattnerab82f412009-04-17 23:30:53 +0000128/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
129/// true, then we consider macros that expand to zero tokens as being ok.
130void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000131 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000132 // Lex unexpanded tokens for most directives: macros might expand to zero
133 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
134 // #line) allow empty macros.
135 if (EnableMacros)
136 Lex(Tmp);
137 else
138 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Chris Lattner141e71f2008-03-09 01:54:53 +0000140 // There should be no tokens after the directive, but we allow them as an
141 // extension.
142 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
143 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Chris Lattner141e71f2008-03-09 01:54:53 +0000145 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000146 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
147 // because it is more trouble than it is worth to insert /**/ and check that
148 // there is no /**/ in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000149 FixItHint Hint;
Chris Lattner959875a2009-04-14 05:15:20 +0000150 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
Douglas Gregor849b2432010-03-31 17:46:05 +0000151 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
152 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000153 DiscardUntilEndOfDirective();
154 }
155}
156
157
158
159/// SkipExcludedConditionalBlock - We just read a #if or related directive and
160/// decided that the subsequent tokens are in the #if'd out portion of the
161/// file. Lex the rest of the file, until we see an #endif. If
162/// FoundNonSkipPortion is true, then we have already emitted code for part of
163/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
164/// is true, then #else directives are ok, if not, then we have already seen one
165/// so a #else directive is a duplicate. When this returns, the caller can lex
166/// the first valid token.
167void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
168 bool FoundNonSkipPortion,
169 bool FoundElse) {
170 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000171 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000172
Ted Kremenek60e45d42008-11-18 00:34:22 +0000173 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000174 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Ted Kremenek268ee702008-12-12 18:34:08 +0000176 if (CurPTHLexer) {
177 PTHSkipExcludedConditionalBlock();
178 return;
179 }
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattner141e71f2008-03-09 01:54:53 +0000181 // Enter raw mode to disable identifier lookup (and thus macro expansion),
182 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000183 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000184 Token Tok;
185 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000186 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Douglas Gregorf44e8542010-08-24 19:08:16 +0000188 if (Tok.is(tok::code_completion)) {
189 if (CodeComplete)
190 CodeComplete->CodeCompleteInConditionalExclusion();
191 continue;
192 }
193
Chris Lattner141e71f2008-03-09 01:54:53 +0000194 // If this is the end of the buffer, we have an error.
195 if (Tok.is(tok::eof)) {
196 // Emit errors for each unterminated conditional on the stack, including
197 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000198 while (!CurPPLexer->ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000199 if (!isCodeCompletionFile(Tok.getLocation()))
200 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
201 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000202 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000203 }
204
Chris Lattner141e71f2008-03-09 01:54:53 +0000205 // Just return and let the caller lex after this #include.
206 break;
207 }
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Chris Lattner141e71f2008-03-09 01:54:53 +0000209 // If this token is not a preprocessor directive, just skip it.
210 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
211 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattner141e71f2008-03-09 01:54:53 +0000213 // We just parsed a # character at the start of a line, so we're in
214 // directive mode. Tell the lexer this so any newlines we see will be
215 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000216 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000217 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000218
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattner141e71f2008-03-09 01:54:53 +0000220 // Read the next token, the directive flavor.
221 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattner141e71f2008-03-09 01:54:53 +0000223 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
224 // something bogus), skip it.
225 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000226 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000227 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000228 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000229 continue;
230 }
231
232 // If the first letter isn't i or e, it isn't intesting to us. We know that
233 // this is safe in the face of spelling differences, because there is no way
234 // to spell an i/e in a strange way that is another letter. Skipping this
235 // allows us to avoid looking up the identifier info for #define/#undef and
236 // other common directives.
Douglas Gregora5430162010-03-16 20:46:42 +0000237 bool Invalid = false;
238 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation(),
239 &Invalid);
240 if (Invalid)
241 return;
242
Chris Lattner141e71f2008-03-09 01:54:53 +0000243 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000244 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000245 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000246 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000247 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000248 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000249 continue;
250 }
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattner141e71f2008-03-09 01:54:53 +0000252 // Get the identifier name without trigraphs or embedded newlines. Note
253 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
254 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000255 char DirectiveBuf[20];
256 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000257 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000258 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000259 } else {
260 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000261 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000262 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000263 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000264 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000265 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000266 continue;
267 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000268 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
269 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000270 }
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000272 if (Directive.startswith("if")) {
273 llvm::StringRef Sub = Directive.substr(2);
274 if (Sub.empty() || // "if"
275 Sub == "def" || // "ifdef"
276 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000277 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
278 // bother parsing the condition.
279 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000280 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000281 /*foundnonskip*/false,
282 /*fnddelse*/false);
283 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000284 } else if (Directive[0] == 'e') {
285 llvm::StringRef Sub = Directive.substr(1);
286 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000287 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000288 PPConditionalInfo CondInfo;
289 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000290 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000291 InCond = InCond; // Silence warning in no-asserts mode.
292 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattner141e71f2008-03-09 01:54:53 +0000294 // If we popped the outermost skipping block, we're done skipping!
295 if (!CondInfo.WasSkipping)
296 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000297 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000298 // #else directive in a skipping conditional. If not in some other
299 // skipping conditional, and if #else hasn't already been seen, enter it
300 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000301 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000302 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattner141e71f2008-03-09 01:54:53 +0000304 // If this is a #else with a #else before it, report the error.
305 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Chris Lattner141e71f2008-03-09 01:54:53 +0000307 // Note that we've seen a #else in this conditional.
308 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Chris Lattner141e71f2008-03-09 01:54:53 +0000310 // If the conditional is at the top level, and the #if block wasn't
311 // entered, enter the #else block now.
312 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
313 CondInfo.FoundNonSkip = true;
314 break;
315 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000316 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000317 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000318
319 bool ShouldEnter;
320 // If this is in a skipping block or if we're already handled this #if
321 // block, don't bother parsing the condition.
322 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
323 DiscardUntilEndOfDirective();
324 ShouldEnter = false;
325 } else {
326 // Restore the value of LexingRawMode so that identifiers are
327 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000328 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
329 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000330 IdentifierInfo *IfNDefMacro = 0;
331 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000332 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000333 }
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Chris Lattner141e71f2008-03-09 01:54:53 +0000335 // If this is a #elif with a #else before it, report the error.
336 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Chris Lattner141e71f2008-03-09 01:54:53 +0000338 // If this condition is true, enter it!
339 if (ShouldEnter) {
340 CondInfo.FoundNonSkip = true;
341 break;
342 }
343 }
344 }
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Ted Kremenek60e45d42008-11-18 00:34:22 +0000346 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000347 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000348 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000349 }
350
351 // Finally, if we are out of the conditional (saw an #endif or ran off the end
352 // of the file, just stop skipping and return to lexing whatever came after
353 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000354 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000355}
356
Ted Kremenek268ee702008-12-12 18:34:08 +0000357void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000358
359 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000360 assert(CurPTHLexer);
361 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Ted Kremenek268ee702008-12-12 18:34:08 +0000363 // Skip to the next '#else', '#elif', or #endif.
364 if (CurPTHLexer->SkipBlock()) {
365 // We have reached an #endif. Both the '#' and 'endif' tokens
366 // have been consumed by the PTHLexer. Just pop off the condition level.
367 PPConditionalInfo CondInfo;
368 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
369 InCond = InCond; // Silence warning in no-asserts mode.
370 assert(!InCond && "Can't be skipping if not in a conditional!");
371 break;
372 }
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Ted Kremenek268ee702008-12-12 18:34:08 +0000374 // We have reached a '#else' or '#elif'. Lex the next token to get
375 // the directive flavor.
376 Token Tok;
377 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Ted Kremenek268ee702008-12-12 18:34:08 +0000379 // We can actually look up the IdentifierInfo here since we aren't in
380 // raw mode.
381 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
382
383 if (K == tok::pp_else) {
384 // #else: Enter the else condition. We aren't in a nested condition
385 // since we skip those. We're always in the one matching the last
386 // blocked we skipped.
387 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
388 // Note that we've seen a #else in this conditional.
389 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Ted Kremenek268ee702008-12-12 18:34:08 +0000391 // If the #if block wasn't entered then enter the #else block now.
392 if (!CondInfo.FoundNonSkip) {
393 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000395 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000396 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000397 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000398 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Ted Kremenek268ee702008-12-12 18:34:08 +0000400 break;
401 }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Ted Kremenek268ee702008-12-12 18:34:08 +0000403 // Otherwise skip this block.
404 continue;
405 }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Ted Kremenek268ee702008-12-12 18:34:08 +0000407 assert(K == tok::pp_elif);
408 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
409
410 // If this is a #elif with a #else before it, report the error.
411 if (CondInfo.FoundElse)
412 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Ted Kremenek268ee702008-12-12 18:34:08 +0000414 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000415 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000416 if (CondInfo.FoundNonSkip)
417 continue;
418
419 // Evaluate the condition of the #elif.
420 IdentifierInfo *IfNDefMacro = 0;
421 CurPTHLexer->ParsingPreprocessorDirective = true;
422 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
423 CurPTHLexer->ParsingPreprocessorDirective = false;
424
425 // If this condition is true, enter it!
426 if (ShouldEnter) {
427 CondInfo.FoundNonSkip = true;
428 break;
429 }
430
431 // Otherwise, skip this block and go to the next one.
432 continue;
433 }
434}
435
Chris Lattner10725092008-03-09 04:17:44 +0000436/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
437/// return null on failure. isAngled indicates whether the file reference is
438/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnera1394812010-01-10 01:35:12 +0000439const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattner10725092008-03-09 04:17:44 +0000440 bool isAngled,
441 const DirectoryLookup *FromDir,
442 const DirectoryLookup *&CurDir) {
443 // If the header lookup mechanism may be relative to the current file, pass in
444 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000445 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000446 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000447 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000448 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000450 // If there is no file entry associated with this file, it must be the
451 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000452 // it won't be scanned for preprocessor directives. If we have the
453 // predefines buffer, resolve #include references (which come from the
454 // -include command line argument) as if they came from the main file, this
455 // affects file lookup etc.
456 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000457 FID = SourceMgr.getMainFileID();
458 CurFileEnt = SourceMgr.getFileEntryForID(FID);
459 }
Chris Lattner10725092008-03-09 04:17:44 +0000460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner10725092008-03-09 04:17:44 +0000462 // Do a standard file entry lookup.
463 CurDir = CurDirLookup;
464 const FileEntry *FE =
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000465 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000466 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Chris Lattner10725092008-03-09 04:17:44 +0000468 // Otherwise, see if this is a subframework header. If so, this is relative
469 // to one of the headers on the #include stack. Walk the list of the current
470 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000471 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000472 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000473 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000474 return FE;
475 }
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Chris Lattner10725092008-03-09 04:17:44 +0000477 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
478 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000479 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000480 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000481 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000482 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000483 return FE;
484 }
485 }
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Chris Lattner10725092008-03-09 04:17:44 +0000487 // Otherwise, we really couldn't find the file.
488 return 0;
489}
490
Chris Lattner141e71f2008-03-09 01:54:53 +0000491
492//===----------------------------------------------------------------------===//
493// Preprocessor Directive Handling.
494//===----------------------------------------------------------------------===//
495
496/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000497/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000498/// lexer/preprocessor state, and advances the lexer(s) so that the next token
499/// read is the correct one.
500void Preprocessor::HandleDirective(Token &Result) {
501 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Chris Lattner141e71f2008-03-09 01:54:53 +0000503 // We just parsed a # character at the start of a line, so we're in directive
504 // mode. Tell the lexer this so any newlines we see will be converted into an
505 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000506 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Chris Lattner141e71f2008-03-09 01:54:53 +0000508 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000509
Chris Lattner141e71f2008-03-09 01:54:53 +0000510 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000511 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000512 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000513 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Chris Lattner42aa16c2009-03-18 21:00:25 +0000515 // Save the '#' token in case we need to return it later.
516 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Chris Lattner141e71f2008-03-09 01:54:53 +0000518 // Read the next token, the directive flavor. This isn't expanded due to
519 // C99 6.10.3p8.
520 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Chris Lattner141e71f2008-03-09 01:54:53 +0000522 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
523 // #define A(x) #x
524 // A(abc
525 // #warning blah
526 // def)
527 // If so, the user is relying on non-portable behavior, emit a diagnostic.
528 if (InMacroArgs)
529 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner141e71f2008-03-09 01:54:53 +0000531TryAgain:
532 switch (Result.getKind()) {
533 case tok::eom:
534 return; // null directive.
535 case tok::comment:
536 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
537 LexUnexpandedToken(Result);
538 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000539 case tok::code_completion:
540 if (CodeComplete)
541 CodeComplete->CodeCompleteDirective(
542 CurPPLexer->getConditionalStackDepth() > 0);
543 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000544 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000545 if (getLangOptions().AsmPreprocessor)
546 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000547 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000548 default:
549 IdentifierInfo *II = Result.getIdentifierInfo();
550 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Chris Lattner141e71f2008-03-09 01:54:53 +0000552 // Ask what the preprocessor keyword ID is.
553 switch (II->getPPKeywordID()) {
554 default: break;
555 // C99 6.10.1 - Conditional Inclusion.
556 case tok::pp_if:
557 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
558 case tok::pp_ifdef:
559 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
560 case tok::pp_ifndef:
561 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
562 case tok::pp_elif:
563 return HandleElifDirective(Result);
564 case tok::pp_else:
565 return HandleElseDirective(Result);
566 case tok::pp_endif:
567 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattner141e71f2008-03-09 01:54:53 +0000569 // C99 6.10.2 - Source File Inclusion.
570 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000571 return HandleIncludeDirective(Result); // Handle #include.
572 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000573 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Chris Lattner141e71f2008-03-09 01:54:53 +0000575 // C99 6.10.3 - Macro Replacement.
576 case tok::pp_define:
577 return HandleDefineDirective(Result);
578 case tok::pp_undef:
579 return HandleUndefDirective(Result);
580
581 // C99 6.10.4 - Line Control.
582 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000583 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Chris Lattner141e71f2008-03-09 01:54:53 +0000585 // C99 6.10.5 - Error Directive.
586 case tok::pp_error:
587 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Chris Lattner141e71f2008-03-09 01:54:53 +0000589 // C99 6.10.6 - Pragma Directive.
590 case tok::pp_pragma:
591 return HandlePragmaDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Chris Lattner141e71f2008-03-09 01:54:53 +0000593 // GNU Extensions.
594 case tok::pp_import:
595 return HandleImportDirective(Result);
596 case tok::pp_include_next:
597 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Chris Lattner141e71f2008-03-09 01:54:53 +0000599 case tok::pp_warning:
600 Diag(Result, diag::ext_pp_warning_directive);
601 return HandleUserDiagnosticDirective(Result, true);
602 case tok::pp_ident:
603 return HandleIdentSCCSDirective(Result);
604 case tok::pp_sccs:
605 return HandleIdentSCCSDirective(Result);
606 case tok::pp_assert:
607 //isExtension = true; // FIXME: implement #assert
608 break;
609 case tok::pp_unassert:
610 //isExtension = true; // FIXME: implement #unassert
611 break;
612 }
613 break;
614 }
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Chris Lattner42aa16c2009-03-18 21:00:25 +0000616 // If this is a .S file, treat unknown # directives as non-preprocessor
617 // directives. This is important because # may be a comment or introduce
618 // various pseudo-ops. Just return the # token and push back the following
619 // token to be lexed next time.
620 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000621 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000622 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000623 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000624 Toks[1] = Result;
625 // Enter this token stream so that we re-lex the tokens. Make sure to
626 // enable macro expansion, in case the token after the # is an identifier
627 // that is expanded.
628 EnterTokenStream(Toks, 2, false, true);
629 return;
630 }
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Chris Lattner141e71f2008-03-09 01:54:53 +0000632 // If we reached here, the preprocessing token is not valid!
633 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Chris Lattner141e71f2008-03-09 01:54:53 +0000635 // Read the rest of the PP line.
636 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattner141e71f2008-03-09 01:54:53 +0000638 // Okay, we're done parsing the directive.
639}
640
Chris Lattner478a18e2009-01-26 06:19:46 +0000641/// GetLineValue - Convert a numeric token into an unsigned value, emitting
642/// Diagnostic DiagID if it is invalid, and returning the value in Val.
643static bool GetLineValue(Token &DigitTok, unsigned &Val,
644 unsigned DiagID, Preprocessor &PP) {
645 if (DigitTok.isNot(tok::numeric_constant)) {
646 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Chris Lattner478a18e2009-01-26 06:19:46 +0000648 if (DigitTok.isNot(tok::eom))
649 PP.DiscardUntilEndOfDirective();
650 return true;
651 }
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Chris Lattner478a18e2009-01-26 06:19:46 +0000653 llvm::SmallString<64> IntegerBuffer;
654 IntegerBuffer.resize(DigitTok.getLength());
655 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000656 bool Invalid = false;
657 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
658 if (Invalid)
659 return true;
660
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000661 // Verify that we have a simple digit-sequence, and compute the value. This
662 // is always a simple digit string computed in decimal, so we do this manually
663 // here.
664 Val = 0;
665 for (unsigned i = 0; i != ActualLength; ++i) {
666 if (!isdigit(DigitTokBegin[i])) {
667 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
668 diag::err_pp_line_digit_sequence);
669 PP.DiscardUntilEndOfDirective();
670 return true;
671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000673 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
674 if (NextVal < Val) { // overflow.
675 PP.Diag(DigitTok, DiagID);
676 PP.DiscardUntilEndOfDirective();
677 return true;
678 }
679 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000680 }
Mike Stump1eb44332009-09-09 15:08:12 +0000681
682 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000683 if (Val == 0) {
684 PP.Diag(DigitTok, DiagID);
685 PP.DiscardUntilEndOfDirective();
686 return true;
687 }
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000689 if (DigitTokBegin[0] == '0')
690 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattner478a18e2009-01-26 06:19:46 +0000692 return false;
693}
694
Mike Stump1eb44332009-09-09 15:08:12 +0000695/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000696/// acceptable forms are:
697/// # line digit-sequence
698/// # line digit-sequence "s-char-sequence"
699void Preprocessor::HandleLineDirective(Token &Tok) {
700 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
701 // expanded.
702 Token DigitTok;
703 Lex(DigitTok);
704
Chris Lattner359cc442009-01-26 05:29:08 +0000705 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000706 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000707 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000708 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000709
Chris Lattner478a18e2009-01-26 06:19:46 +0000710 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
711 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000712 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
713 if (LineNo >= LineLimit)
714 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Chris Lattner5b9a5042009-01-26 07:57:50 +0000716 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000717 Token StrTok;
718 Lex(StrTok);
719
720 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
721 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000722 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000723 ; // ok
724 else if (StrTok.isNot(tok::string_literal)) {
725 Diag(StrTok, diag::err_pp_line_invalid_filename);
726 DiscardUntilEndOfDirective();
727 return;
728 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000729 // Parse and validate the string, converting it into a unique ID.
730 StringLiteralParser Literal(&StrTok, 1, *this);
731 assert(!Literal.AnyWide && "Didn't allow wide strings in");
732 if (Literal.hadError)
733 return DiscardUntilEndOfDirective();
734 if (Literal.Pascal) {
735 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
736 return DiscardUntilEndOfDirective();
737 }
738 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
739 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Chris Lattnerab82f412009-04-17 23:30:53 +0000741 // Verify that there is nothing after the string, other than EOM. Because
742 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
743 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000744 }
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Chris Lattner4c4ea172009-02-03 21:52:55 +0000746 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Chris Lattner16629382009-03-27 17:13:49 +0000748 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000749 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
750 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000751 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000752}
753
Chris Lattner478a18e2009-01-26 06:19:46 +0000754/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
755/// marker directive.
756static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
757 bool &IsSystemHeader, bool &IsExternCHeader,
758 Preprocessor &PP) {
759 unsigned FlagVal;
760 Token FlagTok;
761 PP.Lex(FlagTok);
762 if (FlagTok.is(tok::eom)) return false;
763 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
764 return true;
765
766 if (FlagVal == 1) {
767 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Chris Lattner478a18e2009-01-26 06:19:46 +0000769 PP.Lex(FlagTok);
770 if (FlagTok.is(tok::eom)) return false;
771 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
772 return true;
773 } else if (FlagVal == 2) {
774 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Chris Lattner137b6a62009-02-04 06:25:26 +0000776 SourceManager &SM = PP.getSourceManager();
777 // If we are leaving the current presumed file, check to make sure the
778 // presumed include stack isn't empty!
779 FileID CurFileID =
780 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
781 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Chris Lattner137b6a62009-02-04 06:25:26 +0000783 // If there is no include loc (main file) or if the include loc is in a
784 // different physical file, then we aren't in a "1" line marker flag region.
785 SourceLocation IncLoc = PLoc.getIncludeLoc();
786 if (IncLoc.isInvalid() ||
787 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
788 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
789 PP.DiscardUntilEndOfDirective();
790 return true;
791 }
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chris Lattner478a18e2009-01-26 06:19:46 +0000793 PP.Lex(FlagTok);
794 if (FlagTok.is(tok::eom)) return false;
795 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
796 return true;
797 }
798
799 // We must have 3 if there are still flags.
800 if (FlagVal != 3) {
801 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000802 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000803 return true;
804 }
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Chris Lattner478a18e2009-01-26 06:19:46 +0000806 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Chris Lattner478a18e2009-01-26 06:19:46 +0000808 PP.Lex(FlagTok);
809 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000810 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000811 return true;
812
813 // We must have 4 if there is yet another flag.
814 if (FlagVal != 4) {
815 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000816 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000817 return true;
818 }
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Chris Lattner478a18e2009-01-26 06:19:46 +0000820 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Chris Lattner478a18e2009-01-26 06:19:46 +0000822 PP.Lex(FlagTok);
823 if (FlagTok.is(tok::eom)) return false;
824
825 // There are no more valid flags here.
826 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000827 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000828 return true;
829}
830
831/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
832/// one of the following forms:
833///
834/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000835/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000836/// # 42 "file" ('1' | '2')? '3' '4'?
837///
838void Preprocessor::HandleDigitDirective(Token &DigitTok) {
839 // Validate the number and convert it to an unsigned. GNU does not have a
840 // line # limit other than it fit in 32-bits.
841 unsigned LineNo;
842 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
843 *this))
844 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Chris Lattner478a18e2009-01-26 06:19:46 +0000846 Token StrTok;
847 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Chris Lattner478a18e2009-01-26 06:19:46 +0000849 bool IsFileEntry = false, IsFileExit = false;
850 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000851 int FilenameID = -1;
852
Chris Lattner478a18e2009-01-26 06:19:46 +0000853 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
854 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000855 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000856 ; // ok
857 else if (StrTok.isNot(tok::string_literal)) {
858 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000859 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000860 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000861 // Parse and validate the string, converting it into a unique ID.
862 StringLiteralParser Literal(&StrTok, 1, *this);
863 assert(!Literal.AnyWide && "Didn't allow wide strings in");
864 if (Literal.hadError)
865 return DiscardUntilEndOfDirective();
866 if (Literal.Pascal) {
867 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
868 return DiscardUntilEndOfDirective();
869 }
870 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
871 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Chris Lattner478a18e2009-01-26 06:19:46 +0000873 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000874 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000875 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000876 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000877 }
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Chris Lattner9d79eba2009-02-04 05:21:58 +0000879 // Create a line note with this information.
880 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000881 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000882 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattner16629382009-03-27 17:13:49 +0000884 // If the preprocessor has callbacks installed, notify them of the #line
885 // change. This is used so that the line marker comes out in -E mode for
886 // example.
887 if (Callbacks) {
888 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
889 if (IsFileEntry)
890 Reason = PPCallbacks::EnterFile;
891 else if (IsFileExit)
892 Reason = PPCallbacks::ExitFile;
893 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
894 if (IsExternCHeader)
895 FileKind = SrcMgr::C_ExternCSystem;
896 else if (IsSystemHeader)
897 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Chris Lattner86d0ef72010-04-14 04:28:50 +0000899 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000900 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000901}
902
903
Chris Lattner099dd052009-01-26 05:30:54 +0000904/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
905///
Mike Stump1eb44332009-09-09 15:08:12 +0000906void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000907 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000908 // PTH doesn't emit #warning or #error directives.
909 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000910 return CurPTHLexer->DiscardToEndOfLine();
911
Chris Lattner141e71f2008-03-09 01:54:53 +0000912 // Read the rest of the line raw. We do this because we don't want macros
913 // to be expanded and we don't require that the tokens be valid preprocessing
914 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
915 // collapse multiple consequtive white space between tokens, but this isn't
916 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000917 std::string Message = CurLexer->ReadToEndOfLine();
918 if (isWarning)
919 Diag(Tok, diag::pp_hash_warning) << Message;
920 else
921 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000922}
923
924/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
925///
926void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
927 // Yes, this directive is an extension.
928 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Chris Lattner141e71f2008-03-09 01:54:53 +0000930 // Read the string argument.
931 Token StrTok;
932 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Chris Lattner141e71f2008-03-09 01:54:53 +0000934 // If the token kind isn't a string, it's a malformed directive.
935 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000936 StrTok.isNot(tok::wide_string_literal)) {
937 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000938 if (StrTok.isNot(tok::eom))
939 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000940 return;
941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Chris Lattner141e71f2008-03-09 01:54:53 +0000943 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000944 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000945
Douglas Gregor453091c2010-03-16 22:30:13 +0000946 if (Callbacks) {
947 bool Invalid = false;
948 std::string Str = getSpelling(StrTok, &Invalid);
949 if (!Invalid)
950 Callbacks->Ident(Tok.getLocation(), Str);
951 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000952}
953
954//===----------------------------------------------------------------------===//
955// Preprocessor Include Directive Handling.
956//===----------------------------------------------------------------------===//
957
958/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
959/// checked and spelled filename, e.g. as an operand of #include. This returns
960/// true if the input filename was in <>'s or false if it were in ""'s. The
961/// caller is expected to provide a buffer that is large enough to hold the
962/// spelling of the filename, but is also expected to handle the case when
963/// this method decides to use a different buffer.
964bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000965 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000966 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000967 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Chris Lattner141e71f2008-03-09 01:54:53 +0000969 // Make sure the filename is <x> or "x".
970 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000971 if (Buffer[0] == '<') {
972 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000973 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000974 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000975 return true;
976 }
977 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +0000978 } else if (Buffer[0] == '"') {
979 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000980 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000981 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000982 return true;
983 }
984 isAngled = false;
985 } else {
986 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000987 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000988 return true;
989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattner141e71f2008-03-09 01:54:53 +0000991 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +0000992 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000993 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000994 Buffer = llvm::StringRef();
995 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000996 }
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Chris Lattner141e71f2008-03-09 01:54:53 +0000998 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +0000999 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001000 return isAngled;
1001}
1002
1003/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1004/// from a macro as multiple tokens, which need to be glued together. This
1005/// occurs for code like:
1006/// #define FOO <a/b.h>
1007/// #include FOO
1008/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1009///
1010/// This code concatenates and consumes tokens up to the '>' token. It returns
1011/// false if the > was found, otherwise it returns true if it finds and consumes
1012/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +00001013bool Preprocessor::ConcatenateIncludeName(
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001014 llvm::SmallString<128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001015 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001016
John Thompsona28cc092009-10-30 13:49:06 +00001017 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001018 while (CurTok.isNot(tok::eom)) {
1019 // Append the spelling of this token to the buffer. If there was a space
1020 // before it, add it now.
1021 if (CurTok.hasLeadingSpace())
1022 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Chris Lattner141e71f2008-03-09 01:54:53 +00001024 // Get the spelling of the token, directly into FilenameBuffer if possible.
1025 unsigned PreAppendSize = FilenameBuffer.size();
1026 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Chris Lattner141e71f2008-03-09 01:54:53 +00001028 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001029 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Chris Lattner141e71f2008-03-09 01:54:53 +00001031 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1032 if (BufPtr != &FilenameBuffer[PreAppendSize])
1033 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Chris Lattner141e71f2008-03-09 01:54:53 +00001035 // Resize FilenameBuffer to the correct size.
1036 if (CurTok.getLength() != ActualLen)
1037 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Chris Lattner141e71f2008-03-09 01:54:53 +00001039 // If we found the '>' marker, return success.
1040 if (CurTok.is(tok::greater))
1041 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001042
John Thompsona28cc092009-10-30 13:49:06 +00001043 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001044 }
1045
1046 // If we hit the eom marker, emit an error and return true so that the caller
1047 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001048 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001049 return true;
1050}
1051
1052/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1053/// file to be included from the lexer, then include it! This is a common
1054/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001055/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001056/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001057void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1058 const DirectoryLookup *LookupFrom,
1059 bool isImport) {
1060
1061 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001062 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Chris Lattner141e71f2008-03-09 01:54:53 +00001064 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001065 llvm::SmallString<128> FilenameBuffer;
1066 llvm::StringRef Filename;
Chris Lattner141e71f2008-03-09 01:54:53 +00001067
1068 switch (FilenameTok.getKind()) {
1069 case tok::eom:
1070 // If the token kind is EOM, the error has already been diagnosed.
1071 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Chris Lattner141e71f2008-03-09 01:54:53 +00001073 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001074 case tok::string_literal:
1075 Filename = getSpelling(FilenameTok, FilenameBuffer);
Chris Lattner141e71f2008-03-09 01:54:53 +00001076 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Chris Lattner141e71f2008-03-09 01:54:53 +00001078 case tok::less:
1079 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1080 // case, glue the tokens together into FilenameBuffer and interpret those.
1081 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001082 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001083 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001084 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001085 break;
1086 default:
1087 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1088 DiscardUntilEndOfDirective();
1089 return;
1090 }
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001092 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001093 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001094 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1095 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001096 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001097 DiscardUntilEndOfDirective();
1098 return;
1099 }
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001101 // Verify that there is nothing after the filename, other than EOM. Note that
1102 // we allow macros that expand to nothing after the filename, because this
1103 // falls into the category of "#include pp-tokens new-line" specified in
1104 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001105 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001106
1107 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001108 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1109 Diag(FilenameTok, diag::err_pp_include_too_deep);
1110 return;
1111 }
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Chris Lattner141e71f2008-03-09 01:54:53 +00001113 // Search include directories.
1114 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +00001115 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001116 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001117 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001118 return;
1119 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001120
Chris Lattner72181832008-09-26 20:12:23 +00001121 // The #included file will be considered to be a system header if either it is
1122 // in a system include directory, or if the #includer is a system include
1123 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001124 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001125 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001126 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001128 // Ask HeaderInfo if we should enter this #include file. If not, #including
1129 // this file will have no effect.
1130 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001131 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001132 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001133 return;
1134 }
1135
Chris Lattner141e71f2008-03-09 01:54:53 +00001136 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001137 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1138 FileCharacter);
1139 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001140 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001141 return;
1142 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001143
1144 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001145 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001146}
1147
1148/// HandleIncludeNextDirective - Implements #include_next.
1149///
1150void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1151 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Chris Lattner141e71f2008-03-09 01:54:53 +00001153 // #include_next is like #include, except that we start searching after
1154 // the current found directory. If we can't do this, issue a
1155 // diagnostic.
1156 const DirectoryLookup *Lookup = CurDirLookup;
1157 if (isInPrimaryFile()) {
1158 Lookup = 0;
1159 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1160 } else if (Lookup == 0) {
1161 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1162 } else {
1163 // Start looking up in the next directory.
1164 ++Lookup;
1165 }
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Chris Lattner141e71f2008-03-09 01:54:53 +00001167 return HandleIncludeDirective(IncludeNextTok, Lookup);
1168}
1169
1170/// HandleImportDirective - Implements #import.
1171///
1172void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001173 if (!Features.ObjC1) // #import is standard for ObjC.
1174 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Chris Lattner141e71f2008-03-09 01:54:53 +00001176 return HandleIncludeDirective(ImportTok, 0, true);
1177}
1178
Chris Lattnerde076652009-04-08 18:46:40 +00001179/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1180/// pseudo directive in the predefines buffer. This handles it by sucking all
1181/// tokens through the preprocessor and discarding them (only keeping the side
1182/// effects on the preprocessor).
1183void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1184 // This directive should only occur in the predefines buffer. If not, emit an
1185 // error and reject it.
1186 SourceLocation Loc = IncludeMacrosTok.getLocation();
1187 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1188 Diag(IncludeMacrosTok.getLocation(),
1189 diag::pp_include_macros_out_of_predefines);
1190 DiscardUntilEndOfDirective();
1191 return;
1192 }
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Chris Lattnerfd105112009-04-08 20:53:24 +00001194 // Treat this as a normal #include for checking purposes. If this is
1195 // successful, it will push a new lexer onto the include stack.
1196 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Chris Lattnerfd105112009-04-08 20:53:24 +00001198 Token TmpTok;
1199 do {
1200 Lex(TmpTok);
1201 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1202 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001203}
1204
Chris Lattner141e71f2008-03-09 01:54:53 +00001205//===----------------------------------------------------------------------===//
1206// Preprocessor Macro Directive Handling.
1207//===----------------------------------------------------------------------===//
1208
1209/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1210/// definition has just been read. Lex the rest of the arguments and the
1211/// closing ), updating MI with what we learn. Return true if an error occurs
1212/// parsing the arg list.
1213bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1214 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Chris Lattner141e71f2008-03-09 01:54:53 +00001216 Token Tok;
1217 while (1) {
1218 LexUnexpandedToken(Tok);
1219 switch (Tok.getKind()) {
1220 case tok::r_paren:
1221 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001222 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001223 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001224 // Otherwise we have #define FOO(A,)
1225 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1226 return true;
1227 case tok::ellipsis: // #define X(... -> C99 varargs
1228 // Warn if use of C99 feature in non-C99 mode.
1229 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1230
1231 // Lex the token after the identifier.
1232 LexUnexpandedToken(Tok);
1233 if (Tok.isNot(tok::r_paren)) {
1234 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1235 return true;
1236 }
1237 // Add the __VA_ARGS__ identifier as an argument.
1238 Arguments.push_back(Ident__VA_ARGS__);
1239 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001240 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001241 return false;
1242 case tok::eom: // #define X(
1243 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1244 return true;
1245 default:
1246 // Handle keywords and identifiers here to accept things like
1247 // #define Foo(for) for.
1248 IdentifierInfo *II = Tok.getIdentifierInfo();
1249 if (II == 0) {
1250 // #define X(1
1251 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1252 return true;
1253 }
1254
1255 // If this is already used as an argument, it is used multiple times (e.g.
1256 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001257 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001258 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001259 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001260 return true;
1261 }
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Chris Lattner141e71f2008-03-09 01:54:53 +00001263 // Add the argument to the macro info.
1264 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Chris Lattner141e71f2008-03-09 01:54:53 +00001266 // Lex the token after the identifier.
1267 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Chris Lattner141e71f2008-03-09 01:54:53 +00001269 switch (Tok.getKind()) {
1270 default: // #define X(A B
1271 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1272 return true;
1273 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001274 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001275 return false;
1276 case tok::comma: // #define X(A,
1277 break;
1278 case tok::ellipsis: // #define X(A... -> GCC extension
1279 // Diagnose extension.
1280 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Chris Lattner141e71f2008-03-09 01:54:53 +00001282 // Lex the token after the identifier.
1283 LexUnexpandedToken(Tok);
1284 if (Tok.isNot(tok::r_paren)) {
1285 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1286 return true;
1287 }
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Chris Lattner141e71f2008-03-09 01:54:53 +00001289 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001290 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001291 return false;
1292 }
1293 }
1294 }
1295}
1296
1297/// HandleDefineDirective - Implements #define. This consumes the entire macro
1298/// line then lets the caller lex the next real token.
1299void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1300 ++NumDefined;
1301
1302 Token MacroNameTok;
1303 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Chris Lattner141e71f2008-03-09 01:54:53 +00001305 // Error reading macro name? If so, diagnostic already issued.
1306 if (MacroNameTok.is(tok::eom))
1307 return;
1308
Chris Lattner2451b522009-04-21 04:46:33 +00001309 Token LastTok = MacroNameTok;
1310
Chris Lattner141e71f2008-03-09 01:54:53 +00001311 // If we are supposed to keep comments in #defines, reenable comment saving
1312 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001313 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Chris Lattner141e71f2008-03-09 01:54:53 +00001315 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001316 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Chris Lattner141e71f2008-03-09 01:54:53 +00001318 Token Tok;
1319 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Chris Lattner141e71f2008-03-09 01:54:53 +00001321 // If this is a function-like macro definition, parse the argument list,
1322 // marking each of the identifiers as being used as macro arguments. Also,
1323 // check other constraints on the first token of the macro body.
1324 if (Tok.is(tok::eom)) {
1325 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001326 } else if (Tok.hasLeadingSpace()) {
1327 // This is a normal token with leading space. Clear the leading space
1328 // marker on the first token to get proper expansion.
1329 Tok.clearFlag(Token::LeadingSpace);
1330 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001331 // This is a function-like macro definition. Read the argument list.
1332 MI->setIsFunctionLike();
1333 if (ReadMacroDefinitionArgList(MI)) {
1334 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001335 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001336 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001337 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001338 DiscardUntilEndOfDirective();
1339 return;
1340 }
1341
Chris Lattner8fde5972009-04-19 18:26:34 +00001342 // If this is a definition of a variadic C99 function-like macro, not using
1343 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Chris Lattner8fde5972009-04-19 18:26:34 +00001345 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1346 // This gets unpoisoned where it is allowed.
1347 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1348 if (MI->isC99Varargs())
1349 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Chris Lattner141e71f2008-03-09 01:54:53 +00001351 // Read the first token after the arg list for down below.
1352 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001353 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001354 // C99 requires whitespace between the macro definition and the body. Emit
1355 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001356 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001357 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001358 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1359 // first character of a replacement list is not a character required by
1360 // subclause 5.2.1, then there shall be white-space separation between the
1361 // identifier and the replacement list.". 5.2.1 lists this set:
1362 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1363 // is irrelevant here.
1364 bool isInvalid = false;
1365 if (Tok.is(tok::at)) // @ is not in the list above.
1366 isInvalid = true;
1367 else if (Tok.is(tok::unknown)) {
1368 // If we have an unknown token, it is something strange like "`". Since
1369 // all of valid characters would have lexed into a single character
1370 // token of some sort, we know this is not a valid case.
1371 isInvalid = true;
1372 }
1373 if (isInvalid)
1374 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1375 else
1376 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001377 }
Chris Lattner2451b522009-04-21 04:46:33 +00001378
1379 if (!Tok.is(tok::eom))
1380 LastTok = Tok;
1381
Chris Lattner141e71f2008-03-09 01:54:53 +00001382 // Read the rest of the macro body.
1383 if (MI->isObjectLike()) {
1384 // Object-like macros are very simple, just read their body.
1385 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001386 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001387 MI->AddTokenToBody(Tok);
1388 // Get the next token of the macro.
1389 LexUnexpandedToken(Tok);
1390 }
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Chris Lattner141e71f2008-03-09 01:54:53 +00001392 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001393 // Otherwise, read the body of a function-like macro. While we are at it,
1394 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1395 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001396 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001397 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001398
Chris Lattner141e71f2008-03-09 01:54:53 +00001399 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001400 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Chris Lattner141e71f2008-03-09 01:54:53 +00001402 // Get the next token of the macro.
1403 LexUnexpandedToken(Tok);
1404 continue;
1405 }
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Chris Lattner141e71f2008-03-09 01:54:53 +00001407 // Get the next token of the macro.
1408 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Chris Lattner32404692009-05-25 17:16:10 +00001410 // Check for a valid macro arg identifier.
1411 if (Tok.getIdentifierInfo() == 0 ||
1412 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1413
1414 // If this is assembler-with-cpp mode, we accept random gibberish after
1415 // the '#' because '#' is often a comment character. However, change
1416 // the kind of the token to tok::unknown so that the preprocessor isn't
1417 // confused.
1418 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1419 LastTok.setKind(tok::unknown);
1420 } else {
1421 Diag(Tok, diag::err_pp_stringize_not_parameter);
1422 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Chris Lattner32404692009-05-25 17:16:10 +00001424 // Disable __VA_ARGS__ again.
1425 Ident__VA_ARGS__->setIsPoisoned(true);
1426 return;
1427 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001428 }
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Chris Lattner32404692009-05-25 17:16:10 +00001430 // Things look ok, add the '#' and param name tokens to the macro.
1431 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001432 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001433 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Chris Lattner141e71f2008-03-09 01:54:53 +00001435 // Get the next token of the macro.
1436 LexUnexpandedToken(Tok);
1437 }
1438 }
Mike Stump1eb44332009-09-09 15:08:12 +00001439
1440
Chris Lattner141e71f2008-03-09 01:54:53 +00001441 // Disable __VA_ARGS__ again.
1442 Ident__VA_ARGS__->setIsPoisoned(true);
1443
1444 // Check that there is no paste (##) operator at the begining or end of the
1445 // replacement list.
1446 unsigned NumTokens = MI->getNumTokens();
1447 if (NumTokens != 0) {
1448 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1449 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001450 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001451 return;
1452 }
1453 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1454 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001455 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001456 return;
1457 }
1458 }
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Chris Lattner141e71f2008-03-09 01:54:53 +00001460 // If this is the primary source file, remember that this macro hasn't been
1461 // used yet.
1462 if (isInPrimaryFile())
1463 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001464
1465 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Chris Lattner141e71f2008-03-09 01:54:53 +00001467 // Finally, if this identifier already had a macro defined for it, verify that
1468 // the macro bodies are identical and free the old definition.
1469 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001470 // It is very common for system headers to have tons of macro redefinitions
1471 // and for warnings to be disabled in system headers. If this is the case,
1472 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001473 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001474 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1475 if (!OtherMI->isUsed())
1476 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001477
Chris Lattnerf47724b2010-08-17 15:55:45 +00001478 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001479 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001480 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001481 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001482 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1483 << MacroNameTok.getIdentifierInfo();
1484 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1485 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001486 }
Ted Kremenek0ea76722008-12-15 19:56:42 +00001487 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001488 }
Mike Stump1eb44332009-09-09 15:08:12 +00001489
Chris Lattner141e71f2008-03-09 01:54:53 +00001490 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001492 // If the callbacks want to know, tell them about the macro definition.
1493 if (Callbacks)
1494 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001495}
1496
1497/// HandleUndefDirective - Implements #undef.
1498///
1499void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1500 ++NumUndefined;
1501
1502 Token MacroNameTok;
1503 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Chris Lattner141e71f2008-03-09 01:54:53 +00001505 // Error reading macro name? If so, diagnostic already issued.
1506 if (MacroNameTok.is(tok::eom))
1507 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Chris Lattner141e71f2008-03-09 01:54:53 +00001509 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001510 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001511
Chris Lattner141e71f2008-03-09 01:54:53 +00001512 // Okay, we finally have a valid identifier to undef.
1513 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Chris Lattner141e71f2008-03-09 01:54:53 +00001515 // If the macro is not defined, this is a noop undef, just return.
1516 if (MI == 0) return;
1517
1518 if (!MI->isUsed())
1519 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001520
1521 // If the callbacks want to know, tell them about the macro #undef.
1522 if (Callbacks)
Benjamin Kramer2f054492010-08-07 22:27:00 +00001523 Callbacks->MacroUndefined(MacroNameTok.getLocation(),
1524 MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001525
Chris Lattner141e71f2008-03-09 01:54:53 +00001526 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001527 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001528 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1529}
1530
1531
1532//===----------------------------------------------------------------------===//
1533// Preprocessor Conditional Directive Handling.
1534//===----------------------------------------------------------------------===//
1535
1536/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1537/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1538/// if any tokens have been returned or pp-directives activated before this
1539/// #ifndef has been lexed.
1540///
1541void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1542 bool ReadAnyTokensBeforeDirective) {
1543 ++NumIf;
1544 Token DirectiveTok = Result;
1545
1546 Token MacroNameTok;
1547 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Chris Lattner141e71f2008-03-09 01:54:53 +00001549 // Error reading macro name? If so, diagnostic already issued.
1550 if (MacroNameTok.is(tok::eom)) {
1551 // Skip code until we get to #endif. This helps with recovery by not
1552 // emitting an error when the #endif is reached.
1553 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1554 /*Foundnonskip*/false, /*FoundElse*/false);
1555 return;
1556 }
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Chris Lattner141e71f2008-03-09 01:54:53 +00001558 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001559 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001560
Chris Lattner13d283d2010-02-12 08:03:27 +00001561 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1562 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001563
Ted Kremenek60e45d42008-11-18 00:34:22 +00001564 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001565 // If the start of a top-level #ifdef and if the macro is not defined,
1566 // inform MIOpt that this might be the start of a proper include guard.
1567 // Otherwise it is some other form of unknown conditional which we can't
1568 // handle.
1569 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001570 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001571 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001572 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001573 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001574 }
1575
Chris Lattner141e71f2008-03-09 01:54:53 +00001576 // If there is a macro, process it.
1577 if (MI) // Mark it used.
1578 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Chris Lattner141e71f2008-03-09 01:54:53 +00001580 // Should we include the stuff contained by this directive?
1581 if (!MI == isIfndef) {
1582 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001583 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1584 /*wasskip*/false, /*foundnonskip*/true,
1585 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001586 } else {
1587 // No, skip the contents of this block and return the first token after it.
1588 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001589 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001590 /*FoundElse*/false);
1591 }
1592}
1593
1594/// HandleIfDirective - Implements the #if directive.
1595///
1596void Preprocessor::HandleIfDirective(Token &IfToken,
1597 bool ReadAnyTokensBeforeDirective) {
1598 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Chris Lattner141e71f2008-03-09 01:54:53 +00001600 // Parse and evaluation the conditional expression.
1601 IdentifierInfo *IfNDefMacro = 0;
1602 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Nuno Lopes0049db62008-06-01 18:31:24 +00001604
1605 // If this condition is equivalent to #ifndef X, and if this is the first
1606 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001607 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001608 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001609 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001610 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001611 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001612 }
1613
Chris Lattner141e71f2008-03-09 01:54:53 +00001614 // Should we include the stuff contained by this directive?
1615 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001616 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001617 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001618 /*foundnonskip*/true, /*foundelse*/false);
1619 } else {
1620 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001621 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001622 /*FoundElse*/false);
1623 }
1624}
1625
1626/// HandleEndifDirective - Implements the #endif directive.
1627///
1628void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1629 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Chris Lattner141e71f2008-03-09 01:54:53 +00001631 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001632 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Chris Lattner141e71f2008-03-09 01:54:53 +00001634 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001635 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001636 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001637 Diag(EndifToken, diag::err_pp_endif_without_if);
1638 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001639 }
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Chris Lattner141e71f2008-03-09 01:54:53 +00001641 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001642 if (CurPPLexer->getConditionalStackDepth() == 0)
1643 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Ted Kremenek60e45d42008-11-18 00:34:22 +00001645 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001646 "This code should only be reachable in the non-skipping case!");
1647}
1648
1649
1650void Preprocessor::HandleElseDirective(Token &Result) {
1651 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Chris Lattner141e71f2008-03-09 01:54:53 +00001653 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001654 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Chris Lattner141e71f2008-03-09 01:54:53 +00001656 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001657 if (CurPPLexer->popConditionalLevel(CI)) {
1658 Diag(Result, diag::pp_err_else_without_if);
1659 return;
1660 }
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Chris Lattner141e71f2008-03-09 01:54:53 +00001662 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001663 if (CurPPLexer->getConditionalStackDepth() == 0)
1664 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001665
1666 // If this is a #else with a #else before it, report the error.
1667 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Chris Lattner141e71f2008-03-09 01:54:53 +00001669 // Finally, skip the rest of the contents of this block and return the first
1670 // token after it.
1671 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1672 /*FoundElse*/true);
1673}
1674
1675void Preprocessor::HandleElifDirective(Token &ElifToken) {
1676 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Chris Lattner141e71f2008-03-09 01:54:53 +00001678 // #elif directive in a non-skipping conditional... start skipping.
1679 // We don't care what the condition is, because we will always skip it (since
1680 // the block immediately before it was included).
1681 DiscardUntilEndOfDirective();
1682
1683 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001684 if (CurPPLexer->popConditionalLevel(CI)) {
1685 Diag(ElifToken, diag::pp_err_elif_without_if);
1686 return;
1687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Chris Lattner141e71f2008-03-09 01:54:53 +00001689 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001690 if (CurPPLexer->getConditionalStackDepth() == 0)
1691 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Chris Lattner141e71f2008-03-09 01:54:53 +00001693 // If this is a #elif with a #else before it, report the error.
1694 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1695
1696 // Finally, skip the rest of the contents of this block and return the first
1697 // token after it.
1698 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1699 /*FoundElse*/CI.FoundElse);
1700}