blob: 417724b7778704d21655e7f7de15617969831fde [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"
Chris Lattner6e290142009-11-30 04:18:44 +000019#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000021#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000022using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// Utility Methods for Preprocessor Directive Handling.
26//===----------------------------------------------------------------------===//
27
Chris Lattner0301b3f2009-02-20 22:19:20 +000028MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
Ted Kremenek0ea76722008-12-15 19:56:42 +000029 MacroInfo *MI;
Mike Stump1eb44332009-09-09 15:08:12 +000030
Ted Kremenek0ea76722008-12-15 19:56:42 +000031 if (!MICache.empty()) {
32 MI = MICache.back();
33 MICache.pop_back();
Chris Lattner0301b3f2009-02-20 22:19:20 +000034 } else
35 MI = (MacroInfo*) BP.Allocate<MacroInfo>();
Ted Kremenek0ea76722008-12-15 19:56:42 +000036 new (MI) MacroInfo(L);
37 return MI;
38}
39
Chris Lattner0301b3f2009-02-20 22:19:20 +000040/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
41/// be reused for allocating new MacroInfo objects.
42void Preprocessor::ReleaseMacroInfo(MacroInfo* MI) {
43 MICache.push_back(MI);
Chris Lattner685befe2009-02-20 22:46:43 +000044 MI->FreeArgumentList(BP);
Chris Lattner0301b3f2009-02-20 22:19:20 +000045}
46
47
Chris Lattner141e71f2008-03-09 01:54:53 +000048/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
49/// current line until the tok::eom token is found.
50void Preprocessor::DiscardUntilEndOfDirective() {
51 Token Tmp;
52 do {
53 LexUnexpandedToken(Tmp);
54 } while (Tmp.isNot(tok::eom));
55}
56
Chris Lattner141e71f2008-03-09 01:54:53 +000057/// ReadMacroName - Lex and validate a macro name, which occurs after a
58/// #define or #undef. This sets the token kind to eom and discards the rest
59/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
60/// this is due to a a #define, 2 if #undef directive, 0 if it is something
61/// else (e.g. #ifdef).
62void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
63 // Read the token, don't allow macro expansion on it.
64 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner141e71f2008-03-09 01:54:53 +000066 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000067 if (MacroNameTok.is(tok::eom)) {
68 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
69 return;
70 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner141e71f2008-03-09 01:54:53 +000072 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
73 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +000074 bool Invalid = false;
75 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
76 if (Invalid)
77 return;
78
Chris Lattner9485d232008-12-13 20:12:40 +000079 const IdentifierInfo &Info = Identifiers.get(Spelling);
80 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +000081 // C++ 2.5p2: Alternative tokens behave the same as its primary token
82 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +000083 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000084 else
85 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
86 // Fall through on error.
87 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
88 // Error if defining "defined": C99 6.10.8.4.
89 Diag(MacroNameTok, diag::err_defined_macro_name);
90 } else if (isDefineUndef && II->hasMacroDefinition() &&
91 getMacroInfo(II)->isBuiltinMacro()) {
92 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
93 if (isDefineUndef == 1)
94 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
95 else
96 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
97 } else {
98 // Okay, we got a good identifier node. Return it.
99 return;
100 }
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Chris Lattner141e71f2008-03-09 01:54:53 +0000102 // Invalid macro name, read and discard the rest of the line. Then set the
103 // token kind to tok::eom.
104 MacroNameTok.setKind(tok::eom);
105 return DiscardUntilEndOfDirective();
106}
107
108/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattnerab82f412009-04-17 23:30:53 +0000109/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
110/// true, then we consider macros that expand to zero tokens as being ok.
111void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000112 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000113 // Lex unexpanded tokens for most directives: macros might expand to zero
114 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
115 // #line) allow empty macros.
116 if (EnableMacros)
117 Lex(Tmp);
118 else
119 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattner141e71f2008-03-09 01:54:53 +0000121 // There should be no tokens after the directive, but we allow them as an
122 // extension.
123 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
124 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Chris Lattner141e71f2008-03-09 01:54:53 +0000126 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000127 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
128 // because it is more trouble than it is worth to insert /**/ and check that
129 // there is no /**/ in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000130 FixItHint Hint;
Chris Lattner959875a2009-04-14 05:15:20 +0000131 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
Douglas Gregor849b2432010-03-31 17:46:05 +0000132 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
133 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000134 DiscardUntilEndOfDirective();
135 }
136}
137
138
139
140/// SkipExcludedConditionalBlock - We just read a #if or related directive and
141/// decided that the subsequent tokens are in the #if'd out portion of the
142/// file. Lex the rest of the file, until we see an #endif. If
143/// FoundNonSkipPortion is true, then we have already emitted code for part of
144/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
145/// is true, then #else directives are ok, if not, then we have already seen one
146/// so a #else directive is a duplicate. When this returns, the caller can lex
147/// the first valid token.
148void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
149 bool FoundNonSkipPortion,
150 bool FoundElse) {
151 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000152 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000153
Ted Kremenek60e45d42008-11-18 00:34:22 +0000154 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000155 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000156
Ted Kremenek268ee702008-12-12 18:34:08 +0000157 if (CurPTHLexer) {
158 PTHSkipExcludedConditionalBlock();
159 return;
160 }
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Chris Lattner141e71f2008-03-09 01:54:53 +0000162 // Enter raw mode to disable identifier lookup (and thus macro expansion),
163 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000164 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000165 Token Tok;
166 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000167 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Chris Lattner141e71f2008-03-09 01:54:53 +0000169 // If this is the end of the buffer, we have an error.
170 if (Tok.is(tok::eof)) {
171 // Emit errors for each unterminated conditional on the stack, including
172 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000173 while (!CurPPLexer->ConditionalStack.empty()) {
174 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000175 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000176 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000177 }
178
Chris Lattner141e71f2008-03-09 01:54:53 +0000179 // Just return and let the caller lex after this #include.
180 break;
181 }
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Chris Lattner141e71f2008-03-09 01:54:53 +0000183 // If this token is not a preprocessor directive, just skip it.
184 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
185 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattner141e71f2008-03-09 01:54:53 +0000187 // We just parsed a # character at the start of a line, so we're in
188 // directive mode. Tell the lexer this so any newlines we see will be
189 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000190 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000191 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000192
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattner141e71f2008-03-09 01:54:53 +0000194 // Read the next token, the directive flavor.
195 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattner141e71f2008-03-09 01:54:53 +0000197 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
198 // something bogus), skip it.
199 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000200 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000201 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000202 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000203 continue;
204 }
205
206 // If the first letter isn't i or e, it isn't intesting to us. We know that
207 // this is safe in the face of spelling differences, because there is no way
208 // to spell an i/e in a strange way that is another letter. Skipping this
209 // allows us to avoid looking up the identifier info for #define/#undef and
210 // other common directives.
Douglas Gregora5430162010-03-16 20:46:42 +0000211 bool Invalid = false;
212 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation(),
213 &Invalid);
214 if (Invalid)
215 return;
216
Chris Lattner141e71f2008-03-09 01:54:53 +0000217 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000218 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000219 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000220 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000221 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000222 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000223 continue;
224 }
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattner141e71f2008-03-09 01:54:53 +0000226 // Get the identifier name without trigraphs or embedded newlines. Note
227 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
228 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000229 char DirectiveBuf[20];
230 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000231 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000232 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000233 } else {
234 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000235 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000236 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000237 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000238 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000239 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000240 continue;
241 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000242 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
243 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000244 }
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000246 if (Directive.startswith("if")) {
247 llvm::StringRef Sub = Directive.substr(2);
248 if (Sub.empty() || // "if"
249 Sub == "def" || // "ifdef"
250 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000251 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
252 // bother parsing the condition.
253 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000254 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000255 /*foundnonskip*/false,
256 /*fnddelse*/false);
257 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000258 } else if (Directive[0] == 'e') {
259 llvm::StringRef Sub = Directive.substr(1);
260 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000261 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000262 PPConditionalInfo CondInfo;
263 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000264 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000265 InCond = InCond; // Silence warning in no-asserts mode.
266 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattner141e71f2008-03-09 01:54:53 +0000268 // If we popped the outermost skipping block, we're done skipping!
269 if (!CondInfo.WasSkipping)
270 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000271 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000272 // #else directive in a skipping conditional. If not in some other
273 // skipping conditional, and if #else hasn't already been seen, enter it
274 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000275 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000276 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattner141e71f2008-03-09 01:54:53 +0000278 // If this is a #else with a #else before it, report the error.
279 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattner141e71f2008-03-09 01:54:53 +0000281 // Note that we've seen a #else in this conditional.
282 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Chris Lattner141e71f2008-03-09 01:54:53 +0000284 // If the conditional is at the top level, and the #if block wasn't
285 // entered, enter the #else block now.
286 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
287 CondInfo.FoundNonSkip = true;
288 break;
289 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000290 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000291 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000292
293 bool ShouldEnter;
294 // If this is in a skipping block or if we're already handled this #if
295 // block, don't bother parsing the condition.
296 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
297 DiscardUntilEndOfDirective();
298 ShouldEnter = false;
299 } else {
300 // Restore the value of LexingRawMode so that identifiers are
301 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000302 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
303 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000304 IdentifierInfo *IfNDefMacro = 0;
305 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000306 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattner141e71f2008-03-09 01:54:53 +0000309 // If this is a #elif with a #else before it, report the error.
310 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattner141e71f2008-03-09 01:54:53 +0000312 // If this condition is true, enter it!
313 if (ShouldEnter) {
314 CondInfo.FoundNonSkip = true;
315 break;
316 }
317 }
318 }
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Ted Kremenek60e45d42008-11-18 00:34:22 +0000320 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000321 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000322 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000323 }
324
325 // Finally, if we are out of the conditional (saw an #endif or ran off the end
326 // of the file, just stop skipping and return to lexing whatever came after
327 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000328 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000329}
330
Ted Kremenek268ee702008-12-12 18:34:08 +0000331void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000332
333 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000334 assert(CurPTHLexer);
335 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Ted Kremenek268ee702008-12-12 18:34:08 +0000337 // Skip to the next '#else', '#elif', or #endif.
338 if (CurPTHLexer->SkipBlock()) {
339 // We have reached an #endif. Both the '#' and 'endif' tokens
340 // have been consumed by the PTHLexer. Just pop off the condition level.
341 PPConditionalInfo CondInfo;
342 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
343 InCond = InCond; // Silence warning in no-asserts mode.
344 assert(!InCond && "Can't be skipping if not in a conditional!");
345 break;
346 }
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Ted Kremenek268ee702008-12-12 18:34:08 +0000348 // We have reached a '#else' or '#elif'. Lex the next token to get
349 // the directive flavor.
350 Token Tok;
351 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Ted Kremenek268ee702008-12-12 18:34:08 +0000353 // We can actually look up the IdentifierInfo here since we aren't in
354 // raw mode.
355 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
356
357 if (K == tok::pp_else) {
358 // #else: Enter the else condition. We aren't in a nested condition
359 // since we skip those. We're always in the one matching the last
360 // blocked we skipped.
361 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
362 // Note that we've seen a #else in this conditional.
363 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Ted Kremenek268ee702008-12-12 18:34:08 +0000365 // If the #if block wasn't entered then enter the #else block now.
366 if (!CondInfo.FoundNonSkip) {
367 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000369 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000370 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000371 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000372 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Ted Kremenek268ee702008-12-12 18:34:08 +0000374 break;
375 }
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Ted Kremenek268ee702008-12-12 18:34:08 +0000377 // Otherwise skip this block.
378 continue;
379 }
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Ted Kremenek268ee702008-12-12 18:34:08 +0000381 assert(K == tok::pp_elif);
382 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
383
384 // If this is a #elif with a #else before it, report the error.
385 if (CondInfo.FoundElse)
386 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Ted Kremenek268ee702008-12-12 18:34:08 +0000388 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000389 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000390 if (CondInfo.FoundNonSkip)
391 continue;
392
393 // Evaluate the condition of the #elif.
394 IdentifierInfo *IfNDefMacro = 0;
395 CurPTHLexer->ParsingPreprocessorDirective = true;
396 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
397 CurPTHLexer->ParsingPreprocessorDirective = false;
398
399 // If this condition is true, enter it!
400 if (ShouldEnter) {
401 CondInfo.FoundNonSkip = true;
402 break;
403 }
404
405 // Otherwise, skip this block and go to the next one.
406 continue;
407 }
408}
409
Chris Lattner10725092008-03-09 04:17:44 +0000410/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
411/// return null on failure. isAngled indicates whether the file reference is
412/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnera1394812010-01-10 01:35:12 +0000413const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattner10725092008-03-09 04:17:44 +0000414 bool isAngled,
415 const DirectoryLookup *FromDir,
416 const DirectoryLookup *&CurDir) {
417 // If the header lookup mechanism may be relative to the current file, pass in
418 // info about where the current file is.
419 const FileEntry *CurFileEnt = 0;
420 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000421 FileID FID = getCurrentFileLexer()->getFileID();
422 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000424 // If there is no file entry associated with this file, it must be the
425 // predefines buffer. Any other file is not lexed with a normal lexer, so
426 // it won't be scanned for preprocessor directives. If we have the
427 // predefines buffer, resolve #include references (which come from the
428 // -include command line argument) as if they came from the main file, this
429 // affects file lookup etc.
430 if (CurFileEnt == 0) {
431 FID = SourceMgr.getMainFileID();
432 CurFileEnt = SourceMgr.getFileEntryForID(FID);
433 }
Chris Lattner10725092008-03-09 04:17:44 +0000434 }
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Chris Lattner10725092008-03-09 04:17:44 +0000436 // Do a standard file entry lookup.
437 CurDir = CurDirLookup;
438 const FileEntry *FE =
Chris Lattnera1394812010-01-10 01:35:12 +0000439 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000440 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner10725092008-03-09 04:17:44 +0000442 // Otherwise, see if this is a subframework header. If so, this is relative
443 // to one of the headers on the #include stack. Walk the list of the current
444 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000445 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000446 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000447 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000448 return FE;
449 }
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattner10725092008-03-09 04:17:44 +0000451 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
452 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000453 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000454 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000455 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000456 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000457 return FE;
458 }
459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattner10725092008-03-09 04:17:44 +0000461 // Otherwise, we really couldn't find the file.
462 return 0;
463}
464
Chris Lattner141e71f2008-03-09 01:54:53 +0000465
466//===----------------------------------------------------------------------===//
467// Preprocessor Directive Handling.
468//===----------------------------------------------------------------------===//
469
470/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000471/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000472/// lexer/preprocessor state, and advances the lexer(s) so that the next token
473/// read is the correct one.
474void Preprocessor::HandleDirective(Token &Result) {
475 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Chris Lattner141e71f2008-03-09 01:54:53 +0000477 // We just parsed a # character at the start of a line, so we're in directive
478 // mode. Tell the lexer this so any newlines we see will be converted into an
479 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000480 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Chris Lattner141e71f2008-03-09 01:54:53 +0000482 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000483
Chris Lattner141e71f2008-03-09 01:54:53 +0000484 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000485 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000486 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000487 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Chris Lattner42aa16c2009-03-18 21:00:25 +0000489 // Save the '#' token in case we need to return it later.
490 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Chris Lattner141e71f2008-03-09 01:54:53 +0000492 // Read the next token, the directive flavor. This isn't expanded due to
493 // C99 6.10.3p8.
494 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Chris Lattner141e71f2008-03-09 01:54:53 +0000496 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
497 // #define A(x) #x
498 // A(abc
499 // #warning blah
500 // def)
501 // If so, the user is relying on non-portable behavior, emit a diagnostic.
502 if (InMacroArgs)
503 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Chris Lattner141e71f2008-03-09 01:54:53 +0000505TryAgain:
506 switch (Result.getKind()) {
507 case tok::eom:
508 return; // null directive.
509 case tok::comment:
510 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
511 LexUnexpandedToken(Result);
512 goto TryAgain;
513
Chris Lattner478a18e2009-01-26 06:19:46 +0000514 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000515 if (getLangOptions().AsmPreprocessor)
516 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000517 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000518 default:
519 IdentifierInfo *II = Result.getIdentifierInfo();
520 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Chris Lattner141e71f2008-03-09 01:54:53 +0000522 // Ask what the preprocessor keyword ID is.
523 switch (II->getPPKeywordID()) {
524 default: break;
525 // C99 6.10.1 - Conditional Inclusion.
526 case tok::pp_if:
527 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
528 case tok::pp_ifdef:
529 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
530 case tok::pp_ifndef:
531 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
532 case tok::pp_elif:
533 return HandleElifDirective(Result);
534 case tok::pp_else:
535 return HandleElseDirective(Result);
536 case tok::pp_endif:
537 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Chris Lattner141e71f2008-03-09 01:54:53 +0000539 // C99 6.10.2 - Source File Inclusion.
540 case tok::pp_include:
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000541 return HandleIncludeDirective(Result); // Handle #include.
542 case tok::pp___include_macros:
Chris Lattnerde076652009-04-08 18:46:40 +0000543 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner141e71f2008-03-09 01:54:53 +0000545 // C99 6.10.3 - Macro Replacement.
546 case tok::pp_define:
547 return HandleDefineDirective(Result);
548 case tok::pp_undef:
549 return HandleUndefDirective(Result);
550
551 // C99 6.10.4 - Line Control.
552 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000553 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Chris Lattner141e71f2008-03-09 01:54:53 +0000555 // C99 6.10.5 - Error Directive.
556 case tok::pp_error:
557 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattner141e71f2008-03-09 01:54:53 +0000559 // C99 6.10.6 - Pragma Directive.
560 case tok::pp_pragma:
561 return HandlePragmaDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Chris Lattner141e71f2008-03-09 01:54:53 +0000563 // GNU Extensions.
564 case tok::pp_import:
565 return HandleImportDirective(Result);
566 case tok::pp_include_next:
567 return HandleIncludeNextDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattner141e71f2008-03-09 01:54:53 +0000569 case tok::pp_warning:
570 Diag(Result, diag::ext_pp_warning_directive);
571 return HandleUserDiagnosticDirective(Result, true);
572 case tok::pp_ident:
573 return HandleIdentSCCSDirective(Result);
574 case tok::pp_sccs:
575 return HandleIdentSCCSDirective(Result);
576 case tok::pp_assert:
577 //isExtension = true; // FIXME: implement #assert
578 break;
579 case tok::pp_unassert:
580 //isExtension = true; // FIXME: implement #unassert
581 break;
582 }
583 break;
584 }
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner42aa16c2009-03-18 21:00:25 +0000586 // If this is a .S file, treat unknown # directives as non-preprocessor
587 // directives. This is important because # may be a comment or introduce
588 // various pseudo-ops. Just return the # token and push back the following
589 // token to be lexed next time.
590 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000591 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000592 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000593 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000594 Toks[1] = Result;
595 // Enter this token stream so that we re-lex the tokens. Make sure to
596 // enable macro expansion, in case the token after the # is an identifier
597 // that is expanded.
598 EnterTokenStream(Toks, 2, false, true);
599 return;
600 }
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Chris Lattner141e71f2008-03-09 01:54:53 +0000602 // If we reached here, the preprocessing token is not valid!
603 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Chris Lattner141e71f2008-03-09 01:54:53 +0000605 // Read the rest of the PP line.
606 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Chris Lattner141e71f2008-03-09 01:54:53 +0000608 // Okay, we're done parsing the directive.
609}
610
Chris Lattner478a18e2009-01-26 06:19:46 +0000611/// GetLineValue - Convert a numeric token into an unsigned value, emitting
612/// Diagnostic DiagID if it is invalid, and returning the value in Val.
613static bool GetLineValue(Token &DigitTok, unsigned &Val,
614 unsigned DiagID, Preprocessor &PP) {
615 if (DigitTok.isNot(tok::numeric_constant)) {
616 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Chris Lattner478a18e2009-01-26 06:19:46 +0000618 if (DigitTok.isNot(tok::eom))
619 PP.DiscardUntilEndOfDirective();
620 return true;
621 }
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Chris Lattner478a18e2009-01-26 06:19:46 +0000623 llvm::SmallString<64> IntegerBuffer;
624 IntegerBuffer.resize(DigitTok.getLength());
625 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000626 bool Invalid = false;
627 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
628 if (Invalid)
629 return true;
630
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000631 // Verify that we have a simple digit-sequence, and compute the value. This
632 // is always a simple digit string computed in decimal, so we do this manually
633 // here.
634 Val = 0;
635 for (unsigned i = 0; i != ActualLength; ++i) {
636 if (!isdigit(DigitTokBegin[i])) {
637 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
638 diag::err_pp_line_digit_sequence);
639 PP.DiscardUntilEndOfDirective();
640 return true;
641 }
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000643 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
644 if (NextVal < Val) { // overflow.
645 PP.Diag(DigitTok, DiagID);
646 PP.DiscardUntilEndOfDirective();
647 return true;
648 }
649 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000650 }
Mike Stump1eb44332009-09-09 15:08:12 +0000651
652 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000653 if (Val == 0) {
654 PP.Diag(DigitTok, DiagID);
655 PP.DiscardUntilEndOfDirective();
656 return true;
657 }
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000659 if (DigitTokBegin[0] == '0')
660 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Chris Lattner478a18e2009-01-26 06:19:46 +0000662 return false;
663}
664
Mike Stump1eb44332009-09-09 15:08:12 +0000665/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000666/// acceptable forms are:
667/// # line digit-sequence
668/// # line digit-sequence "s-char-sequence"
669void Preprocessor::HandleLineDirective(Token &Tok) {
670 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
671 // expanded.
672 Token DigitTok;
673 Lex(DigitTok);
674
Chris Lattner359cc442009-01-26 05:29:08 +0000675 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000676 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000677 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000678 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000679
Chris Lattner478a18e2009-01-26 06:19:46 +0000680 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
681 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000682 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
683 if (LineNo >= LineLimit)
684 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattner5b9a5042009-01-26 07:57:50 +0000686 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000687 Token StrTok;
688 Lex(StrTok);
689
690 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
691 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000692 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000693 ; // ok
694 else if (StrTok.isNot(tok::string_literal)) {
695 Diag(StrTok, diag::err_pp_line_invalid_filename);
696 DiscardUntilEndOfDirective();
697 return;
698 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000699 // Parse and validate the string, converting it into a unique ID.
700 StringLiteralParser Literal(&StrTok, 1, *this);
701 assert(!Literal.AnyWide && "Didn't allow wide strings in");
702 if (Literal.hadError)
703 return DiscardUntilEndOfDirective();
704 if (Literal.Pascal) {
705 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
706 return DiscardUntilEndOfDirective();
707 }
708 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
709 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Chris Lattnerab82f412009-04-17 23:30:53 +0000711 // Verify that there is nothing after the string, other than EOM. Because
712 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
713 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000714 }
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Chris Lattner4c4ea172009-02-03 21:52:55 +0000716 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattner16629382009-03-27 17:13:49 +0000718 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000719 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
720 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000721 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000722}
723
Chris Lattner478a18e2009-01-26 06:19:46 +0000724/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
725/// marker directive.
726static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
727 bool &IsSystemHeader, bool &IsExternCHeader,
728 Preprocessor &PP) {
729 unsigned FlagVal;
730 Token FlagTok;
731 PP.Lex(FlagTok);
732 if (FlagTok.is(tok::eom)) return false;
733 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
734 return true;
735
736 if (FlagVal == 1) {
737 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Chris Lattner478a18e2009-01-26 06:19:46 +0000739 PP.Lex(FlagTok);
740 if (FlagTok.is(tok::eom)) return false;
741 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
742 return true;
743 } else if (FlagVal == 2) {
744 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Chris Lattner137b6a62009-02-04 06:25:26 +0000746 SourceManager &SM = PP.getSourceManager();
747 // If we are leaving the current presumed file, check to make sure the
748 // presumed include stack isn't empty!
749 FileID CurFileID =
750 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
751 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Chris Lattner137b6a62009-02-04 06:25:26 +0000753 // If there is no include loc (main file) or if the include loc is in a
754 // different physical file, then we aren't in a "1" line marker flag region.
755 SourceLocation IncLoc = PLoc.getIncludeLoc();
756 if (IncLoc.isInvalid() ||
757 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
758 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
759 PP.DiscardUntilEndOfDirective();
760 return true;
761 }
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Chris Lattner478a18e2009-01-26 06:19:46 +0000763 PP.Lex(FlagTok);
764 if (FlagTok.is(tok::eom)) return false;
765 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
766 return true;
767 }
768
769 // We must have 3 if there are still flags.
770 if (FlagVal != 3) {
771 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000772 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000773 return true;
774 }
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Chris Lattner478a18e2009-01-26 06:19:46 +0000776 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Chris Lattner478a18e2009-01-26 06:19:46 +0000778 PP.Lex(FlagTok);
779 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000780 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000781 return true;
782
783 // We must have 4 if there is yet another flag.
784 if (FlagVal != 4) {
785 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000786 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000787 return true;
788 }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Chris Lattner478a18e2009-01-26 06:19:46 +0000790 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Chris Lattner478a18e2009-01-26 06:19:46 +0000792 PP.Lex(FlagTok);
793 if (FlagTok.is(tok::eom)) return false;
794
795 // There are no more valid flags here.
796 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000797 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000798 return true;
799}
800
801/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
802/// one of the following forms:
803///
804/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000805/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000806/// # 42 "file" ('1' | '2')? '3' '4'?
807///
808void Preprocessor::HandleDigitDirective(Token &DigitTok) {
809 // Validate the number and convert it to an unsigned. GNU does not have a
810 // line # limit other than it fit in 32-bits.
811 unsigned LineNo;
812 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
813 *this))
814 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Chris Lattner478a18e2009-01-26 06:19:46 +0000816 Token StrTok;
817 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Chris Lattner478a18e2009-01-26 06:19:46 +0000819 bool IsFileEntry = false, IsFileExit = false;
820 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000821 int FilenameID = -1;
822
Chris Lattner478a18e2009-01-26 06:19:46 +0000823 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
824 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000825 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000826 ; // ok
827 else if (StrTok.isNot(tok::string_literal)) {
828 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000829 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000830 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000831 // Parse and validate the string, converting it into a unique ID.
832 StringLiteralParser Literal(&StrTok, 1, *this);
833 assert(!Literal.AnyWide && "Didn't allow wide strings in");
834 if (Literal.hadError)
835 return DiscardUntilEndOfDirective();
836 if (Literal.Pascal) {
837 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
838 return DiscardUntilEndOfDirective();
839 }
840 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
841 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Chris Lattner478a18e2009-01-26 06:19:46 +0000843 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000844 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000845 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000846 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000847 }
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Chris Lattner9d79eba2009-02-04 05:21:58 +0000849 // Create a line note with this information.
850 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000851 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000852 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Chris Lattner16629382009-03-27 17:13:49 +0000854 // If the preprocessor has callbacks installed, notify them of the #line
855 // change. This is used so that the line marker comes out in -E mode for
856 // example.
857 if (Callbacks) {
858 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
859 if (IsFileEntry)
860 Reason = PPCallbacks::EnterFile;
861 else if (IsFileExit)
862 Reason = PPCallbacks::ExitFile;
863 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
864 if (IsExternCHeader)
865 FileKind = SrcMgr::C_ExternCSystem;
866 else if (IsSystemHeader)
867 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Chris Lattner86d0ef72010-04-14 04:28:50 +0000869 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000870 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000871}
872
873
Chris Lattner099dd052009-01-26 05:30:54 +0000874/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
875///
Mike Stump1eb44332009-09-09 15:08:12 +0000876void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000877 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000878 // PTH doesn't emit #warning or #error directives.
879 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000880 return CurPTHLexer->DiscardToEndOfLine();
881
Chris Lattner141e71f2008-03-09 01:54:53 +0000882 // Read the rest of the line raw. We do this because we don't want macros
883 // to be expanded and we don't require that the tokens be valid preprocessing
884 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
885 // collapse multiple consequtive white space between tokens, but this isn't
886 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000887 std::string Message = CurLexer->ReadToEndOfLine();
888 if (isWarning)
889 Diag(Tok, diag::pp_hash_warning) << Message;
890 else
891 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000892}
893
894/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
895///
896void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
897 // Yes, this directive is an extension.
898 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner141e71f2008-03-09 01:54:53 +0000900 // Read the string argument.
901 Token StrTok;
902 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner141e71f2008-03-09 01:54:53 +0000904 // If the token kind isn't a string, it's a malformed directive.
905 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000906 StrTok.isNot(tok::wide_string_literal)) {
907 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000908 if (StrTok.isNot(tok::eom))
909 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000910 return;
911 }
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Chris Lattner141e71f2008-03-09 01:54:53 +0000913 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000914 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000915
Douglas Gregor453091c2010-03-16 22:30:13 +0000916 if (Callbacks) {
917 bool Invalid = false;
918 std::string Str = getSpelling(StrTok, &Invalid);
919 if (!Invalid)
920 Callbacks->Ident(Tok.getLocation(), Str);
921 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000922}
923
924//===----------------------------------------------------------------------===//
925// Preprocessor Include Directive Handling.
926//===----------------------------------------------------------------------===//
927
928/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
929/// checked and spelled filename, e.g. as an operand of #include. This returns
930/// true if the input filename was in <>'s or false if it were in ""'s. The
931/// caller is expected to provide a buffer that is large enough to hold the
932/// spelling of the filename, but is also expected to handle the case when
933/// this method decides to use a different buffer.
934bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000935 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000936 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000937 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner141e71f2008-03-09 01:54:53 +0000939 // Make sure the filename is <x> or "x".
940 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000941 if (Buffer[0] == '<') {
942 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000943 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000944 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000945 return true;
946 }
947 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +0000948 } else if (Buffer[0] == '"') {
949 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +0000950 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000951 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000952 return true;
953 }
954 isAngled = false;
955 } else {
956 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000957 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +0000958 return true;
959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattner141e71f2008-03-09 01:54:53 +0000961 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +0000962 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000963 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +0000964 Buffer = llvm::StringRef();
965 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000966 }
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Chris Lattner141e71f2008-03-09 01:54:53 +0000968 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +0000969 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +0000970 return isAngled;
971}
972
973/// ConcatenateIncludeName - Handle cases where the #include name is expanded
974/// from a macro as multiple tokens, which need to be glued together. This
975/// occurs for code like:
976/// #define FOO <a/b.h>
977/// #include FOO
978/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
979///
980/// This code concatenates and consumes tokens up to the '>' token. It returns
981/// false if the > was found, otherwise it returns true if it finds and consumes
982/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +0000983bool Preprocessor::ConcatenateIncludeName(
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000984 llvm::SmallString<128> &FilenameBuffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000985 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +0000986
John Thompsona28cc092009-10-30 13:49:06 +0000987 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000988 while (CurTok.isNot(tok::eom)) {
989 // Append the spelling of this token to the buffer. If there was a space
990 // before it, add it now.
991 if (CurTok.hasLeadingSpace())
992 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner141e71f2008-03-09 01:54:53 +0000994 // Get the spelling of the token, directly into FilenameBuffer if possible.
995 unsigned PreAppendSize = FilenameBuffer.size();
996 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Chris Lattner141e71f2008-03-09 01:54:53 +0000998 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +0000999 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattner141e71f2008-03-09 01:54:53 +00001001 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1002 if (BufPtr != &FilenameBuffer[PreAppendSize])
1003 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Chris Lattner141e71f2008-03-09 01:54:53 +00001005 // Resize FilenameBuffer to the correct size.
1006 if (CurTok.getLength() != ActualLen)
1007 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattner141e71f2008-03-09 01:54:53 +00001009 // If we found the '>' marker, return success.
1010 if (CurTok.is(tok::greater))
1011 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001012
John Thompsona28cc092009-10-30 13:49:06 +00001013 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001014 }
1015
1016 // If we hit the eom marker, emit an error and return true so that the caller
1017 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001018 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001019 return true;
1020}
1021
1022/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1023/// file to be included from the lexer, then include it! This is a common
1024/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001025/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001026/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +00001027void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1028 const DirectoryLookup *LookupFrom,
1029 bool isImport) {
1030
1031 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001032 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Chris Lattner141e71f2008-03-09 01:54:53 +00001034 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001035 llvm::SmallString<128> FilenameBuffer;
1036 llvm::StringRef Filename;
Chris Lattner141e71f2008-03-09 01:54:53 +00001037
1038 switch (FilenameTok.getKind()) {
1039 case tok::eom:
1040 // If the token kind is EOM, the error has already been diagnosed.
1041 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Chris Lattner141e71f2008-03-09 01:54:53 +00001043 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001044 case tok::string_literal:
1045 Filename = getSpelling(FilenameTok, FilenameBuffer);
Chris Lattner141e71f2008-03-09 01:54:53 +00001046 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Chris Lattner141e71f2008-03-09 01:54:53 +00001048 case tok::less:
1049 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1050 // case, glue the tokens together into FilenameBuffer and interpret those.
1051 FilenameBuffer.push_back('<');
John Thompsona28cc092009-10-30 13:49:06 +00001052 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattner141e71f2008-03-09 01:54:53 +00001053 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001054 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001055 break;
1056 default:
1057 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1058 DiscardUntilEndOfDirective();
1059 return;
1060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001062 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001063 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001064 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1065 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001066 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001067 DiscardUntilEndOfDirective();
1068 return;
1069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001071 // Verify that there is nothing after the filename, other than EOM. Note that
1072 // we allow macros that expand to nothing after the filename, because this
1073 // falls into the category of "#include pp-tokens new-line" specified in
1074 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001075 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001076
1077 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001078 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1079 Diag(FilenameTok, diag::err_pp_include_too_deep);
1080 return;
1081 }
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Chris Lattner141e71f2008-03-09 01:54:53 +00001083 // Search include directories.
1084 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +00001085 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001086 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001087 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001088 return;
1089 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001090
Chris Lattner72181832008-09-26 20:12:23 +00001091 // The #included file will be considered to be a system header if either it is
1092 // in a system include directory, or if the #includer is a system include
1093 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001094 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001095 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001096 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001098 // Ask HeaderInfo if we should enter this #include file. If not, #including
1099 // this file will have no effect.
1100 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001101 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001102 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001103 return;
1104 }
1105
Chris Lattner141e71f2008-03-09 01:54:53 +00001106 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001107 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1108 FileCharacter);
1109 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001110 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001111 return;
1112 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001113
1114 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001115 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001116}
1117
1118/// HandleIncludeNextDirective - Implements #include_next.
1119///
1120void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1121 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Chris Lattner141e71f2008-03-09 01:54:53 +00001123 // #include_next is like #include, except that we start searching after
1124 // the current found directory. If we can't do this, issue a
1125 // diagnostic.
1126 const DirectoryLookup *Lookup = CurDirLookup;
1127 if (isInPrimaryFile()) {
1128 Lookup = 0;
1129 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1130 } else if (Lookup == 0) {
1131 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1132 } else {
1133 // Start looking up in the next directory.
1134 ++Lookup;
1135 }
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattner141e71f2008-03-09 01:54:53 +00001137 return HandleIncludeDirective(IncludeNextTok, Lookup);
1138}
1139
1140/// HandleImportDirective - Implements #import.
1141///
1142void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001143 if (!Features.ObjC1) // #import is standard for ObjC.
1144 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Chris Lattner141e71f2008-03-09 01:54:53 +00001146 return HandleIncludeDirective(ImportTok, 0, true);
1147}
1148
Chris Lattnerde076652009-04-08 18:46:40 +00001149/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1150/// pseudo directive in the predefines buffer. This handles it by sucking all
1151/// tokens through the preprocessor and discarding them (only keeping the side
1152/// effects on the preprocessor).
1153void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1154 // This directive should only occur in the predefines buffer. If not, emit an
1155 // error and reject it.
1156 SourceLocation Loc = IncludeMacrosTok.getLocation();
1157 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1158 Diag(IncludeMacrosTok.getLocation(),
1159 diag::pp_include_macros_out_of_predefines);
1160 DiscardUntilEndOfDirective();
1161 return;
1162 }
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Chris Lattnerfd105112009-04-08 20:53:24 +00001164 // Treat this as a normal #include for checking purposes. If this is
1165 // successful, it will push a new lexer onto the include stack.
1166 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Chris Lattnerfd105112009-04-08 20:53:24 +00001168 Token TmpTok;
1169 do {
1170 Lex(TmpTok);
1171 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1172 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001173}
1174
Chris Lattner141e71f2008-03-09 01:54:53 +00001175//===----------------------------------------------------------------------===//
1176// Preprocessor Macro Directive Handling.
1177//===----------------------------------------------------------------------===//
1178
1179/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1180/// definition has just been read. Lex the rest of the arguments and the
1181/// closing ), updating MI with what we learn. Return true if an error occurs
1182/// parsing the arg list.
1183bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1184 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Chris Lattner141e71f2008-03-09 01:54:53 +00001186 Token Tok;
1187 while (1) {
1188 LexUnexpandedToken(Tok);
1189 switch (Tok.getKind()) {
1190 case tok::r_paren:
1191 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001192 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001193 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001194 // Otherwise we have #define FOO(A,)
1195 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1196 return true;
1197 case tok::ellipsis: // #define X(... -> C99 varargs
1198 // Warn if use of C99 feature in non-C99 mode.
1199 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1200
1201 // Lex the token after the identifier.
1202 LexUnexpandedToken(Tok);
1203 if (Tok.isNot(tok::r_paren)) {
1204 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1205 return true;
1206 }
1207 // Add the __VA_ARGS__ identifier as an argument.
1208 Arguments.push_back(Ident__VA_ARGS__);
1209 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001210 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001211 return false;
1212 case tok::eom: // #define X(
1213 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1214 return true;
1215 default:
1216 // Handle keywords and identifiers here to accept things like
1217 // #define Foo(for) for.
1218 IdentifierInfo *II = Tok.getIdentifierInfo();
1219 if (II == 0) {
1220 // #define X(1
1221 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1222 return true;
1223 }
1224
1225 // If this is already used as an argument, it is used multiple times (e.g.
1226 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001227 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001228 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001229 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001230 return true;
1231 }
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Chris Lattner141e71f2008-03-09 01:54:53 +00001233 // Add the argument to the macro info.
1234 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Chris Lattner141e71f2008-03-09 01:54:53 +00001236 // Lex the token after the identifier.
1237 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Chris Lattner141e71f2008-03-09 01:54:53 +00001239 switch (Tok.getKind()) {
1240 default: // #define X(A B
1241 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1242 return true;
1243 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001244 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001245 return false;
1246 case tok::comma: // #define X(A,
1247 break;
1248 case tok::ellipsis: // #define X(A... -> GCC extension
1249 // Diagnose extension.
1250 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Chris Lattner141e71f2008-03-09 01:54:53 +00001252 // Lex the token after the identifier.
1253 LexUnexpandedToken(Tok);
1254 if (Tok.isNot(tok::r_paren)) {
1255 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1256 return true;
1257 }
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Chris Lattner141e71f2008-03-09 01:54:53 +00001259 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001260 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001261 return false;
1262 }
1263 }
1264 }
1265}
1266
1267/// HandleDefineDirective - Implements #define. This consumes the entire macro
1268/// line then lets the caller lex the next real token.
1269void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1270 ++NumDefined;
1271
1272 Token MacroNameTok;
1273 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Chris Lattner141e71f2008-03-09 01:54:53 +00001275 // Error reading macro name? If so, diagnostic already issued.
1276 if (MacroNameTok.is(tok::eom))
1277 return;
1278
Chris Lattner2451b522009-04-21 04:46:33 +00001279 Token LastTok = MacroNameTok;
1280
Chris Lattner141e71f2008-03-09 01:54:53 +00001281 // If we are supposed to keep comments in #defines, reenable comment saving
1282 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001283 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Chris Lattner141e71f2008-03-09 01:54:53 +00001285 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001286 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Chris Lattner141e71f2008-03-09 01:54:53 +00001288 Token Tok;
1289 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Chris Lattner141e71f2008-03-09 01:54:53 +00001291 // If this is a function-like macro definition, parse the argument list,
1292 // marking each of the identifiers as being used as macro arguments. Also,
1293 // check other constraints on the first token of the macro body.
1294 if (Tok.is(tok::eom)) {
1295 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001296 } else if (Tok.hasLeadingSpace()) {
1297 // This is a normal token with leading space. Clear the leading space
1298 // marker on the first token to get proper expansion.
1299 Tok.clearFlag(Token::LeadingSpace);
1300 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001301 // This is a function-like macro definition. Read the argument list.
1302 MI->setIsFunctionLike();
1303 if (ReadMacroDefinitionArgList(MI)) {
1304 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001305 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001306 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001307 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001308 DiscardUntilEndOfDirective();
1309 return;
1310 }
1311
Chris Lattner8fde5972009-04-19 18:26:34 +00001312 // If this is a definition of a variadic C99 function-like macro, not using
1313 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Chris Lattner8fde5972009-04-19 18:26:34 +00001315 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1316 // This gets unpoisoned where it is allowed.
1317 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1318 if (MI->isC99Varargs())
1319 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Chris Lattner141e71f2008-03-09 01:54:53 +00001321 // Read the first token after the arg list for down below.
1322 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001323 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001324 // C99 requires whitespace between the macro definition and the body. Emit
1325 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001326 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001327 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001328 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1329 // first character of a replacement list is not a character required by
1330 // subclause 5.2.1, then there shall be white-space separation between the
1331 // identifier and the replacement list.". 5.2.1 lists this set:
1332 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1333 // is irrelevant here.
1334 bool isInvalid = false;
1335 if (Tok.is(tok::at)) // @ is not in the list above.
1336 isInvalid = true;
1337 else if (Tok.is(tok::unknown)) {
1338 // If we have an unknown token, it is something strange like "`". Since
1339 // all of valid characters would have lexed into a single character
1340 // token of some sort, we know this is not a valid case.
1341 isInvalid = true;
1342 }
1343 if (isInvalid)
1344 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1345 else
1346 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001347 }
Chris Lattner2451b522009-04-21 04:46:33 +00001348
1349 if (!Tok.is(tok::eom))
1350 LastTok = Tok;
1351
Chris Lattner141e71f2008-03-09 01:54:53 +00001352 // Read the rest of the macro body.
1353 if (MI->isObjectLike()) {
1354 // Object-like macros are very simple, just read their body.
1355 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001356 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001357 MI->AddTokenToBody(Tok);
1358 // Get the next token of the macro.
1359 LexUnexpandedToken(Tok);
1360 }
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Chris Lattner141e71f2008-03-09 01:54:53 +00001362 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001363 // Otherwise, read the body of a function-like macro. While we are at it,
1364 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1365 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001366 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001367 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001368
Chris Lattner141e71f2008-03-09 01:54:53 +00001369 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001370 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Chris Lattner141e71f2008-03-09 01:54:53 +00001372 // Get the next token of the macro.
1373 LexUnexpandedToken(Tok);
1374 continue;
1375 }
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Chris Lattner141e71f2008-03-09 01:54:53 +00001377 // Get the next token of the macro.
1378 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Chris Lattner32404692009-05-25 17:16:10 +00001380 // Check for a valid macro arg identifier.
1381 if (Tok.getIdentifierInfo() == 0 ||
1382 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1383
1384 // If this is assembler-with-cpp mode, we accept random gibberish after
1385 // the '#' because '#' is often a comment character. However, change
1386 // the kind of the token to tok::unknown so that the preprocessor isn't
1387 // confused.
1388 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1389 LastTok.setKind(tok::unknown);
1390 } else {
1391 Diag(Tok, diag::err_pp_stringize_not_parameter);
1392 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Chris Lattner32404692009-05-25 17:16:10 +00001394 // Disable __VA_ARGS__ again.
1395 Ident__VA_ARGS__->setIsPoisoned(true);
1396 return;
1397 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001398 }
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Chris Lattner32404692009-05-25 17:16:10 +00001400 // Things look ok, add the '#' and param name tokens to the macro.
1401 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001402 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001403 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Chris Lattner141e71f2008-03-09 01:54:53 +00001405 // Get the next token of the macro.
1406 LexUnexpandedToken(Tok);
1407 }
1408 }
Mike Stump1eb44332009-09-09 15:08:12 +00001409
1410
Chris Lattner141e71f2008-03-09 01:54:53 +00001411 // Disable __VA_ARGS__ again.
1412 Ident__VA_ARGS__->setIsPoisoned(true);
1413
1414 // Check that there is no paste (##) operator at the begining or end of the
1415 // replacement list.
1416 unsigned NumTokens = MI->getNumTokens();
1417 if (NumTokens != 0) {
1418 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1419 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001420 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001421 return;
1422 }
1423 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1424 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001425 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001426 return;
1427 }
1428 }
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Chris Lattner141e71f2008-03-09 01:54:53 +00001430 // If this is the primary source file, remember that this macro hasn't been
1431 // used yet.
1432 if (isInPrimaryFile())
1433 MI->setIsUsed(false);
Chris Lattner2451b522009-04-21 04:46:33 +00001434
1435 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Chris Lattner141e71f2008-03-09 01:54:53 +00001437 // Finally, if this identifier already had a macro defined for it, verify that
1438 // the macro bodies are identical and free the old definition.
1439 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001440 // It is very common for system headers to have tons of macro redefinitions
1441 // and for warnings to be disabled in system headers. If this is the case,
1442 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001443 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001444 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1445 if (!OtherMI->isUsed())
1446 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001447
Chris Lattner41c3ae12009-01-16 19:50:11 +00001448 // Macros must be identical. This means all tokes and whitespace
1449 // separation must be the same. C99 6.10.3.2.
1450 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1451 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1452 << MacroNameTok.getIdentifierInfo();
1453 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1454 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001455 }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Ted Kremenek0ea76722008-12-15 19:56:42 +00001457 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001458 }
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Chris Lattner141e71f2008-03-09 01:54:53 +00001460 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001462 // If the callbacks want to know, tell them about the macro definition.
1463 if (Callbacks)
1464 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001465}
1466
1467/// HandleUndefDirective - Implements #undef.
1468///
1469void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1470 ++NumUndefined;
1471
1472 Token MacroNameTok;
1473 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Chris Lattner141e71f2008-03-09 01:54:53 +00001475 // Error reading macro name? If so, diagnostic already issued.
1476 if (MacroNameTok.is(tok::eom))
1477 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Chris Lattner141e71f2008-03-09 01:54:53 +00001479 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001480 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Chris Lattner141e71f2008-03-09 01:54:53 +00001482 // Okay, we finally have a valid identifier to undef.
1483 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Chris Lattner141e71f2008-03-09 01:54:53 +00001485 // If the macro is not defined, this is a noop undef, just return.
1486 if (MI == 0) return;
1487
1488 if (!MI->isUsed())
1489 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001490
1491 // If the callbacks want to know, tell them about the macro #undef.
1492 if (Callbacks)
1493 Callbacks->MacroUndefined(MacroNameTok.getIdentifierInfo(), MI);
1494
Chris Lattner141e71f2008-03-09 01:54:53 +00001495 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001496 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001497 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1498}
1499
1500
1501//===----------------------------------------------------------------------===//
1502// Preprocessor Conditional Directive Handling.
1503//===----------------------------------------------------------------------===//
1504
1505/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1506/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1507/// if any tokens have been returned or pp-directives activated before this
1508/// #ifndef has been lexed.
1509///
1510void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1511 bool ReadAnyTokensBeforeDirective) {
1512 ++NumIf;
1513 Token DirectiveTok = Result;
1514
1515 Token MacroNameTok;
1516 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Chris Lattner141e71f2008-03-09 01:54:53 +00001518 // Error reading macro name? If so, diagnostic already issued.
1519 if (MacroNameTok.is(tok::eom)) {
1520 // Skip code until we get to #endif. This helps with recovery by not
1521 // emitting an error when the #endif is reached.
1522 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1523 /*Foundnonskip*/false, /*FoundElse*/false);
1524 return;
1525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Chris Lattner141e71f2008-03-09 01:54:53 +00001527 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001528 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001529
Chris Lattner13d283d2010-02-12 08:03:27 +00001530 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1531 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001532
Ted Kremenek60e45d42008-11-18 00:34:22 +00001533 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001534 // If the start of a top-level #ifdef and if the macro is not defined,
1535 // inform MIOpt that this might be the start of a proper include guard.
1536 // Otherwise it is some other form of unknown conditional which we can't
1537 // handle.
1538 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001539 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001540 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001541 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001542 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001543 }
1544
Chris Lattner141e71f2008-03-09 01:54:53 +00001545 // If there is a macro, process it.
1546 if (MI) // Mark it used.
1547 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Chris Lattner141e71f2008-03-09 01:54:53 +00001549 // Should we include the stuff contained by this directive?
1550 if (!MI == isIfndef) {
1551 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001552 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1553 /*wasskip*/false, /*foundnonskip*/true,
1554 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001555 } else {
1556 // No, skip the contents of this block and return the first token after it.
1557 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001558 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001559 /*FoundElse*/false);
1560 }
1561}
1562
1563/// HandleIfDirective - Implements the #if directive.
1564///
1565void Preprocessor::HandleIfDirective(Token &IfToken,
1566 bool ReadAnyTokensBeforeDirective) {
1567 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Chris Lattner141e71f2008-03-09 01:54:53 +00001569 // Parse and evaluation the conditional expression.
1570 IdentifierInfo *IfNDefMacro = 0;
1571 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Nuno Lopes0049db62008-06-01 18:31:24 +00001573
1574 // If this condition is equivalent to #ifndef X, and if this is the first
1575 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001576 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001577 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001578 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001579 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001580 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001581 }
1582
Chris Lattner141e71f2008-03-09 01:54:53 +00001583 // Should we include the stuff contained by this directive?
1584 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001585 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001586 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001587 /*foundnonskip*/true, /*foundelse*/false);
1588 } else {
1589 // No, skip the contents of this block and return the first token after it.
Mike Stump1eb44332009-09-09 15:08:12 +00001590 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001591 /*FoundElse*/false);
1592 }
1593}
1594
1595/// HandleEndifDirective - Implements the #endif directive.
1596///
1597void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1598 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Chris Lattner141e71f2008-03-09 01:54:53 +00001600 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001601 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Chris Lattner141e71f2008-03-09 01:54:53 +00001603 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001604 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001605 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001606 Diag(EndifToken, diag::err_pp_endif_without_if);
1607 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001608 }
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Chris Lattner141e71f2008-03-09 01:54:53 +00001610 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001611 if (CurPPLexer->getConditionalStackDepth() == 0)
1612 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Ted Kremenek60e45d42008-11-18 00:34:22 +00001614 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001615 "This code should only be reachable in the non-skipping case!");
1616}
1617
1618
1619void Preprocessor::HandleElseDirective(Token &Result) {
1620 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Chris Lattner141e71f2008-03-09 01:54:53 +00001622 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001623 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Chris Lattner141e71f2008-03-09 01:54:53 +00001625 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001626 if (CurPPLexer->popConditionalLevel(CI)) {
1627 Diag(Result, diag::pp_err_else_without_if);
1628 return;
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Chris Lattner141e71f2008-03-09 01:54:53 +00001631 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001632 if (CurPPLexer->getConditionalStackDepth() == 0)
1633 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001634
1635 // If this is a #else with a #else before it, report the error.
1636 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Chris Lattner141e71f2008-03-09 01:54:53 +00001638 // Finally, skip the rest of the contents of this block and return the first
1639 // token after it.
1640 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1641 /*FoundElse*/true);
1642}
1643
1644void Preprocessor::HandleElifDirective(Token &ElifToken) {
1645 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Chris Lattner141e71f2008-03-09 01:54:53 +00001647 // #elif directive in a non-skipping conditional... start skipping.
1648 // We don't care what the condition is, because we will always skip it (since
1649 // the block immediately before it was included).
1650 DiscardUntilEndOfDirective();
1651
1652 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001653 if (CurPPLexer->popConditionalLevel(CI)) {
1654 Diag(ElifToken, diag::pp_err_elif_without_if);
1655 return;
1656 }
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Chris Lattner141e71f2008-03-09 01:54:53 +00001658 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001659 if (CurPPLexer->getConditionalStackDepth() == 0)
1660 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Chris Lattner141e71f2008-03-09 01:54:53 +00001662 // If this is a #elif with a #else before it, report the error.
1663 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1664
1665 // Finally, skip the rest of the contents of this block and return the first
1666 // token after it.
1667 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1668 /*FoundElse*/CI.FoundElse);
1669}