blob: 53619f923a9a5fb38c3d74ee228276a1073f56fe [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-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 Lattner100c65e2009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Chris Lattner710bb872009-11-30 04:18:44 +000019#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000021#include "llvm/ADT/APInt.h"
Douglas Gregord26129a2010-08-06 12:06:13 +000022#include "llvm/System/Path.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000023using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// Utility Methods for Preprocessor Directive Handling.
27//===----------------------------------------------------------------------===//
28
Chris Lattner666f7a42009-02-20 22:19:20 +000029MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
Ted Kremenek6c7ea112008-12-15 19:56:42 +000030 MacroInfo *MI;
Mike Stump11289f42009-09-09 15:08:12 +000031
Ted Kremenek6c7ea112008-12-15 19:56:42 +000032 if (!MICache.empty()) {
33 MI = MICache.back();
34 MICache.pop_back();
Chris Lattner666f7a42009-02-20 22:19:20 +000035 } else
36 MI = (MacroInfo*) BP.Allocate<MacroInfo>();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000037 new (MI) MacroInfo(L);
38 return MI;
39}
40
Chris Lattner666f7a42009-02-20 22:19:20 +000041/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
42/// be reused for allocating new MacroInfo objects.
43void Preprocessor::ReleaseMacroInfo(MacroInfo* MI) {
44 MICache.push_back(MI);
Chris Lattner70946da2009-02-20 22:46:43 +000045 MI->FreeArgumentList(BP);
Chris Lattner666f7a42009-02-20 22:19:20 +000046}
47
48
Chris Lattnerf64b3522008-03-09 01:54:53 +000049/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
50/// current line until the tok::eom token is found.
51void Preprocessor::DiscardUntilEndOfDirective() {
52 Token Tmp;
53 do {
54 LexUnexpandedToken(Tmp);
55 } while (Tmp.isNot(tok::eom));
56}
57
Chris Lattnerf64b3522008-03-09 01:54:53 +000058/// ReadMacroName - Lex and validate a macro name, which occurs after a
59/// #define or #undef. This sets the token kind to eom and discards the rest
60/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
61/// this is due to a a #define, 2 if #undef directive, 0 if it is something
62/// else (e.g. #ifdef).
63void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
64 // Read the token, don't allow macro expansion on it.
65 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +000066
Chris Lattnerf64b3522008-03-09 01:54:53 +000067 // Missing macro name?
Chris Lattner907dfe92008-11-18 07:59:24 +000068 if (MacroNameTok.is(tok::eom)) {
69 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
70 return;
71 }
Mike Stump11289f42009-09-09 15:08:12 +000072
Chris Lattnerf64b3522008-03-09 01:54:53 +000073 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
74 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +000075 bool Invalid = false;
76 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
77 if (Invalid)
78 return;
79
Chris Lattner77c76ae2008-12-13 20:12:40 +000080 const IdentifierInfo &Info = Identifiers.get(Spelling);
81 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +000082 // C++ 2.5p2: Alternative tokens behave the same as its primary token
83 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +000084 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +000085 else
86 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
87 // Fall through on error.
88 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
89 // Error if defining "defined": C99 6.10.8.4.
90 Diag(MacroNameTok, diag::err_defined_macro_name);
91 } else if (isDefineUndef && II->hasMacroDefinition() &&
92 getMacroInfo(II)->isBuiltinMacro()) {
93 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
94 if (isDefineUndef == 1)
95 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
96 else
97 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
98 } else {
99 // Okay, we got a good identifier node. Return it.
100 return;
101 }
Mike Stump11289f42009-09-09 15:08:12 +0000102
Chris Lattnerf64b3522008-03-09 01:54:53 +0000103 // Invalid macro name, read and discard the rest of the line. Then set the
104 // token kind to tok::eom.
105 MacroNameTok.setKind(tok::eom);
106 return DiscardUntilEndOfDirective();
107}
108
109/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattner0003c272009-04-17 23:30:53 +0000110/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
111/// true, then we consider macros that expand to zero tokens as being ok.
112void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000113 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000114 // Lex unexpanded tokens for most directives: macros might expand to zero
115 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
116 // #line) allow empty macros.
117 if (EnableMacros)
118 Lex(Tmp);
119 else
120 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000121
Chris Lattnerf64b3522008-03-09 01:54:53 +0000122 // There should be no tokens after the directive, but we allow them as an
123 // extension.
124 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
125 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000126
Chris Lattnerf64b3522008-03-09 01:54:53 +0000127 if (Tmp.isNot(tok::eom)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000128 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
129 // because it is more trouble than it is worth to insert /**/ and check that
130 // there is no /**/ in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000131 FixItHint Hint;
Chris Lattner825676a2009-04-14 05:15:20 +0000132 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
Douglas Gregora771f462010-03-31 17:46:05 +0000133 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
134 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000135 DiscardUntilEndOfDirective();
136 }
137}
138
139
140
141/// SkipExcludedConditionalBlock - We just read a #if or related directive and
142/// decided that the subsequent tokens are in the #if'd out portion of the
143/// file. Lex the rest of the file, until we see an #endif. If
144/// FoundNonSkipPortion is true, then we have already emitted code for part of
145/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
146/// is true, then #else directives are ok, if not, then we have already seen one
147/// so a #else directive is a duplicate. When this returns, the caller can lex
148/// the first valid token.
149void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
150 bool FoundNonSkipPortion,
151 bool FoundElse) {
152 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000153 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000154
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000155 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000156 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000157
Ted Kremenek56572ab2008-12-12 18:34:08 +0000158 if (CurPTHLexer) {
159 PTHSkipExcludedConditionalBlock();
160 return;
161 }
Mike Stump11289f42009-09-09 15:08:12 +0000162
Chris Lattnerf64b3522008-03-09 01:54:53 +0000163 // Enter raw mode to disable identifier lookup (and thus macro expansion),
164 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000165 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000166 Token Tok;
167 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000168 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Chris Lattnerf64b3522008-03-09 01:54:53 +0000170 // If this is the end of the buffer, we have an error.
171 if (Tok.is(tok::eof)) {
172 // Emit errors for each unterminated conditional on the stack, including
173 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000174 while (!CurPPLexer->ConditionalStack.empty()) {
175 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000176 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000177 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000178 }
179
Chris Lattnerf64b3522008-03-09 01:54:53 +0000180 // Just return and let the caller lex after this #include.
181 break;
182 }
Mike Stump11289f42009-09-09 15:08:12 +0000183
Chris Lattnerf64b3522008-03-09 01:54:53 +0000184 // If this token is not a preprocessor directive, just skip it.
185 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
186 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000187
Chris Lattnerf64b3522008-03-09 01:54:53 +0000188 // We just parsed a # character at the start of a line, so we're in
189 // directive mode. Tell the lexer this so any newlines we see will be
190 // converted into an EOM token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000191 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000192 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000193
Mike Stump11289f42009-09-09 15:08:12 +0000194
Chris Lattnerf64b3522008-03-09 01:54:53 +0000195 // Read the next token, the directive flavor.
196 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattnerf64b3522008-03-09 01:54:53 +0000198 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
199 // something bogus), skip it.
200 if (Tok.isNot(tok::identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000201 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000202 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000203 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000204 continue;
205 }
206
207 // If the first letter isn't i or e, it isn't intesting to us. We know that
208 // this is safe in the face of spelling differences, because there is no way
209 // to spell an i/e in a strange way that is another letter. Skipping this
210 // allows us to avoid looking up the identifier info for #define/#undef and
211 // other common directives.
Douglas Gregor42fe8582010-03-16 20:46:42 +0000212 bool Invalid = false;
213 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation(),
214 &Invalid);
215 if (Invalid)
216 return;
217
Chris Lattnerf64b3522008-03-09 01:54:53 +0000218 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000219 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000220 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000221 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000222 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000223 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000224 continue;
225 }
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattnerf64b3522008-03-09 01:54:53 +0000227 // Get the identifier name without trigraphs or embedded newlines. Note
228 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
229 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000230 char DirectiveBuf[20];
231 llvm::StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000232 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramer144884642009-12-31 13:32:38 +0000233 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000234 } else {
235 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000236 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000237 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000238 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000239 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000240 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000241 continue;
242 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000243 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
244 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000245 }
Mike Stump11289f42009-09-09 15:08:12 +0000246
Benjamin Kramer144884642009-12-31 13:32:38 +0000247 if (Directive.startswith("if")) {
248 llvm::StringRef Sub = Directive.substr(2);
249 if (Sub.empty() || // "if"
250 Sub == "def" || // "ifdef"
251 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000252 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
253 // bother parsing the condition.
254 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000255 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000256 /*foundnonskip*/false,
257 /*fnddelse*/false);
258 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000259 } else if (Directive[0] == 'e') {
260 llvm::StringRef Sub = Directive.substr(1);
261 if (Sub == "ndif") { // "endif"
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000262 CheckEndOfDirective("endif");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000263 PPConditionalInfo CondInfo;
264 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000265 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000266 InCond = InCond; // Silence warning in no-asserts mode.
267 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000268
Chris Lattnerf64b3522008-03-09 01:54:53 +0000269 // If we popped the outermost skipping block, we're done skipping!
270 if (!CondInfo.WasSkipping)
271 break;
Benjamin Kramer144884642009-12-31 13:32:38 +0000272 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000273 // #else directive in a skipping conditional. If not in some other
274 // skipping conditional, and if #else hasn't already been seen, enter it
275 // as a non-skipping conditional.
Chris Lattnerbc63de12009-04-18 01:34:22 +0000276 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000277 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000278
Chris Lattnerf64b3522008-03-09 01:54:53 +0000279 // If this is a #else with a #else before it, report the error.
280 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000281
Chris Lattnerf64b3522008-03-09 01:54:53 +0000282 // Note that we've seen a #else in this conditional.
283 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000284
Chris Lattnerf64b3522008-03-09 01:54:53 +0000285 // If the conditional is at the top level, and the #if block wasn't
286 // entered, enter the #else block now.
287 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
288 CondInfo.FoundNonSkip = true;
289 break;
290 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000291 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000292 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000293
294 bool ShouldEnter;
295 // If this is in a skipping block or if we're already handled this #if
296 // block, don't bother parsing the condition.
297 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
298 DiscardUntilEndOfDirective();
299 ShouldEnter = false;
300 } else {
301 // Restore the value of LexingRawMode so that identifiers are
302 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000303 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
304 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000305 IdentifierInfo *IfNDefMacro = 0;
306 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000307 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000308 }
Mike Stump11289f42009-09-09 15:08:12 +0000309
Chris Lattnerf64b3522008-03-09 01:54:53 +0000310 // If this is a #elif with a #else before it, report the error.
311 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000312
Chris Lattnerf64b3522008-03-09 01:54:53 +0000313 // If this condition is true, enter it!
314 if (ShouldEnter) {
315 CondInfo.FoundNonSkip = true;
316 break;
317 }
318 }
319 }
Mike Stump11289f42009-09-09 15:08:12 +0000320
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000321 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000322 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000323 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000324 }
325
326 // Finally, if we are out of the conditional (saw an #endif or ran off the end
327 // of the file, just stop skipping and return to lexing whatever came after
328 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000329 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000330}
331
Ted Kremenek56572ab2008-12-12 18:34:08 +0000332void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000333
334 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000335 assert(CurPTHLexer);
336 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000337
Ted Kremenek56572ab2008-12-12 18:34:08 +0000338 // Skip to the next '#else', '#elif', or #endif.
339 if (CurPTHLexer->SkipBlock()) {
340 // We have reached an #endif. Both the '#' and 'endif' tokens
341 // have been consumed by the PTHLexer. Just pop off the condition level.
342 PPConditionalInfo CondInfo;
343 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
344 InCond = InCond; // Silence warning in no-asserts mode.
345 assert(!InCond && "Can't be skipping if not in a conditional!");
346 break;
347 }
Mike Stump11289f42009-09-09 15:08:12 +0000348
Ted Kremenek56572ab2008-12-12 18:34:08 +0000349 // We have reached a '#else' or '#elif'. Lex the next token to get
350 // the directive flavor.
351 Token Tok;
352 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000353
Ted Kremenek56572ab2008-12-12 18:34:08 +0000354 // We can actually look up the IdentifierInfo here since we aren't in
355 // raw mode.
356 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
357
358 if (K == tok::pp_else) {
359 // #else: Enter the else condition. We aren't in a nested condition
360 // since we skip those. We're always in the one matching the last
361 // blocked we skipped.
362 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
363 // Note that we've seen a #else in this conditional.
364 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000365
Ted Kremenek56572ab2008-12-12 18:34:08 +0000366 // If the #if block wasn't entered then enter the #else block now.
367 if (!CondInfo.FoundNonSkip) {
368 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000369
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000370 // Scan until the eom token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000371 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000372 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000373 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000374
Ted Kremenek56572ab2008-12-12 18:34:08 +0000375 break;
376 }
Mike Stump11289f42009-09-09 15:08:12 +0000377
Ted Kremenek56572ab2008-12-12 18:34:08 +0000378 // Otherwise skip this block.
379 continue;
380 }
Mike Stump11289f42009-09-09 15:08:12 +0000381
Ted Kremenek56572ab2008-12-12 18:34:08 +0000382 assert(K == tok::pp_elif);
383 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
384
385 // If this is a #elif with a #else before it, report the error.
386 if (CondInfo.FoundElse)
387 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000388
Ted Kremenek56572ab2008-12-12 18:34:08 +0000389 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000390 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000391 if (CondInfo.FoundNonSkip)
392 continue;
393
394 // Evaluate the condition of the #elif.
395 IdentifierInfo *IfNDefMacro = 0;
396 CurPTHLexer->ParsingPreprocessorDirective = true;
397 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
398 CurPTHLexer->ParsingPreprocessorDirective = false;
399
400 // If this condition is true, enter it!
401 if (ShouldEnter) {
402 CondInfo.FoundNonSkip = true;
403 break;
404 }
405
406 // Otherwise, skip this block and go to the next one.
407 continue;
408 }
409}
410
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000411/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
412/// return null on failure. isAngled indicates whether the file reference is
413/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000414const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000415 bool isAngled,
416 const DirectoryLookup *FromDir,
417 const DirectoryLookup *&CurDir) {
418 // If the header lookup mechanism may be relative to the current file, pass in
419 // info about where the current file is.
Douglas Gregord26129a2010-08-06 12:06:13 +0000420 llvm::sys::Path RelSearchPath;
421
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000422 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000423 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregord26129a2010-08-06 12:06:13 +0000424 const FileEntry *CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000425
Chris Lattner022923a2009-02-04 19:45:07 +0000426 // If there is no file entry associated with this file, it must be the
427 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregord26129a2010-08-06 12:06:13 +0000428 // it won't be scanned for preprocessor directives.
429 //
430 // If we have the predefines buffer, resolve #include references (which
431 // come from the -include command line argument) as if they came from the
432 // main file. When the main file is actually stdin, resolve references
433 // as if they came from the current working directory.
434 if (CurFileEnt) {
435 if (!RelSearchPath.set(CurFileEnt->getDir()->getName())) {
436 assert("Main file somehow invalid path?");
437 }
438 } else {
Chris Lattner022923a2009-02-04 19:45:07 +0000439 FID = SourceMgr.getMainFileID();
440 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Douglas Gregord26129a2010-08-06 12:06:13 +0000441
442 if (CurFileEnt) {
443 // 'main file' case
444 RelSearchPath.set(CurFileEnt->getDir()->getName());
445 } else {
446 // stdin case
447 RelSearchPath = llvm::sys::Path::GetCurrentDirectory();
448 }
Chris Lattner022923a2009-02-04 19:45:07 +0000449 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000450 }
Mike Stump11289f42009-09-09 15:08:12 +0000451
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000452 // Do a standard file entry lookup.
453 CurDir = CurDirLookup;
454 const FileEntry *FE =
Douglas Gregord26129a2010-08-06 12:06:13 +0000455 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, RelSearchPath);
Chris Lattnerfde85352010-01-22 00:14:44 +0000456 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000457
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000458 // Otherwise, see if this is a subframework header. If so, this is relative
459 // to one of the headers on the #include stack. Walk the list of the current
460 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000461 if (IsFileLexer()) {
Douglas Gregord26129a2010-08-06 12:06:13 +0000462 const FileEntry *CurFileEnt = 0;
Ted Kremenek45245212008-11-19 21:57:25 +0000463 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000464 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000465 return FE;
466 }
Mike Stump11289f42009-09-09 15:08:12 +0000467
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000468 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
469 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000470 if (IsFileLexer(ISEntry)) {
Douglas Gregord26129a2010-08-06 12:06:13 +0000471 const FileEntry *CurFileEnt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000472 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000473 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000474 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000475 return FE;
476 }
477 }
Mike Stump11289f42009-09-09 15:08:12 +0000478
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000479 // Otherwise, we really couldn't find the file.
480 return 0;
481}
482
Chris Lattnerf64b3522008-03-09 01:54:53 +0000483
484//===----------------------------------------------------------------------===//
485// Preprocessor Directive Handling.
486//===----------------------------------------------------------------------===//
487
488/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000489/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000490/// lexer/preprocessor state, and advances the lexer(s) so that the next token
491/// read is the correct one.
492void Preprocessor::HandleDirective(Token &Result) {
493 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000494
Chris Lattnerf64b3522008-03-09 01:54:53 +0000495 // We just parsed a # character at the start of a line, so we're in directive
496 // mode. Tell the lexer this so any newlines we see will be converted into an
497 // EOM token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000498 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000499
Chris Lattnerf64b3522008-03-09 01:54:53 +0000500 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000501
Chris Lattnerf64b3522008-03-09 01:54:53 +0000502 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000503 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000504 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000505 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000506
Chris Lattner2d17ab72009-03-18 21:00:25 +0000507 // Save the '#' token in case we need to return it later.
508 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000509
Chris Lattnerf64b3522008-03-09 01:54:53 +0000510 // Read the next token, the directive flavor. This isn't expanded due to
511 // C99 6.10.3p8.
512 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000513
Chris Lattnerf64b3522008-03-09 01:54:53 +0000514 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
515 // #define A(x) #x
516 // A(abc
517 // #warning blah
518 // def)
519 // If so, the user is relying on non-portable behavior, emit a diagnostic.
520 if (InMacroArgs)
521 Diag(Result, diag::ext_embedded_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000522
Chris Lattnerf64b3522008-03-09 01:54:53 +0000523TryAgain:
524 switch (Result.getKind()) {
525 case tok::eom:
526 return; // null directive.
527 case tok::comment:
528 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
529 LexUnexpandedToken(Result);
530 goto TryAgain;
531
Chris Lattner76e68962009-01-26 06:19:46 +0000532 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000533 if (getLangOptions().AsmPreprocessor)
534 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000535 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000536 default:
537 IdentifierInfo *II = Result.getIdentifierInfo();
538 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000539
Chris Lattnerf64b3522008-03-09 01:54:53 +0000540 // Ask what the preprocessor keyword ID is.
541 switch (II->getPPKeywordID()) {
542 default: break;
543 // C99 6.10.1 - Conditional Inclusion.
544 case tok::pp_if:
545 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
546 case tok::pp_ifdef:
547 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
548 case tok::pp_ifndef:
549 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
550 case tok::pp_elif:
551 return HandleElifDirective(Result);
552 case tok::pp_else:
553 return HandleElseDirective(Result);
554 case tok::pp_endif:
555 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000556
Chris Lattnerf64b3522008-03-09 01:54:53 +0000557 // C99 6.10.2 - Source File Inclusion.
558 case tok::pp_include:
Chris Lattner14a7f392009-04-08 18:24:34 +0000559 return HandleIncludeDirective(Result); // Handle #include.
560 case tok::pp___include_macros:
Chris Lattner58a1eb02009-04-08 18:46:40 +0000561 return HandleIncludeMacrosDirective(Result); // Handle -imacros.
Mike Stump11289f42009-09-09 15:08:12 +0000562
Chris Lattnerf64b3522008-03-09 01:54:53 +0000563 // C99 6.10.3 - Macro Replacement.
564 case tok::pp_define:
565 return HandleDefineDirective(Result);
566 case tok::pp_undef:
567 return HandleUndefDirective(Result);
568
569 // C99 6.10.4 - Line Control.
570 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000571 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000572
Chris Lattnerf64b3522008-03-09 01:54:53 +0000573 // C99 6.10.5 - Error Directive.
574 case tok::pp_error:
575 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000576
Chris Lattnerf64b3522008-03-09 01:54:53 +0000577 // C99 6.10.6 - Pragma Directive.
578 case tok::pp_pragma:
579 return HandlePragmaDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000580
Chris Lattnerf64b3522008-03-09 01:54:53 +0000581 // GNU Extensions.
582 case tok::pp_import:
583 return HandleImportDirective(Result);
584 case tok::pp_include_next:
585 return HandleIncludeNextDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000586
Chris Lattnerf64b3522008-03-09 01:54:53 +0000587 case tok::pp_warning:
588 Diag(Result, diag::ext_pp_warning_directive);
589 return HandleUserDiagnosticDirective(Result, true);
590 case tok::pp_ident:
591 return HandleIdentSCCSDirective(Result);
592 case tok::pp_sccs:
593 return HandleIdentSCCSDirective(Result);
594 case tok::pp_assert:
595 //isExtension = true; // FIXME: implement #assert
596 break;
597 case tok::pp_unassert:
598 //isExtension = true; // FIXME: implement #unassert
599 break;
600 }
601 break;
602 }
Mike Stump11289f42009-09-09 15:08:12 +0000603
Chris Lattner2d17ab72009-03-18 21:00:25 +0000604 // If this is a .S file, treat unknown # directives as non-preprocessor
605 // directives. This is important because # may be a comment or introduce
606 // various pseudo-ops. Just return the # token and push back the following
607 // token to be lexed next time.
608 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000609 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000610 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000611 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000612 Toks[1] = Result;
613 // Enter this token stream so that we re-lex the tokens. Make sure to
614 // enable macro expansion, in case the token after the # is an identifier
615 // that is expanded.
616 EnterTokenStream(Toks, 2, false, true);
617 return;
618 }
Mike Stump11289f42009-09-09 15:08:12 +0000619
Chris Lattnerf64b3522008-03-09 01:54:53 +0000620 // If we reached here, the preprocessing token is not valid!
621 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000622
Chris Lattnerf64b3522008-03-09 01:54:53 +0000623 // Read the rest of the PP line.
624 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000625
Chris Lattnerf64b3522008-03-09 01:54:53 +0000626 // Okay, we're done parsing the directive.
627}
628
Chris Lattner76e68962009-01-26 06:19:46 +0000629/// GetLineValue - Convert a numeric token into an unsigned value, emitting
630/// Diagnostic DiagID if it is invalid, and returning the value in Val.
631static bool GetLineValue(Token &DigitTok, unsigned &Val,
632 unsigned DiagID, Preprocessor &PP) {
633 if (DigitTok.isNot(tok::numeric_constant)) {
634 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000635
Chris Lattner76e68962009-01-26 06:19:46 +0000636 if (DigitTok.isNot(tok::eom))
637 PP.DiscardUntilEndOfDirective();
638 return true;
639 }
Mike Stump11289f42009-09-09 15:08:12 +0000640
Chris Lattner76e68962009-01-26 06:19:46 +0000641 llvm::SmallString<64> IntegerBuffer;
642 IntegerBuffer.resize(DigitTok.getLength());
643 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000644 bool Invalid = false;
645 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
646 if (Invalid)
647 return true;
648
Chris Lattnerd66f1722009-04-18 18:35:15 +0000649 // Verify that we have a simple digit-sequence, and compute the value. This
650 // is always a simple digit string computed in decimal, so we do this manually
651 // here.
652 Val = 0;
653 for (unsigned i = 0; i != ActualLength; ++i) {
654 if (!isdigit(DigitTokBegin[i])) {
655 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
656 diag::err_pp_line_digit_sequence);
657 PP.DiscardUntilEndOfDirective();
658 return true;
659 }
Mike Stump11289f42009-09-09 15:08:12 +0000660
Chris Lattnerd66f1722009-04-18 18:35:15 +0000661 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
662 if (NextVal < Val) { // overflow.
663 PP.Diag(DigitTok, DiagID);
664 PP.DiscardUntilEndOfDirective();
665 return true;
666 }
667 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000668 }
Mike Stump11289f42009-09-09 15:08:12 +0000669
670 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000671 if (Val == 0) {
672 PP.Diag(DigitTok, DiagID);
673 PP.DiscardUntilEndOfDirective();
674 return true;
675 }
Mike Stump11289f42009-09-09 15:08:12 +0000676
Chris Lattnerd66f1722009-04-18 18:35:15 +0000677 if (DigitTokBegin[0] == '0')
678 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000679
Chris Lattner76e68962009-01-26 06:19:46 +0000680 return false;
681}
682
Mike Stump11289f42009-09-09 15:08:12 +0000683/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner100c65e2009-01-26 05:29:08 +0000684/// acceptable forms are:
685/// # line digit-sequence
686/// # line digit-sequence "s-char-sequence"
687void Preprocessor::HandleLineDirective(Token &Tok) {
688 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
689 // expanded.
690 Token DigitTok;
691 Lex(DigitTok);
692
Chris Lattner100c65e2009-01-26 05:29:08 +0000693 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000694 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000695 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000696 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000697
Chris Lattner76e68962009-01-26 06:19:46 +0000698 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
699 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner100c65e2009-01-26 05:29:08 +0000700 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
701 if (LineNo >= LineLimit)
702 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump11289f42009-09-09 15:08:12 +0000703
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000704 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000705 Token StrTok;
706 Lex(StrTok);
707
708 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
709 // string followed by eom.
Mike Stump11289f42009-09-09 15:08:12 +0000710 if (StrTok.is(tok::eom))
Chris Lattner100c65e2009-01-26 05:29:08 +0000711 ; // ok
712 else if (StrTok.isNot(tok::string_literal)) {
713 Diag(StrTok, diag::err_pp_line_invalid_filename);
714 DiscardUntilEndOfDirective();
715 return;
716 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000717 // Parse and validate the string, converting it into a unique ID.
718 StringLiteralParser Literal(&StrTok, 1, *this);
719 assert(!Literal.AnyWide && "Didn't allow wide strings in");
720 if (Literal.hadError)
721 return DiscardUntilEndOfDirective();
722 if (Literal.Pascal) {
723 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
724 return DiscardUntilEndOfDirective();
725 }
726 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
727 Literal.GetStringLength());
Mike Stump11289f42009-09-09 15:08:12 +0000728
Chris Lattner0003c272009-04-17 23:30:53 +0000729 // Verify that there is nothing after the string, other than EOM. Because
730 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
731 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000732 }
Mike Stump11289f42009-09-09 15:08:12 +0000733
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000734 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattner839150e2009-03-27 17:13:49 +0000736 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000737 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
738 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000739 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000740}
741
Chris Lattner76e68962009-01-26 06:19:46 +0000742/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
743/// marker directive.
744static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
745 bool &IsSystemHeader, bool &IsExternCHeader,
746 Preprocessor &PP) {
747 unsigned FlagVal;
748 Token FlagTok;
749 PP.Lex(FlagTok);
750 if (FlagTok.is(tok::eom)) return false;
751 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
752 return true;
753
754 if (FlagVal == 1) {
755 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000756
Chris Lattner76e68962009-01-26 06:19:46 +0000757 PP.Lex(FlagTok);
758 if (FlagTok.is(tok::eom)) return false;
759 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
760 return true;
761 } else if (FlagVal == 2) {
762 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000763
Chris Lattner1c967782009-02-04 06:25:26 +0000764 SourceManager &SM = PP.getSourceManager();
765 // If we are leaving the current presumed file, check to make sure the
766 // presumed include stack isn't empty!
767 FileID CurFileID =
768 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
769 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000770
Chris Lattner1c967782009-02-04 06:25:26 +0000771 // If there is no include loc (main file) or if the include loc is in a
772 // different physical file, then we aren't in a "1" line marker flag region.
773 SourceLocation IncLoc = PLoc.getIncludeLoc();
774 if (IncLoc.isInvalid() ||
775 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
776 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
777 PP.DiscardUntilEndOfDirective();
778 return true;
779 }
Mike Stump11289f42009-09-09 15:08:12 +0000780
Chris Lattner76e68962009-01-26 06:19:46 +0000781 PP.Lex(FlagTok);
782 if (FlagTok.is(tok::eom)) return false;
783 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
784 return true;
785 }
786
787 // We must have 3 if there are still flags.
788 if (FlagVal != 3) {
789 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000790 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000791 return true;
792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
Chris Lattner76e68962009-01-26 06:19:46 +0000794 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000795
Chris Lattner76e68962009-01-26 06:19:46 +0000796 PP.Lex(FlagTok);
797 if (FlagTok.is(tok::eom)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000798 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000799 return true;
800
801 // We must have 4 if there is yet another flag.
802 if (FlagVal != 4) {
803 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000804 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000805 return true;
806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Chris Lattner76e68962009-01-26 06:19:46 +0000808 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000809
Chris Lattner76e68962009-01-26 06:19:46 +0000810 PP.Lex(FlagTok);
811 if (FlagTok.is(tok::eom)) return false;
812
813 // There are no more valid flags here.
814 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000815 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000816 return true;
817}
818
819/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
820/// one of the following forms:
821///
822/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000823/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000824/// # 42 "file" ('1' | '2')? '3' '4'?
825///
826void Preprocessor::HandleDigitDirective(Token &DigitTok) {
827 // Validate the number and convert it to an unsigned. GNU does not have a
828 // line # limit other than it fit in 32-bits.
829 unsigned LineNo;
830 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
831 *this))
832 return;
Mike Stump11289f42009-09-09 15:08:12 +0000833
Chris Lattner76e68962009-01-26 06:19:46 +0000834 Token StrTok;
835 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattner76e68962009-01-26 06:19:46 +0000837 bool IsFileEntry = false, IsFileExit = false;
838 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000839 int FilenameID = -1;
840
Chris Lattner76e68962009-01-26 06:19:46 +0000841 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
842 // string followed by eom.
Mike Stump11289f42009-09-09 15:08:12 +0000843 if (StrTok.is(tok::eom))
Chris Lattner76e68962009-01-26 06:19:46 +0000844 ; // ok
845 else if (StrTok.isNot(tok::string_literal)) {
846 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000847 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000848 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000849 // Parse and validate the string, converting it into a unique ID.
850 StringLiteralParser Literal(&StrTok, 1, *this);
851 assert(!Literal.AnyWide && "Didn't allow wide strings in");
852 if (Literal.hadError)
853 return DiscardUntilEndOfDirective();
854 if (Literal.Pascal) {
855 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
856 return DiscardUntilEndOfDirective();
857 }
858 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
859 Literal.GetStringLength());
Mike Stump11289f42009-09-09 15:08:12 +0000860
Chris Lattner76e68962009-01-26 06:19:46 +0000861 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +0000862 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000863 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +0000864 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000865 }
Mike Stump11289f42009-09-09 15:08:12 +0000866
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000867 // Create a line note with this information.
868 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +0000869 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000870 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +0000871
Chris Lattner839150e2009-03-27 17:13:49 +0000872 // If the preprocessor has callbacks installed, notify them of the #line
873 // change. This is used so that the line marker comes out in -E mode for
874 // example.
875 if (Callbacks) {
876 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
877 if (IsFileEntry)
878 Reason = PPCallbacks::EnterFile;
879 else if (IsFileExit)
880 Reason = PPCallbacks::ExitFile;
881 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
882 if (IsExternCHeader)
883 FileKind = SrcMgr::C_ExternCSystem;
884 else if (IsSystemHeader)
885 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +0000886
Chris Lattnerc745cec2010-04-14 04:28:50 +0000887 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +0000888 }
Chris Lattner76e68962009-01-26 06:19:46 +0000889}
890
891
Chris Lattner38d7fd22009-01-26 05:30:54 +0000892/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
893///
Mike Stump11289f42009-09-09 15:08:12 +0000894void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000895 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +0000896 // PTH doesn't emit #warning or #error directives.
897 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +0000898 return CurPTHLexer->DiscardToEndOfLine();
899
Chris Lattnerf64b3522008-03-09 01:54:53 +0000900 // Read the rest of the line raw. We do this because we don't want macros
901 // to be expanded and we don't require that the tokens be valid preprocessing
902 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
903 // collapse multiple consequtive white space between tokens, but this isn't
904 // specified by the standard.
Chris Lattner100c65e2009-01-26 05:29:08 +0000905 std::string Message = CurLexer->ReadToEndOfLine();
906 if (isWarning)
907 Diag(Tok, diag::pp_hash_warning) << Message;
908 else
909 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000910}
911
912/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
913///
914void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
915 // Yes, this directive is an extension.
916 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000917
Chris Lattnerf64b3522008-03-09 01:54:53 +0000918 // Read the string argument.
919 Token StrTok;
920 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000921
Chris Lattnerf64b3522008-03-09 01:54:53 +0000922 // If the token kind isn't a string, it's a malformed directive.
923 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +0000924 StrTok.isNot(tok::wide_string_literal)) {
925 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner38d7fd22009-01-26 05:30:54 +0000926 if (StrTok.isNot(tok::eom))
927 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000928 return;
929 }
Mike Stump11289f42009-09-09 15:08:12 +0000930
Chris Lattnerf64b3522008-03-09 01:54:53 +0000931 // Verify that there is nothing after the string, other than EOM.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000932 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000933
Douglas Gregordc970f02010-03-16 22:30:13 +0000934 if (Callbacks) {
935 bool Invalid = false;
936 std::string Str = getSpelling(StrTok, &Invalid);
937 if (!Invalid)
938 Callbacks->Ident(Tok.getLocation(), Str);
939 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000940}
941
942//===----------------------------------------------------------------------===//
943// Preprocessor Include Directive Handling.
944//===----------------------------------------------------------------------===//
945
946/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
947/// checked and spelled filename, e.g. as an operand of #include. This returns
948/// true if the input filename was in <>'s or false if it were in ""'s. The
949/// caller is expected to provide a buffer that is large enough to hold the
950/// spelling of the filename, but is also expected to handle the case when
951/// this method decides to use a different buffer.
952bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000953 llvm::StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000954 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000955 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +0000956
Chris Lattnerf64b3522008-03-09 01:54:53 +0000957 // Make sure the filename is <x> or "x".
958 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000959 if (Buffer[0] == '<') {
960 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000961 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000962 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000963 return true;
964 }
965 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000966 } else if (Buffer[0] == '"') {
967 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000968 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000969 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000970 return true;
971 }
972 isAngled = false;
973 } else {
974 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000975 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000976 return true;
977 }
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattnerf64b3522008-03-09 01:54:53 +0000979 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000980 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000981 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000982 Buffer = llvm::StringRef();
983 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattnerf64b3522008-03-09 01:54:53 +0000986 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000987 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000988 return isAngled;
989}
990
991/// ConcatenateIncludeName - Handle cases where the #include name is expanded
992/// from a macro as multiple tokens, which need to be glued together. This
993/// occurs for code like:
994/// #define FOO <a/b.h>
995/// #include FOO
996/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
997///
998/// This code concatenates and consumes tokens up to the '>' token. It returns
999/// false if the > was found, otherwise it returns true if it finds and consumes
1000/// the EOM marker.
John Thompsonb5353522009-10-30 13:49:06 +00001001bool Preprocessor::ConcatenateIncludeName(
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001002 llvm::SmallString<128> &FilenameBuffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001003 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001004
John Thompsonb5353522009-10-30 13:49:06 +00001005 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001006 while (CurTok.isNot(tok::eom)) {
1007 // Append the spelling of this token to the buffer. If there was a space
1008 // before it, add it now.
1009 if (CurTok.hasLeadingSpace())
1010 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattnerf64b3522008-03-09 01:54:53 +00001012 // Get the spelling of the token, directly into FilenameBuffer if possible.
1013 unsigned PreAppendSize = FilenameBuffer.size();
1014 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001015
Chris Lattnerf64b3522008-03-09 01:54:53 +00001016 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001017 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001018
Chris Lattnerf64b3522008-03-09 01:54:53 +00001019 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1020 if (BufPtr != &FilenameBuffer[PreAppendSize])
1021 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattnerf64b3522008-03-09 01:54:53 +00001023 // Resize FilenameBuffer to the correct size.
1024 if (CurTok.getLength() != ActualLen)
1025 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001026
Chris Lattnerf64b3522008-03-09 01:54:53 +00001027 // If we found the '>' marker, return success.
1028 if (CurTok.is(tok::greater))
1029 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001030
John Thompsonb5353522009-10-30 13:49:06 +00001031 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001032 }
1033
1034 // If we hit the eom marker, emit an error and return true so that the caller
1035 // knows the EOM has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001036 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001037 return true;
1038}
1039
1040/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1041/// file to be included from the lexer, then include it! This is a common
1042/// routine with functionality shared between #include, #include_next and
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001043/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001044/// specifies the file to start searching from.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001045void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1046 const DirectoryLookup *LookupFrom,
1047 bool isImport) {
1048
1049 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001050 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001051
Chris Lattnerf64b3522008-03-09 01:54:53 +00001052 // Reserve a buffer to get the spelling.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001053 llvm::SmallString<128> FilenameBuffer;
1054 llvm::StringRef Filename;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001055
1056 switch (FilenameTok.getKind()) {
1057 case tok::eom:
1058 // If the token kind is EOM, the error has already been diagnosed.
1059 return;
Mike Stump11289f42009-09-09 15:08:12 +00001060
Chris Lattnerf64b3522008-03-09 01:54:53 +00001061 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001062 case tok::string_literal:
1063 Filename = getSpelling(FilenameTok, FilenameBuffer);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001064 break;
Mike Stump11289f42009-09-09 15:08:12 +00001065
Chris Lattnerf64b3522008-03-09 01:54:53 +00001066 case tok::less:
1067 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1068 // case, glue the tokens together into FilenameBuffer and interpret those.
1069 FilenameBuffer.push_back('<');
John Thompsonb5353522009-10-30 13:49:06 +00001070 if (ConcatenateIncludeName(FilenameBuffer))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001071 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001072 Filename = FilenameBuffer.str();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001073 break;
1074 default:
1075 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1076 DiscardUntilEndOfDirective();
1077 return;
1078 }
Mike Stump11289f42009-09-09 15:08:12 +00001079
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001080 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001081 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001082 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1083 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001084 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001085 DiscardUntilEndOfDirective();
1086 return;
1087 }
Mike Stump11289f42009-09-09 15:08:12 +00001088
Chris Lattnerb40289b2009-04-17 23:56:52 +00001089 // Verify that there is nothing after the filename, other than EOM. Note that
1090 // we allow macros that expand to nothing after the filename, because this
1091 // falls into the category of "#include pp-tokens new-line" specified in
1092 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001093 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001094
1095 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001096 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1097 Diag(FilenameTok, diag::err_pp_include_too_deep);
1098 return;
1099 }
Mike Stump11289f42009-09-09 15:08:12 +00001100
Chris Lattnerf64b3522008-03-09 01:54:53 +00001101 // Search include directories.
1102 const DirectoryLookup *CurDir;
Chris Lattnerfde85352010-01-22 00:14:44 +00001103 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner907dfe92008-11-18 07:59:24 +00001104 if (File == 0) {
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001105 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner907dfe92008-11-18 07:59:24 +00001106 return;
1107 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001108
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001109 // The #included file will be considered to be a system header if either it is
1110 // in a system include directory, or if the #includer is a system include
1111 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001112 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001113 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001114 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001115
Chris Lattner72286d62010-04-19 20:44:31 +00001116 // Ask HeaderInfo if we should enter this #include file. If not, #including
1117 // this file will have no effect.
1118 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001119 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001120 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001121 return;
1122 }
1123
Chris Lattnerf64b3522008-03-09 01:54:53 +00001124 // Look up the file, create a File ID for it.
Chris Lattnerd32480d2009-01-17 06:22:33 +00001125 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1126 FileCharacter);
1127 if (FID.isInvalid()) {
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001128 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +00001129 return;
1130 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001131
1132 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001133 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001134}
1135
1136/// HandleIncludeNextDirective - Implements #include_next.
1137///
1138void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1139 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001140
Chris Lattnerf64b3522008-03-09 01:54:53 +00001141 // #include_next is like #include, except that we start searching after
1142 // the current found directory. If we can't do this, issue a
1143 // diagnostic.
1144 const DirectoryLookup *Lookup = CurDirLookup;
1145 if (isInPrimaryFile()) {
1146 Lookup = 0;
1147 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1148 } else if (Lookup == 0) {
1149 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1150 } else {
1151 // Start looking up in the next directory.
1152 ++Lookup;
1153 }
Mike Stump11289f42009-09-09 15:08:12 +00001154
Chris Lattnerf64b3522008-03-09 01:54:53 +00001155 return HandleIncludeDirective(IncludeNextTok, Lookup);
1156}
1157
1158/// HandleImportDirective - Implements #import.
1159///
1160void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnerd4a96732009-03-06 04:28:03 +00001161 if (!Features.ObjC1) // #import is standard for ObjC.
1162 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001163
Chris Lattnerf64b3522008-03-09 01:54:53 +00001164 return HandleIncludeDirective(ImportTok, 0, true);
1165}
1166
Chris Lattner58a1eb02009-04-08 18:46:40 +00001167/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1168/// pseudo directive in the predefines buffer. This handles it by sucking all
1169/// tokens through the preprocessor and discarding them (only keeping the side
1170/// effects on the preprocessor).
1171void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
1172 // This directive should only occur in the predefines buffer. If not, emit an
1173 // error and reject it.
1174 SourceLocation Loc = IncludeMacrosTok.getLocation();
1175 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1176 Diag(IncludeMacrosTok.getLocation(),
1177 diag::pp_include_macros_out_of_predefines);
1178 DiscardUntilEndOfDirective();
1179 return;
1180 }
Mike Stump11289f42009-09-09 15:08:12 +00001181
Chris Lattnere01d82b2009-04-08 20:53:24 +00001182 // Treat this as a normal #include for checking purposes. If this is
1183 // successful, it will push a new lexer onto the include stack.
1184 HandleIncludeDirective(IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001185
Chris Lattnere01d82b2009-04-08 20:53:24 +00001186 Token TmpTok;
1187 do {
1188 Lex(TmpTok);
1189 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1190 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001191}
1192
Chris Lattnerf64b3522008-03-09 01:54:53 +00001193//===----------------------------------------------------------------------===//
1194// Preprocessor Macro Directive Handling.
1195//===----------------------------------------------------------------------===//
1196
1197/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1198/// definition has just been read. Lex the rest of the arguments and the
1199/// closing ), updating MI with what we learn. Return true if an error occurs
1200/// parsing the arg list.
1201bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1202 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001203
Chris Lattnerf64b3522008-03-09 01:54:53 +00001204 Token Tok;
1205 while (1) {
1206 LexUnexpandedToken(Tok);
1207 switch (Tok.getKind()) {
1208 case tok::r_paren:
1209 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001210 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001211 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001212 // Otherwise we have #define FOO(A,)
1213 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1214 return true;
1215 case tok::ellipsis: // #define X(... -> C99 varargs
1216 // Warn if use of C99 feature in non-C99 mode.
1217 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1218
1219 // Lex the token after the identifier.
1220 LexUnexpandedToken(Tok);
1221 if (Tok.isNot(tok::r_paren)) {
1222 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1223 return true;
1224 }
1225 // Add the __VA_ARGS__ identifier as an argument.
1226 Arguments.push_back(Ident__VA_ARGS__);
1227 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001228 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001229 return false;
1230 case tok::eom: // #define X(
1231 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1232 return true;
1233 default:
1234 // Handle keywords and identifiers here to accept things like
1235 // #define Foo(for) for.
1236 IdentifierInfo *II = Tok.getIdentifierInfo();
1237 if (II == 0) {
1238 // #define X(1
1239 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1240 return true;
1241 }
1242
1243 // If this is already used as an argument, it is used multiple times (e.g.
1244 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001245 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001246 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001247 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001248 return true;
1249 }
Mike Stump11289f42009-09-09 15:08:12 +00001250
Chris Lattnerf64b3522008-03-09 01:54:53 +00001251 // Add the argument to the macro info.
1252 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001253
Chris Lattnerf64b3522008-03-09 01:54:53 +00001254 // Lex the token after the identifier.
1255 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001256
Chris Lattnerf64b3522008-03-09 01:54:53 +00001257 switch (Tok.getKind()) {
1258 default: // #define X(A B
1259 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1260 return true;
1261 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001262 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001263 return false;
1264 case tok::comma: // #define X(A,
1265 break;
1266 case tok::ellipsis: // #define X(A... -> GCC extension
1267 // Diagnose extension.
1268 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001269
Chris Lattnerf64b3522008-03-09 01:54:53 +00001270 // Lex the token after the identifier.
1271 LexUnexpandedToken(Tok);
1272 if (Tok.isNot(tok::r_paren)) {
1273 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1274 return true;
1275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Chris Lattnerf64b3522008-03-09 01:54:53 +00001277 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001278 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001279 return false;
1280 }
1281 }
1282 }
1283}
1284
1285/// HandleDefineDirective - Implements #define. This consumes the entire macro
1286/// line then lets the caller lex the next real token.
1287void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1288 ++NumDefined;
1289
1290 Token MacroNameTok;
1291 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001292
Chris Lattnerf64b3522008-03-09 01:54:53 +00001293 // Error reading macro name? If so, diagnostic already issued.
1294 if (MacroNameTok.is(tok::eom))
1295 return;
1296
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001297 Token LastTok = MacroNameTok;
1298
Chris Lattnerf64b3522008-03-09 01:54:53 +00001299 // If we are supposed to keep comments in #defines, reenable comment saving
1300 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001301 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001302
Chris Lattnerf64b3522008-03-09 01:54:53 +00001303 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001304 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001305
Chris Lattnerf64b3522008-03-09 01:54:53 +00001306 Token Tok;
1307 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001308
Chris Lattnerf64b3522008-03-09 01:54:53 +00001309 // If this is a function-like macro definition, parse the argument list,
1310 // marking each of the identifiers as being used as macro arguments. Also,
1311 // check other constraints on the first token of the macro body.
1312 if (Tok.is(tok::eom)) {
1313 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001314 } else if (Tok.hasLeadingSpace()) {
1315 // This is a normal token with leading space. Clear the leading space
1316 // marker on the first token to get proper expansion.
1317 Tok.clearFlag(Token::LeadingSpace);
1318 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001319 // This is a function-like macro definition. Read the argument list.
1320 MI->setIsFunctionLike();
1321 if (ReadMacroDefinitionArgList(MI)) {
1322 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001323 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001324 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001325 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001326 DiscardUntilEndOfDirective();
1327 return;
1328 }
1329
Chris Lattner249c38b2009-04-19 18:26:34 +00001330 // If this is a definition of a variadic C99 function-like macro, not using
1331 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattner249c38b2009-04-19 18:26:34 +00001333 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1334 // This gets unpoisoned where it is allowed.
1335 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1336 if (MI->isC99Varargs())
1337 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001338
Chris Lattnerf64b3522008-03-09 01:54:53 +00001339 // Read the first token after the arg list for down below.
1340 LexUnexpandedToken(Tok);
Chris Lattner2425bcb2009-04-18 02:23:25 +00001341 } else if (Features.C99) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001342 // C99 requires whitespace between the macro definition and the body. Emit
1343 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001344 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001345 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001346 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1347 // first character of a replacement list is not a character required by
1348 // subclause 5.2.1, then there shall be white-space separation between the
1349 // identifier and the replacement list.". 5.2.1 lists this set:
1350 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1351 // is irrelevant here.
1352 bool isInvalid = false;
1353 if (Tok.is(tok::at)) // @ is not in the list above.
1354 isInvalid = true;
1355 else if (Tok.is(tok::unknown)) {
1356 // If we have an unknown token, it is something strange like "`". Since
1357 // all of valid characters would have lexed into a single character
1358 // token of some sort, we know this is not a valid case.
1359 isInvalid = true;
1360 }
1361 if (isInvalid)
1362 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1363 else
1364 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001365 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001366
1367 if (!Tok.is(tok::eom))
1368 LastTok = Tok;
1369
Chris Lattnerf64b3522008-03-09 01:54:53 +00001370 // Read the rest of the macro body.
1371 if (MI->isObjectLike()) {
1372 // Object-like macros are very simple, just read their body.
1373 while (Tok.isNot(tok::eom)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001374 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001375 MI->AddTokenToBody(Tok);
1376 // Get the next token of the macro.
1377 LexUnexpandedToken(Tok);
1378 }
Mike Stump11289f42009-09-09 15:08:12 +00001379
Chris Lattnerf64b3522008-03-09 01:54:53 +00001380 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001381 // Otherwise, read the body of a function-like macro. While we are at it,
1382 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1383 // parameters in function-like macro expansions.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001384 while (Tok.isNot(tok::eom)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001385 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001386
Chris Lattnerf64b3522008-03-09 01:54:53 +00001387 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001388 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001389
Chris Lattnerf64b3522008-03-09 01:54:53 +00001390 // Get the next token of the macro.
1391 LexUnexpandedToken(Tok);
1392 continue;
1393 }
Mike Stump11289f42009-09-09 15:08:12 +00001394
Chris Lattnerf64b3522008-03-09 01:54:53 +00001395 // Get the next token of the macro.
1396 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001397
Chris Lattner83bd8282009-05-25 17:16:10 +00001398 // Check for a valid macro arg identifier.
1399 if (Tok.getIdentifierInfo() == 0 ||
1400 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1401
1402 // If this is assembler-with-cpp mode, we accept random gibberish after
1403 // the '#' because '#' is often a comment character. However, change
1404 // the kind of the token to tok::unknown so that the preprocessor isn't
1405 // confused.
1406 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1407 LastTok.setKind(tok::unknown);
1408 } else {
1409 Diag(Tok, diag::err_pp_stringize_not_parameter);
1410 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001411
Chris Lattner83bd8282009-05-25 17:16:10 +00001412 // Disable __VA_ARGS__ again.
1413 Ident__VA_ARGS__->setIsPoisoned(true);
1414 return;
1415 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001416 }
Mike Stump11289f42009-09-09 15:08:12 +00001417
Chris Lattner83bd8282009-05-25 17:16:10 +00001418 // Things look ok, add the '#' and param name tokens to the macro.
1419 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001420 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001421 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001422
Chris Lattnerf64b3522008-03-09 01:54:53 +00001423 // Get the next token of the macro.
1424 LexUnexpandedToken(Tok);
1425 }
1426 }
Mike Stump11289f42009-09-09 15:08:12 +00001427
1428
Chris Lattnerf64b3522008-03-09 01:54:53 +00001429 // Disable __VA_ARGS__ again.
1430 Ident__VA_ARGS__->setIsPoisoned(true);
1431
1432 // Check that there is no paste (##) operator at the begining or end of the
1433 // replacement list.
1434 unsigned NumTokens = MI->getNumTokens();
1435 if (NumTokens != 0) {
1436 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1437 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001438 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001439 return;
1440 }
1441 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1442 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001443 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001444 return;
1445 }
1446 }
Mike Stump11289f42009-09-09 15:08:12 +00001447
Chris Lattnerf64b3522008-03-09 01:54:53 +00001448 // If this is the primary source file, remember that this macro hasn't been
1449 // used yet.
1450 if (isInPrimaryFile())
1451 MI->setIsUsed(false);
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001452
1453 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001454
Chris Lattnerf64b3522008-03-09 01:54:53 +00001455 // Finally, if this identifier already had a macro defined for it, verify that
1456 // the macro bodies are identical and free the old definition.
1457 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001458 // It is very common for system headers to have tons of macro redefinitions
1459 // and for warnings to be disabled in system headers. If this is the case,
1460 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001461 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001462 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1463 if (!OtherMI->isUsed())
1464 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001465
Chris Lattner5244f342009-01-16 19:50:11 +00001466 // Macros must be identical. This means all tokes and whitespace
1467 // separation must be the same. C99 6.10.3.2.
1468 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1469 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1470 << MacroNameTok.getIdentifierInfo();
1471 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1472 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001473 }
Mike Stump11289f42009-09-09 15:08:12 +00001474
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001475 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001476 }
Mike Stump11289f42009-09-09 15:08:12 +00001477
Chris Lattnerf64b3522008-03-09 01:54:53 +00001478 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001479
Chris Lattner928e9092009-04-12 01:39:54 +00001480 // If the callbacks want to know, tell them about the macro definition.
1481 if (Callbacks)
1482 Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001483}
1484
1485/// HandleUndefDirective - Implements #undef.
1486///
1487void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1488 ++NumUndefined;
1489
1490 Token MacroNameTok;
1491 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001492
Chris Lattnerf64b3522008-03-09 01:54:53 +00001493 // Error reading macro name? If so, diagnostic already issued.
1494 if (MacroNameTok.is(tok::eom))
1495 return;
Mike Stump11289f42009-09-09 15:08:12 +00001496
Chris Lattnerf64b3522008-03-09 01:54:53 +00001497 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001498 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001499
Chris Lattnerf64b3522008-03-09 01:54:53 +00001500 // Okay, we finally have a valid identifier to undef.
1501 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001502
Chris Lattnerf64b3522008-03-09 01:54:53 +00001503 // If the macro is not defined, this is a noop undef, just return.
1504 if (MI == 0) return;
1505
1506 if (!MI->isUsed())
1507 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001508
1509 // If the callbacks want to know, tell them about the macro #undef.
1510 if (Callbacks)
Benjamin Kramerd05f31d2010-08-07 22:27:00 +00001511 Callbacks->MacroUndefined(MacroNameTok.getLocation(),
1512 MacroNameTok.getIdentifierInfo(), MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001513
Chris Lattnerf64b3522008-03-09 01:54:53 +00001514 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001515 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001516 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1517}
1518
1519
1520//===----------------------------------------------------------------------===//
1521// Preprocessor Conditional Directive Handling.
1522//===----------------------------------------------------------------------===//
1523
1524/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1525/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1526/// if any tokens have been returned or pp-directives activated before this
1527/// #ifndef has been lexed.
1528///
1529void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1530 bool ReadAnyTokensBeforeDirective) {
1531 ++NumIf;
1532 Token DirectiveTok = Result;
1533
1534 Token MacroNameTok;
1535 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001536
Chris Lattnerf64b3522008-03-09 01:54:53 +00001537 // Error reading macro name? If so, diagnostic already issued.
1538 if (MacroNameTok.is(tok::eom)) {
1539 // Skip code until we get to #endif. This helps with recovery by not
1540 // emitting an error when the #endif is reached.
1541 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1542 /*Foundnonskip*/false, /*FoundElse*/false);
1543 return;
1544 }
Mike Stump11289f42009-09-09 15:08:12 +00001545
Chris Lattnerf64b3522008-03-09 01:54:53 +00001546 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001547 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001548
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001549 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1550 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001551
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001552 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001553 // If the start of a top-level #ifdef and if the macro is not defined,
1554 // inform MIOpt that this might be the start of a proper include guard.
1555 // Otherwise it is some other form of unknown conditional which we can't
1556 // handle.
1557 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001558 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001559 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001560 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001561 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001562 }
1563
Chris Lattnerf64b3522008-03-09 01:54:53 +00001564 // If there is a macro, process it.
1565 if (MI) // Mark it used.
1566 MI->setIsUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00001567
Chris Lattnerf64b3522008-03-09 01:54:53 +00001568 // Should we include the stuff contained by this directive?
1569 if (!MI == isIfndef) {
1570 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001571 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1572 /*wasskip*/false, /*foundnonskip*/true,
1573 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001574 } else {
1575 // No, skip the contents of this block and return the first token after it.
1576 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001577 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001578 /*FoundElse*/false);
1579 }
1580}
1581
1582/// HandleIfDirective - Implements the #if directive.
1583///
1584void Preprocessor::HandleIfDirective(Token &IfToken,
1585 bool ReadAnyTokensBeforeDirective) {
1586 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001587
Chris Lattnerf64b3522008-03-09 01:54:53 +00001588 // Parse and evaluation the conditional expression.
1589 IdentifierInfo *IfNDefMacro = 0;
1590 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Mike Stump11289f42009-09-09 15:08:12 +00001591
Nuno Lopes363212b2008-06-01 18:31:24 +00001592
1593 // If this condition is equivalent to #ifndef X, and if this is the first
1594 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001595 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001596 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001597 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001598 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001599 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001600 }
1601
Chris Lattnerf64b3522008-03-09 01:54:53 +00001602 // Should we include the stuff contained by this directive?
1603 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001604 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001605 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001606 /*foundnonskip*/true, /*foundelse*/false);
1607 } else {
1608 // No, skip the contents of this block and return the first token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001609 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001610 /*FoundElse*/false);
1611 }
1612}
1613
1614/// HandleEndifDirective - Implements the #endif directive.
1615///
1616void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1617 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00001618
Chris Lattnerf64b3522008-03-09 01:54:53 +00001619 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001620 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00001621
Chris Lattnerf64b3522008-03-09 01:54:53 +00001622 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001623 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001624 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00001625 Diag(EndifToken, diag::err_pp_endif_without_if);
1626 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001627 }
Mike Stump11289f42009-09-09 15:08:12 +00001628
Chris Lattnerf64b3522008-03-09 01:54:53 +00001629 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001630 if (CurPPLexer->getConditionalStackDepth() == 0)
1631 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001632
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001633 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00001634 "This code should only be reachable in the non-skipping case!");
1635}
1636
1637
1638void Preprocessor::HandleElseDirective(Token &Result) {
1639 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001640
Chris Lattnerf64b3522008-03-09 01:54:53 +00001641 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001642 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00001643
Chris Lattnerf64b3522008-03-09 01:54:53 +00001644 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001645 if (CurPPLexer->popConditionalLevel(CI)) {
1646 Diag(Result, diag::pp_err_else_without_if);
1647 return;
1648 }
Mike Stump11289f42009-09-09 15:08:12 +00001649
Chris Lattnerf64b3522008-03-09 01:54:53 +00001650 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001651 if (CurPPLexer->getConditionalStackDepth() == 0)
1652 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001653
1654 // If this is a #else with a #else before it, report the error.
1655 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattnerf64b3522008-03-09 01:54:53 +00001657 // Finally, skip the rest of the contents of this block and return the first
1658 // token after it.
1659 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1660 /*FoundElse*/true);
1661}
1662
1663void Preprocessor::HandleElifDirective(Token &ElifToken) {
1664 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001665
Chris Lattnerf64b3522008-03-09 01:54:53 +00001666 // #elif directive in a non-skipping conditional... start skipping.
1667 // We don't care what the condition is, because we will always skip it (since
1668 // the block immediately before it was included).
1669 DiscardUntilEndOfDirective();
1670
1671 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001672 if (CurPPLexer->popConditionalLevel(CI)) {
1673 Diag(ElifToken, diag::pp_err_elif_without_if);
1674 return;
1675 }
Mike Stump11289f42009-09-09 15:08:12 +00001676
Chris Lattnerf64b3522008-03-09 01:54:53 +00001677 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001678 if (CurPPLexer->getConditionalStackDepth() == 0)
1679 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattnerf64b3522008-03-09 01:54:53 +00001681 // If this is a #elif with a #else before it, report the error.
1682 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1683
1684 // Finally, skip the rest of the contents of this block and return the first
1685 // token after it.
1686 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1687 /*FoundElse*/CI.FoundElse);
1688}