blob: 00cdbd774e352cd7132964fbb45a6806acdd448a [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"
Douglas Gregor3a7ad252010-08-24 19:08:16 +000019#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregorc7d65762010-09-09 22:45:38 +000020#include "clang/Lex/Pragma.h"
Chris Lattner710bb872009-11-30 04:18:44 +000021#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000023#include "llvm/ADT/APInt.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000024using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Utility Methods for Preprocessor Directive Handling.
28//===----------------------------------------------------------------------===//
29
Chris Lattnerc0a585d2010-08-17 15:55:45 +000030MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000031 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000032
Ted Kremenekc8456f82010-10-19 22:15:20 +000033 if (MICache) {
34 MIChain = MICache;
35 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000036 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000037 else {
38 MIChain = BP.Allocate<MacroInfoChain>();
39 }
40
41 MIChain->Next = MIChainHead;
42 MIChain->Prev = 0;
43 if (MIChainHead)
44 MIChainHead->Prev = MIChain;
45 MIChainHead = MIChain;
46
47 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000048}
49
50MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
51 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000052 new (MI) MacroInfo(L);
53 return MI;
54}
55
Chris Lattnerc0a585d2010-08-17 15:55:45 +000056MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
57 MacroInfo *MI = AllocateMacroInfo();
58 new (MI) MacroInfo(MacroToClone, BP);
59 return MI;
60}
61
Chris Lattner666f7a42009-02-20 22:19:20 +000062/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
63/// be reused for allocating new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +000064void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +000065 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
66 if (MacroInfoChain *Prev = MIChain->Prev) {
67 MacroInfoChain *Next = MIChain->Next;
68 Prev->Next = Next;
69 if (Next)
70 Next->Prev = Prev;
71 }
72 else {
73 assert(MIChainHead == MIChain);
74 MIChainHead = MIChain->Next;
75 MIChainHead->Prev = 0;
76 }
77 MIChain->Next = MICache;
78 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +000079
Ted Kremenekc8456f82010-10-19 22:15:20 +000080 MI->Destroy();
81}
Chris Lattner666f7a42009-02-20 22:19:20 +000082
Chris Lattnerf64b3522008-03-09 01:54:53 +000083/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
84/// current line until the tok::eom token is found.
85void Preprocessor::DiscardUntilEndOfDirective() {
86 Token Tmp;
87 do {
88 LexUnexpandedToken(Tmp);
89 } while (Tmp.isNot(tok::eom));
90}
91
Chris Lattnerf64b3522008-03-09 01:54:53 +000092/// ReadMacroName - Lex and validate a macro name, which occurs after a
93/// #define or #undef. This sets the token kind to eom and discards the rest
94/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
95/// this is due to a a #define, 2 if #undef directive, 0 if it is something
96/// else (e.g. #ifdef).
97void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
98 // Read the token, don't allow macro expansion on it.
99 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000100
Douglas Gregor12785102010-08-24 20:21:13 +0000101 if (MacroNameTok.is(tok::code_completion)) {
102 if (CodeComplete)
103 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
104 LexUnexpandedToken(MacroNameTok);
105 return;
106 }
107
Chris Lattnerf64b3522008-03-09 01:54:53 +0000108 // Missing macro name?
Chris Lattner907dfe92008-11-18 07:59:24 +0000109 if (MacroNameTok.is(tok::eom)) {
110 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
111 return;
112 }
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattnerf64b3522008-03-09 01:54:53 +0000114 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
115 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000116 bool Invalid = false;
117 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
118 if (Invalid)
119 return;
120
Chris Lattner77c76ae2008-12-13 20:12:40 +0000121 const IdentifierInfo &Info = Identifiers.get(Spelling);
122 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000123 // C++ 2.5p2: Alternative tokens behave the same as its primary token
124 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000125 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000126 else
127 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
128 // Fall through on error.
129 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
130 // Error if defining "defined": C99 6.10.8.4.
131 Diag(MacroNameTok, diag::err_defined_macro_name);
132 } else if (isDefineUndef && II->hasMacroDefinition() &&
133 getMacroInfo(II)->isBuiltinMacro()) {
134 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
135 if (isDefineUndef == 1)
136 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
137 else
138 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
139 } else {
140 // Okay, we got a good identifier node. Return it.
141 return;
142 }
Mike Stump11289f42009-09-09 15:08:12 +0000143
Chris Lattnerf64b3522008-03-09 01:54:53 +0000144 // Invalid macro name, read and discard the rest of the line. Then set the
145 // token kind to tok::eom.
146 MacroNameTok.setKind(tok::eom);
147 return DiscardUntilEndOfDirective();
148}
149
150/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
Chris Lattner0003c272009-04-17 23:30:53 +0000151/// not, emit a diagnostic and consume up until the eom. If EnableMacros is
152/// true, then we consider macros that expand to zero tokens as being ok.
153void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000154 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000155 // Lex unexpanded tokens for most directives: macros might expand to zero
156 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
157 // #line) allow empty macros.
158 if (EnableMacros)
159 Lex(Tmp);
160 else
161 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000162
Chris Lattnerf64b3522008-03-09 01:54:53 +0000163 // There should be no tokens after the directive, but we allow them as an
164 // extension.
165 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
166 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattnerf64b3522008-03-09 01:54:53 +0000168 if (Tmp.isNot(tok::eom)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000169 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
170 // because it is more trouble than it is worth to insert /**/ and check that
171 // there is no /**/ in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000172 FixItHint Hint;
Chris Lattner825676a2009-04-14 05:15:20 +0000173 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
Douglas Gregora771f462010-03-31 17:46:05 +0000174 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
175 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000176 DiscardUntilEndOfDirective();
177 }
178}
179
180
181
182/// SkipExcludedConditionalBlock - We just read a #if or related directive and
183/// decided that the subsequent tokens are in the #if'd out portion of the
184/// file. Lex the rest of the file, until we see an #endif. If
185/// FoundNonSkipPortion is true, then we have already emitted code for part of
186/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
187/// is true, then #else directives are ok, if not, then we have already seen one
188/// so a #else directive is a duplicate. When this returns, the caller can lex
189/// the first valid token.
190void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
191 bool FoundNonSkipPortion,
192 bool FoundElse) {
193 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000194 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000195
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000196 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000197 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000198
Ted Kremenek56572ab2008-12-12 18:34:08 +0000199 if (CurPTHLexer) {
200 PTHSkipExcludedConditionalBlock();
201 return;
202 }
Mike Stump11289f42009-09-09 15:08:12 +0000203
Chris Lattnerf64b3522008-03-09 01:54:53 +0000204 // Enter raw mode to disable identifier lookup (and thus macro expansion),
205 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000206 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000207 Token Tok;
208 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000209 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000210
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000211 if (Tok.is(tok::code_completion)) {
212 if (CodeComplete)
213 CodeComplete->CodeCompleteInConditionalExclusion();
214 continue;
215 }
216
Chris Lattnerf64b3522008-03-09 01:54:53 +0000217 // If this is the end of the buffer, we have an error.
218 if (Tok.is(tok::eof)) {
219 // Emit errors for each unterminated conditional on the stack, including
220 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000221 while (!CurPPLexer->ConditionalStack.empty()) {
Douglas Gregor02690ba2010-08-12 17:04:55 +0000222 if (!isCodeCompletionFile(Tok.getLocation()))
223 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
224 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000225 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000226 }
227
Chris Lattnerf64b3522008-03-09 01:54:53 +0000228 // Just return and let the caller lex after this #include.
229 break;
230 }
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattnerf64b3522008-03-09 01:54:53 +0000232 // If this token is not a preprocessor directive, just skip it.
233 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
234 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000235
Chris Lattnerf64b3522008-03-09 01:54:53 +0000236 // We just parsed a # character at the start of a line, so we're in
237 // directive mode. Tell the lexer this so any newlines we see will be
238 // converted into an EOM token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000239 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000240 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000241
Mike Stump11289f42009-09-09 15:08:12 +0000242
Chris Lattnerf64b3522008-03-09 01:54:53 +0000243 // Read the next token, the directive flavor.
244 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000245
Chris Lattnerf64b3522008-03-09 01:54:53 +0000246 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
247 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000248 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000249 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000250 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000251 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000252 continue;
253 }
254
255 // If the first letter isn't i or e, it isn't intesting to us. We know that
256 // this is safe in the face of spelling differences, because there is no way
257 // to spell an i/e in a strange way that is another letter. Skipping this
258 // allows us to avoid looking up the identifier info for #define/#undef and
259 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000260 const char *RawCharData = Tok.getRawIdentifierData();
261
Chris Lattnerf64b3522008-03-09 01:54:53 +0000262 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000263 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000264 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000265 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000266 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000267 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000268 continue;
269 }
Mike Stump11289f42009-09-09 15:08:12 +0000270
Chris Lattnerf64b3522008-03-09 01:54:53 +0000271 // Get the identifier name without trigraphs or embedded newlines. Note
272 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
273 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000274 char DirectiveBuf[20];
275 llvm::StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000276 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramer144884642009-12-31 13:32:38 +0000277 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000278 } else {
279 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000280 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000281 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000282 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000283 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000284 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000285 continue;
286 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000287 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
288 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000289 }
Mike Stump11289f42009-09-09 15:08:12 +0000290
Benjamin Kramer144884642009-12-31 13:32:38 +0000291 if (Directive.startswith("if")) {
292 llvm::StringRef Sub = Directive.substr(2);
293 if (Sub.empty() || // "if"
294 Sub == "def" || // "ifdef"
295 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000296 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
297 // bother parsing the condition.
298 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000299 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000300 /*foundnonskip*/false,
301 /*fnddelse*/false);
302 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000303 } else if (Directive[0] == 'e') {
304 llvm::StringRef Sub = Directive.substr(1);
305 if (Sub == "ndif") { // "endif"
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000306 CheckEndOfDirective("endif");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000307 PPConditionalInfo CondInfo;
308 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000309 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000310 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000311 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000312
Chris Lattnerf64b3522008-03-09 01:54:53 +0000313 // If we popped the outermost skipping block, we're done skipping!
314 if (!CondInfo.WasSkipping)
315 break;
Benjamin Kramer144884642009-12-31 13:32:38 +0000316 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000317 // #else directive in a skipping conditional. If not in some other
318 // skipping conditional, and if #else hasn't already been seen, enter it
319 // as a non-skipping conditional.
Chris Lattnerbc63de12009-04-18 01:34:22 +0000320 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000321 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattnerf64b3522008-03-09 01:54:53 +0000323 // If this is a #else with a #else before it, report the error.
324 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattnerf64b3522008-03-09 01:54:53 +0000326 // Note that we've seen a #else in this conditional.
327 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000328
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 // If the conditional is at the top level, and the #if block wasn't
330 // entered, enter the #else block now.
331 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
332 CondInfo.FoundNonSkip = true;
333 break;
334 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000335 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000336 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000337
338 bool ShouldEnter;
339 // If this is in a skipping block or if we're already handled this #if
340 // block, don't bother parsing the condition.
341 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
342 DiscardUntilEndOfDirective();
343 ShouldEnter = false;
344 } else {
345 // Restore the value of LexingRawMode so that identifiers are
346 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000347 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
348 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000349 IdentifierInfo *IfNDefMacro = 0;
350 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000351 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000352 }
Mike Stump11289f42009-09-09 15:08:12 +0000353
Chris Lattnerf64b3522008-03-09 01:54:53 +0000354 // If this is a #elif with a #else before it, report the error.
355 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000356
Chris Lattnerf64b3522008-03-09 01:54:53 +0000357 // If this condition is true, enter it!
358 if (ShouldEnter) {
359 CondInfo.FoundNonSkip = true;
360 break;
361 }
362 }
363 }
Mike Stump11289f42009-09-09 15:08:12 +0000364
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000365 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000366 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000367 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000368 }
369
370 // Finally, if we are out of the conditional (saw an #endif or ran off the end
371 // of the file, just stop skipping and return to lexing whatever came after
372 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000373 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000374}
375
Ted Kremenek56572ab2008-12-12 18:34:08 +0000376void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000377
378 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000379 assert(CurPTHLexer);
380 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Ted Kremenek56572ab2008-12-12 18:34:08 +0000382 // Skip to the next '#else', '#elif', or #endif.
383 if (CurPTHLexer->SkipBlock()) {
384 // We have reached an #endif. Both the '#' and 'endif' tokens
385 // have been consumed by the PTHLexer. Just pop off the condition level.
386 PPConditionalInfo CondInfo;
387 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000388 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000389 assert(!InCond && "Can't be skipping if not in a conditional!");
390 break;
391 }
Mike Stump11289f42009-09-09 15:08:12 +0000392
Ted Kremenek56572ab2008-12-12 18:34:08 +0000393 // We have reached a '#else' or '#elif'. Lex the next token to get
394 // the directive flavor.
395 Token Tok;
396 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000397
Ted Kremenek56572ab2008-12-12 18:34:08 +0000398 // We can actually look up the IdentifierInfo here since we aren't in
399 // raw mode.
400 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
401
402 if (K == tok::pp_else) {
403 // #else: Enter the else condition. We aren't in a nested condition
404 // since we skip those. We're always in the one matching the last
405 // blocked we skipped.
406 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
407 // Note that we've seen a #else in this conditional.
408 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000409
Ted Kremenek56572ab2008-12-12 18:34:08 +0000410 // If the #if block wasn't entered then enter the #else block now.
411 if (!CondInfo.FoundNonSkip) {
412 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000413
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000414 // Scan until the eom token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000415 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000416 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000417 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000418
Ted Kremenek56572ab2008-12-12 18:34:08 +0000419 break;
420 }
Mike Stump11289f42009-09-09 15:08:12 +0000421
Ted Kremenek56572ab2008-12-12 18:34:08 +0000422 // Otherwise skip this block.
423 continue;
424 }
Mike Stump11289f42009-09-09 15:08:12 +0000425
Ted Kremenek56572ab2008-12-12 18:34:08 +0000426 assert(K == tok::pp_elif);
427 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
428
429 // If this is a #elif with a #else before it, report the error.
430 if (CondInfo.FoundElse)
431 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000432
Ted Kremenek56572ab2008-12-12 18:34:08 +0000433 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000434 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000435 if (CondInfo.FoundNonSkip)
436 continue;
437
438 // Evaluate the condition of the #elif.
439 IdentifierInfo *IfNDefMacro = 0;
440 CurPTHLexer->ParsingPreprocessorDirective = true;
441 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
442 CurPTHLexer->ParsingPreprocessorDirective = false;
443
444 // If this condition is true, enter it!
445 if (ShouldEnter) {
446 CondInfo.FoundNonSkip = true;
447 break;
448 }
449
450 // Otherwise, skip this block and go to the next one.
451 continue;
452 }
453}
454
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000455/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
456/// return null on failure. isAngled indicates whether the file reference is
457/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000458const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000459 bool isAngled,
460 const DirectoryLookup *FromDir,
461 const DirectoryLookup *&CurDir) {
462 // If the header lookup mechanism may be relative to the current file, pass in
463 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000464 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000465 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000466 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000467 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000468
Chris Lattner022923a2009-02-04 19:45:07 +0000469 // If there is no file entry associated with this file, it must be the
470 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000471 // it won't be scanned for preprocessor directives. If we have the
472 // predefines buffer, resolve #include references (which come from the
473 // -include command line argument) as if they came from the main file, this
474 // affects file lookup etc.
475 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000476 FID = SourceMgr.getMainFileID();
477 CurFileEnt = SourceMgr.getFileEntryForID(FID);
478 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000479 }
Mike Stump11289f42009-09-09 15:08:12 +0000480
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000481 // Do a standard file entry lookup.
482 CurDir = CurDirLookup;
483 const FileEntry *FE =
Douglas Gregor618e64a2010-08-08 07:49:23 +0000484 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerfde85352010-01-22 00:14:44 +0000485 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000486
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000487 // Otherwise, see if this is a subframework header. If so, this is relative
488 // to one of the headers on the #include stack. Walk the list of the current
489 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000490 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000491 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000492 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000493 return FE;
494 }
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000496 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
497 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000498 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000499 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000500 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000501 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000502 return FE;
503 }
504 }
Mike Stump11289f42009-09-09 15:08:12 +0000505
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000506 // Otherwise, we really couldn't find the file.
507 return 0;
508}
509
Chris Lattnerf64b3522008-03-09 01:54:53 +0000510
511//===----------------------------------------------------------------------===//
512// Preprocessor Directive Handling.
513//===----------------------------------------------------------------------===//
514
515/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000516/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000517/// lexer/preprocessor state, and advances the lexer(s) so that the next token
518/// read is the correct one.
519void Preprocessor::HandleDirective(Token &Result) {
520 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000521
Chris Lattnerf64b3522008-03-09 01:54:53 +0000522 // We just parsed a # character at the start of a line, so we're in directive
523 // mode. Tell the lexer this so any newlines we see will be converted into an
524 // EOM token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000525 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Chris Lattnerf64b3522008-03-09 01:54:53 +0000527 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000528
Chris Lattnerf64b3522008-03-09 01:54:53 +0000529 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000530 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000531 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000532 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000533
Chris Lattner2d17ab72009-03-18 21:00:25 +0000534 // Save the '#' token in case we need to return it later.
535 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000536
Chris Lattnerf64b3522008-03-09 01:54:53 +0000537 // Read the next token, the directive flavor. This isn't expanded due to
538 // C99 6.10.3p8.
539 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000540
Chris Lattnerf64b3522008-03-09 01:54:53 +0000541 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
542 // #define A(x) #x
543 // A(abc
544 // #warning blah
545 // def)
546 // If so, the user is relying on non-portable behavior, emit a diagnostic.
547 if (InMacroArgs)
548 Diag(Result, diag::ext_embedded_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattnerf64b3522008-03-09 01:54:53 +0000550TryAgain:
551 switch (Result.getKind()) {
552 case tok::eom:
553 return; // null directive.
554 case tok::comment:
555 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
556 LexUnexpandedToken(Result);
557 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000558 case tok::code_completion:
559 if (CodeComplete)
560 CodeComplete->CodeCompleteDirective(
561 CurPPLexer->getConditionalStackDepth() > 0);
562 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000563 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000564 if (getLangOptions().AsmPreprocessor)
565 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000566 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000567 default:
568 IdentifierInfo *II = Result.getIdentifierInfo();
569 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000570
Chris Lattnerf64b3522008-03-09 01:54:53 +0000571 // Ask what the preprocessor keyword ID is.
572 switch (II->getPPKeywordID()) {
573 default: break;
574 // C99 6.10.1 - Conditional Inclusion.
575 case tok::pp_if:
576 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
577 case tok::pp_ifdef:
578 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
579 case tok::pp_ifndef:
580 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
581 case tok::pp_elif:
582 return HandleElifDirective(Result);
583 case tok::pp_else:
584 return HandleElseDirective(Result);
585 case tok::pp_endif:
586 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000587
Chris Lattnerf64b3522008-03-09 01:54:53 +0000588 // C99 6.10.2 - Source File Inclusion.
589 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000590 // Handle #include.
591 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000592 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000593 // Handle -imacros.
594 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000595
Chris Lattnerf64b3522008-03-09 01:54:53 +0000596 // C99 6.10.3 - Macro Replacement.
597 case tok::pp_define:
598 return HandleDefineDirective(Result);
599 case tok::pp_undef:
600 return HandleUndefDirective(Result);
601
602 // C99 6.10.4 - Line Control.
603 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000604 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000605
Chris Lattnerf64b3522008-03-09 01:54:53 +0000606 // C99 6.10.5 - Error Directive.
607 case tok::pp_error:
608 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000609
Chris Lattnerf64b3522008-03-09 01:54:53 +0000610 // C99 6.10.6 - Pragma Directive.
611 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000612 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000613
Chris Lattnerf64b3522008-03-09 01:54:53 +0000614 // GNU Extensions.
615 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000616 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000617 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000618 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000619
Chris Lattnerf64b3522008-03-09 01:54:53 +0000620 case tok::pp_warning:
621 Diag(Result, diag::ext_pp_warning_directive);
622 return HandleUserDiagnosticDirective(Result, true);
623 case tok::pp_ident:
624 return HandleIdentSCCSDirective(Result);
625 case tok::pp_sccs:
626 return HandleIdentSCCSDirective(Result);
627 case tok::pp_assert:
628 //isExtension = true; // FIXME: implement #assert
629 break;
630 case tok::pp_unassert:
631 //isExtension = true; // FIXME: implement #unassert
632 break;
633 }
634 break;
635 }
Mike Stump11289f42009-09-09 15:08:12 +0000636
Chris Lattner2d17ab72009-03-18 21:00:25 +0000637 // If this is a .S file, treat unknown # directives as non-preprocessor
638 // directives. This is important because # may be a comment or introduce
639 // various pseudo-ops. Just return the # token and push back the following
640 // token to be lexed next time.
641 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000642 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000643 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000644 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000645 Toks[1] = Result;
646 // Enter this token stream so that we re-lex the tokens. Make sure to
647 // enable macro expansion, in case the token after the # is an identifier
648 // that is expanded.
649 EnterTokenStream(Toks, 2, false, true);
650 return;
651 }
Mike Stump11289f42009-09-09 15:08:12 +0000652
Chris Lattnerf64b3522008-03-09 01:54:53 +0000653 // If we reached here, the preprocessing token is not valid!
654 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000655
Chris Lattnerf64b3522008-03-09 01:54:53 +0000656 // Read the rest of the PP line.
657 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000658
Chris Lattnerf64b3522008-03-09 01:54:53 +0000659 // Okay, we're done parsing the directive.
660}
661
Chris Lattner76e68962009-01-26 06:19:46 +0000662/// GetLineValue - Convert a numeric token into an unsigned value, emitting
663/// Diagnostic DiagID if it is invalid, and returning the value in Val.
664static bool GetLineValue(Token &DigitTok, unsigned &Val,
665 unsigned DiagID, Preprocessor &PP) {
666 if (DigitTok.isNot(tok::numeric_constant)) {
667 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000668
Chris Lattner76e68962009-01-26 06:19:46 +0000669 if (DigitTok.isNot(tok::eom))
670 PP.DiscardUntilEndOfDirective();
671 return true;
672 }
Mike Stump11289f42009-09-09 15:08:12 +0000673
Chris Lattner76e68962009-01-26 06:19:46 +0000674 llvm::SmallString<64> IntegerBuffer;
675 IntegerBuffer.resize(DigitTok.getLength());
676 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000677 bool Invalid = false;
678 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
679 if (Invalid)
680 return true;
681
Chris Lattnerd66f1722009-04-18 18:35:15 +0000682 // Verify that we have a simple digit-sequence, and compute the value. This
683 // is always a simple digit string computed in decimal, so we do this manually
684 // here.
685 Val = 0;
686 for (unsigned i = 0; i != ActualLength; ++i) {
687 if (!isdigit(DigitTokBegin[i])) {
688 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
689 diag::err_pp_line_digit_sequence);
690 PP.DiscardUntilEndOfDirective();
691 return true;
692 }
Mike Stump11289f42009-09-09 15:08:12 +0000693
Chris Lattnerd66f1722009-04-18 18:35:15 +0000694 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
695 if (NextVal < Val) { // overflow.
696 PP.Diag(DigitTok, DiagID);
697 PP.DiscardUntilEndOfDirective();
698 return true;
699 }
700 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000701 }
Mike Stump11289f42009-09-09 15:08:12 +0000702
703 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000704 if (Val == 0) {
705 PP.Diag(DigitTok, DiagID);
706 PP.DiscardUntilEndOfDirective();
707 return true;
708 }
Mike Stump11289f42009-09-09 15:08:12 +0000709
Chris Lattnerd66f1722009-04-18 18:35:15 +0000710 if (DigitTokBegin[0] == '0')
711 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000712
Chris Lattner76e68962009-01-26 06:19:46 +0000713 return false;
714}
715
Mike Stump11289f42009-09-09 15:08:12 +0000716/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner100c65e2009-01-26 05:29:08 +0000717/// acceptable forms are:
718/// # line digit-sequence
719/// # line digit-sequence "s-char-sequence"
720void Preprocessor::HandleLineDirective(Token &Tok) {
721 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
722 // expanded.
723 Token DigitTok;
724 Lex(DigitTok);
725
Chris Lattner100c65e2009-01-26 05:29:08 +0000726 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000727 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000728 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000729 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000730
Chris Lattner76e68962009-01-26 06:19:46 +0000731 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
732 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner100c65e2009-01-26 05:29:08 +0000733 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
734 if (LineNo >= LineLimit)
735 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump11289f42009-09-09 15:08:12 +0000736
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000737 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000738 Token StrTok;
739 Lex(StrTok);
740
741 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
742 // string followed by eom.
Mike Stump11289f42009-09-09 15:08:12 +0000743 if (StrTok.is(tok::eom))
Chris Lattner100c65e2009-01-26 05:29:08 +0000744 ; // ok
745 else if (StrTok.isNot(tok::string_literal)) {
746 Diag(StrTok, diag::err_pp_line_invalid_filename);
747 DiscardUntilEndOfDirective();
748 return;
749 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000750 // Parse and validate the string, converting it into a unique ID.
751 StringLiteralParser Literal(&StrTok, 1, *this);
752 assert(!Literal.AnyWide && "Didn't allow wide strings in");
753 if (Literal.hadError)
754 return DiscardUntilEndOfDirective();
755 if (Literal.Pascal) {
756 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
757 return DiscardUntilEndOfDirective();
758 }
759 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
760 Literal.GetStringLength());
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattner0003c272009-04-17 23:30:53 +0000762 // Verify that there is nothing after the string, other than EOM. Because
763 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
764 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000765 }
Mike Stump11289f42009-09-09 15:08:12 +0000766
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000767 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000768
Chris Lattner839150e2009-03-27 17:13:49 +0000769 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000770 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
771 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000772 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000773}
774
Chris Lattner76e68962009-01-26 06:19:46 +0000775/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
776/// marker directive.
777static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
778 bool &IsSystemHeader, bool &IsExternCHeader,
779 Preprocessor &PP) {
780 unsigned FlagVal;
781 Token FlagTok;
782 PP.Lex(FlagTok);
783 if (FlagTok.is(tok::eom)) return false;
784 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
785 return true;
786
787 if (FlagVal == 1) {
788 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000789
Chris Lattner76e68962009-01-26 06:19:46 +0000790 PP.Lex(FlagTok);
791 if (FlagTok.is(tok::eom)) return false;
792 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
793 return true;
794 } else if (FlagVal == 2) {
795 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000796
Chris Lattner1c967782009-02-04 06:25:26 +0000797 SourceManager &SM = PP.getSourceManager();
798 // If we are leaving the current presumed file, check to make sure the
799 // presumed include stack isn't empty!
800 FileID CurFileID =
801 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
802 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000803 if (PLoc.isInvalid())
804 return true;
805
Chris Lattner1c967782009-02-04 06:25:26 +0000806 // If there is no include loc (main file) or if the include loc is in a
807 // different physical file, then we aren't in a "1" line marker flag region.
808 SourceLocation IncLoc = PLoc.getIncludeLoc();
809 if (IncLoc.isInvalid() ||
810 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
811 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
812 PP.DiscardUntilEndOfDirective();
813 return true;
814 }
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chris Lattner76e68962009-01-26 06:19:46 +0000816 PP.Lex(FlagTok);
817 if (FlagTok.is(tok::eom)) return false;
818 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
819 return true;
820 }
821
822 // We must have 3 if there are still flags.
823 if (FlagVal != 3) {
824 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000825 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000826 return true;
827 }
Mike Stump11289f42009-09-09 15:08:12 +0000828
Chris Lattner76e68962009-01-26 06:19:46 +0000829 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000830
Chris Lattner76e68962009-01-26 06:19:46 +0000831 PP.Lex(FlagTok);
832 if (FlagTok.is(tok::eom)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000833 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000834 return true;
835
836 // We must have 4 if there is yet another flag.
837 if (FlagVal != 4) {
838 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000839 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000840 return true;
841 }
Mike Stump11289f42009-09-09 15:08:12 +0000842
Chris Lattner76e68962009-01-26 06:19:46 +0000843 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000844
Chris Lattner76e68962009-01-26 06:19:46 +0000845 PP.Lex(FlagTok);
846 if (FlagTok.is(tok::eom)) return false;
847
848 // There are no more valid flags here.
849 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000850 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000851 return true;
852}
853
854/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
855/// one of the following forms:
856///
857/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000858/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000859/// # 42 "file" ('1' | '2')? '3' '4'?
860///
861void Preprocessor::HandleDigitDirective(Token &DigitTok) {
862 // Validate the number and convert it to an unsigned. GNU does not have a
863 // line # limit other than it fit in 32-bits.
864 unsigned LineNo;
865 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
866 *this))
867 return;
Mike Stump11289f42009-09-09 15:08:12 +0000868
Chris Lattner76e68962009-01-26 06:19:46 +0000869 Token StrTok;
870 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000871
Chris Lattner76e68962009-01-26 06:19:46 +0000872 bool IsFileEntry = false, IsFileExit = false;
873 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000874 int FilenameID = -1;
875
Chris Lattner76e68962009-01-26 06:19:46 +0000876 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
877 // string followed by eom.
Mike Stump11289f42009-09-09 15:08:12 +0000878 if (StrTok.is(tok::eom))
Chris Lattner76e68962009-01-26 06:19:46 +0000879 ; // ok
880 else if (StrTok.isNot(tok::string_literal)) {
881 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000882 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000883 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000884 // Parse and validate the string, converting it into a unique ID.
885 StringLiteralParser Literal(&StrTok, 1, *this);
886 assert(!Literal.AnyWide && "Didn't allow wide strings in");
887 if (Literal.hadError)
888 return DiscardUntilEndOfDirective();
889 if (Literal.Pascal) {
890 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
891 return DiscardUntilEndOfDirective();
892 }
893 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
894 Literal.GetStringLength());
Mike Stump11289f42009-09-09 15:08:12 +0000895
Chris Lattner76e68962009-01-26 06:19:46 +0000896 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +0000897 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000898 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +0000899 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000900 }
Mike Stump11289f42009-09-09 15:08:12 +0000901
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000902 // Create a line note with this information.
903 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +0000904 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000905 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +0000906
Chris Lattner839150e2009-03-27 17:13:49 +0000907 // If the preprocessor has callbacks installed, notify them of the #line
908 // change. This is used so that the line marker comes out in -E mode for
909 // example.
910 if (Callbacks) {
911 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
912 if (IsFileEntry)
913 Reason = PPCallbacks::EnterFile;
914 else if (IsFileExit)
915 Reason = PPCallbacks::ExitFile;
916 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
917 if (IsExternCHeader)
918 FileKind = SrcMgr::C_ExternCSystem;
919 else if (IsSystemHeader)
920 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +0000921
Chris Lattnerc745cec2010-04-14 04:28:50 +0000922 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +0000923 }
Chris Lattner76e68962009-01-26 06:19:46 +0000924}
925
926
Chris Lattner38d7fd22009-01-26 05:30:54 +0000927/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
928///
Mike Stump11289f42009-09-09 15:08:12 +0000929void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000930 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +0000931 // PTH doesn't emit #warning or #error directives.
932 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +0000933 return CurPTHLexer->DiscardToEndOfLine();
934
Chris Lattnerf64b3522008-03-09 01:54:53 +0000935 // Read the rest of the line raw. We do this because we don't want macros
936 // to be expanded and we don't require that the tokens be valid preprocessing
937 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
938 // collapse multiple consequtive white space between tokens, but this isn't
939 // specified by the standard.
Chris Lattner100c65e2009-01-26 05:29:08 +0000940 std::string Message = CurLexer->ReadToEndOfLine();
941 if (isWarning)
942 Diag(Tok, diag::pp_hash_warning) << Message;
943 else
944 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000945}
946
947/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
948///
949void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
950 // Yes, this directive is an extension.
951 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000952
Chris Lattnerf64b3522008-03-09 01:54:53 +0000953 // Read the string argument.
954 Token StrTok;
955 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000956
Chris Lattnerf64b3522008-03-09 01:54:53 +0000957 // If the token kind isn't a string, it's a malformed directive.
958 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +0000959 StrTok.isNot(tok::wide_string_literal)) {
960 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner38d7fd22009-01-26 05:30:54 +0000961 if (StrTok.isNot(tok::eom))
962 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000963 return;
964 }
Mike Stump11289f42009-09-09 15:08:12 +0000965
Chris Lattnerf64b3522008-03-09 01:54:53 +0000966 // Verify that there is nothing after the string, other than EOM.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000967 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000968
Douglas Gregordc970f02010-03-16 22:30:13 +0000969 if (Callbacks) {
970 bool Invalid = false;
971 std::string Str = getSpelling(StrTok, &Invalid);
972 if (!Invalid)
973 Callbacks->Ident(Tok.getLocation(), Str);
974 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000975}
976
977//===----------------------------------------------------------------------===//
978// Preprocessor Include Directive Handling.
979//===----------------------------------------------------------------------===//
980
981/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
982/// checked and spelled filename, e.g. as an operand of #include. This returns
983/// true if the input filename was in <>'s or false if it were in ""'s. The
984/// caller is expected to provide a buffer that is large enough to hold the
985/// spelling of the filename, but is also expected to handle the case when
986/// this method decides to use a different buffer.
987bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000988 llvm::StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000989 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000990 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +0000991
Chris Lattnerf64b3522008-03-09 01:54:53 +0000992 // Make sure the filename is <x> or "x".
993 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000994 if (Buffer[0] == '<') {
995 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000996 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000997 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000998 return true;
999 }
1000 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001001 } else if (Buffer[0] == '"') {
1002 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001003 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001004 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001005 return true;
1006 }
1007 isAngled = false;
1008 } else {
1009 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001010 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001011 return true;
1012 }
Mike Stump11289f42009-09-09 15:08:12 +00001013
Chris Lattnerf64b3522008-03-09 01:54:53 +00001014 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001015 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001016 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001017 Buffer = llvm::StringRef();
1018 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001019 }
Mike Stump11289f42009-09-09 15:08:12 +00001020
Chris Lattnerf64b3522008-03-09 01:54:53 +00001021 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001022 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001023 return isAngled;
1024}
1025
1026/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1027/// from a macro as multiple tokens, which need to be glued together. This
1028/// occurs for code like:
1029/// #define FOO <a/b.h>
1030/// #include FOO
1031/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1032///
1033/// This code concatenates and consumes tokens up to the '>' token. It returns
1034/// false if the > was found, otherwise it returns true if it finds and consumes
1035/// the EOM marker.
John Thompsonb5353522009-10-30 13:49:06 +00001036bool Preprocessor::ConcatenateIncludeName(
Douglas Gregor796d76a2010-10-20 22:00:55 +00001037 llvm::SmallString<128> &FilenameBuffer,
1038 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001039 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001040
John Thompsonb5353522009-10-30 13:49:06 +00001041 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001042 while (CurTok.isNot(tok::eom)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001043 End = CurTok.getLocation();
1044
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001045 // FIXME: Provide code completion for #includes.
1046 if (CurTok.is(tok::code_completion)) {
1047 Lex(CurTok);
1048 continue;
1049 }
1050
Chris Lattnerf64b3522008-03-09 01:54:53 +00001051 // Append the spelling of this token to the buffer. If there was a space
1052 // before it, add it now.
1053 if (CurTok.hasLeadingSpace())
1054 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001055
Chris Lattnerf64b3522008-03-09 01:54:53 +00001056 // Get the spelling of the token, directly into FilenameBuffer if possible.
1057 unsigned PreAppendSize = FilenameBuffer.size();
1058 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001059
Chris Lattnerf64b3522008-03-09 01:54:53 +00001060 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001061 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001062
Chris Lattnerf64b3522008-03-09 01:54:53 +00001063 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1064 if (BufPtr != &FilenameBuffer[PreAppendSize])
1065 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001066
Chris Lattnerf64b3522008-03-09 01:54:53 +00001067 // Resize FilenameBuffer to the correct size.
1068 if (CurTok.getLength() != ActualLen)
1069 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chris Lattnerf64b3522008-03-09 01:54:53 +00001071 // If we found the '>' marker, return success.
1072 if (CurTok.is(tok::greater))
1073 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001074
John Thompsonb5353522009-10-30 13:49:06 +00001075 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001076 }
1077
1078 // If we hit the eom marker, emit an error and return true so that the caller
1079 // knows the EOM has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001080 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001081 return true;
1082}
1083
1084/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1085/// file to be included from the lexer, then include it! This is a common
1086/// routine with functionality shared between #include, #include_next and
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001087/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001088/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001089void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1090 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001091 const DirectoryLookup *LookupFrom,
1092 bool isImport) {
1093
1094 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001095 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001096
Chris Lattnerf64b3522008-03-09 01:54:53 +00001097 // Reserve a buffer to get the spelling.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001098 llvm::SmallString<128> FilenameBuffer;
1099 llvm::StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001100 SourceLocation End;
1101
Chris Lattnerf64b3522008-03-09 01:54:53 +00001102 switch (FilenameTok.getKind()) {
1103 case tok::eom:
1104 // If the token kind is EOM, the error has already been diagnosed.
1105 return;
Mike Stump11289f42009-09-09 15:08:12 +00001106
Chris Lattnerf64b3522008-03-09 01:54:53 +00001107 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001108 case tok::string_literal:
1109 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001110 End = FilenameTok.getLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001111 break;
Mike Stump11289f42009-09-09 15:08:12 +00001112
Chris Lattnerf64b3522008-03-09 01:54:53 +00001113 case tok::less:
1114 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1115 // case, glue the tokens together into FilenameBuffer and interpret those.
1116 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001117 if (ConcatenateIncludeName(FilenameBuffer, End))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001118 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001119 Filename = FilenameBuffer.str();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001120 break;
1121 default:
1122 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1123 DiscardUntilEndOfDirective();
1124 return;
1125 }
Mike Stump11289f42009-09-09 15:08:12 +00001126
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001127 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001128 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001129 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1130 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001131 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001132 DiscardUntilEndOfDirective();
1133 return;
1134 }
Mike Stump11289f42009-09-09 15:08:12 +00001135
Chris Lattnerb40289b2009-04-17 23:56:52 +00001136 // Verify that there is nothing after the filename, other than EOM. Note that
1137 // we allow macros that expand to nothing after the filename, because this
1138 // falls into the category of "#include pp-tokens new-line" specified in
1139 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001140 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001141
1142 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001143 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1144 Diag(FilenameTok, diag::err_pp_include_too_deep);
1145 return;
1146 }
Mike Stump11289f42009-09-09 15:08:12 +00001147
Chris Lattnerf64b3522008-03-09 01:54:53 +00001148 // Search include directories.
1149 const DirectoryLookup *CurDir;
Chris Lattnerfde85352010-01-22 00:14:44 +00001150 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner907dfe92008-11-18 07:59:24 +00001151 if (File == 0) {
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001152 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner907dfe92008-11-18 07:59:24 +00001153 return;
1154 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001155
Douglas Gregor796d76a2010-10-20 22:00:55 +00001156 // Notify the callback object that we've seen an inclusion directive.
1157 if (Callbacks)
1158 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1159 End);
1160
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001161 // The #included file will be considered to be a system header if either it is
1162 // in a system include directory, or if the #includer is a system include
1163 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001164 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001165 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001166 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001167
Chris Lattner72286d62010-04-19 20:44:31 +00001168 // Ask HeaderInfo if we should enter this #include file. If not, #including
1169 // this file will have no effect.
1170 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001171 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001172 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001173 return;
1174 }
1175
Chris Lattnerf64b3522008-03-09 01:54:53 +00001176 // Look up the file, create a File ID for it.
Chris Lattnerd32480d2009-01-17 06:22:33 +00001177 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1178 FileCharacter);
1179 if (FID.isInvalid()) {
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001180 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +00001181 return;
1182 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001183
1184 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001185 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001186}
1187
1188/// HandleIncludeNextDirective - Implements #include_next.
1189///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001190void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1191 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001192 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001193
Chris Lattnerf64b3522008-03-09 01:54:53 +00001194 // #include_next is like #include, except that we start searching after
1195 // the current found directory. If we can't do this, issue a
1196 // diagnostic.
1197 const DirectoryLookup *Lookup = CurDirLookup;
1198 if (isInPrimaryFile()) {
1199 Lookup = 0;
1200 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1201 } else if (Lookup == 0) {
1202 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1203 } else {
1204 // Start looking up in the next directory.
1205 ++Lookup;
1206 }
Mike Stump11289f42009-09-09 15:08:12 +00001207
Douglas Gregor796d76a2010-10-20 22:00:55 +00001208 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001209}
1210
1211/// HandleImportDirective - Implements #import.
1212///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001213void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1214 Token &ImportTok) {
Chris Lattnerd4a96732009-03-06 04:28:03 +00001215 if (!Features.ObjC1) // #import is standard for ObjC.
1216 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001217
Douglas Gregor796d76a2010-10-20 22:00:55 +00001218 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001219}
1220
Chris Lattner58a1eb02009-04-08 18:46:40 +00001221/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1222/// pseudo directive in the predefines buffer. This handles it by sucking all
1223/// tokens through the preprocessor and discarding them (only keeping the side
1224/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001225void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1226 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001227 // This directive should only occur in the predefines buffer. If not, emit an
1228 // error and reject it.
1229 SourceLocation Loc = IncludeMacrosTok.getLocation();
1230 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1231 Diag(IncludeMacrosTok.getLocation(),
1232 diag::pp_include_macros_out_of_predefines);
1233 DiscardUntilEndOfDirective();
1234 return;
1235 }
Mike Stump11289f42009-09-09 15:08:12 +00001236
Chris Lattnere01d82b2009-04-08 20:53:24 +00001237 // Treat this as a normal #include for checking purposes. If this is
1238 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001239 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001240
Chris Lattnere01d82b2009-04-08 20:53:24 +00001241 Token TmpTok;
1242 do {
1243 Lex(TmpTok);
1244 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1245 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001246}
1247
Chris Lattnerf64b3522008-03-09 01:54:53 +00001248//===----------------------------------------------------------------------===//
1249// Preprocessor Macro Directive Handling.
1250//===----------------------------------------------------------------------===//
1251
1252/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1253/// definition has just been read. Lex the rest of the arguments and the
1254/// closing ), updating MI with what we learn. Return true if an error occurs
1255/// parsing the arg list.
1256bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1257 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001258
Chris Lattnerf64b3522008-03-09 01:54:53 +00001259 Token Tok;
1260 while (1) {
1261 LexUnexpandedToken(Tok);
1262 switch (Tok.getKind()) {
1263 case tok::r_paren:
1264 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001265 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001266 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001267 // Otherwise we have #define FOO(A,)
1268 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1269 return true;
1270 case tok::ellipsis: // #define X(... -> C99 varargs
1271 // Warn if use of C99 feature in non-C99 mode.
1272 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1273
1274 // Lex the token after the identifier.
1275 LexUnexpandedToken(Tok);
1276 if (Tok.isNot(tok::r_paren)) {
1277 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1278 return true;
1279 }
1280 // Add the __VA_ARGS__ identifier as an argument.
1281 Arguments.push_back(Ident__VA_ARGS__);
1282 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001283 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001284 return false;
1285 case tok::eom: // #define X(
1286 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1287 return true;
1288 default:
1289 // Handle keywords and identifiers here to accept things like
1290 // #define Foo(for) for.
1291 IdentifierInfo *II = Tok.getIdentifierInfo();
1292 if (II == 0) {
1293 // #define X(1
1294 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1295 return true;
1296 }
1297
1298 // If this is already used as an argument, it is used multiple times (e.g.
1299 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001300 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001301 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001302 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001303 return true;
1304 }
Mike Stump11289f42009-09-09 15:08:12 +00001305
Chris Lattnerf64b3522008-03-09 01:54:53 +00001306 // Add the argument to the macro info.
1307 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001308
Chris Lattnerf64b3522008-03-09 01:54:53 +00001309 // Lex the token after the identifier.
1310 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001311
Chris Lattnerf64b3522008-03-09 01:54:53 +00001312 switch (Tok.getKind()) {
1313 default: // #define X(A B
1314 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1315 return true;
1316 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001317 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001318 return false;
1319 case tok::comma: // #define X(A,
1320 break;
1321 case tok::ellipsis: // #define X(A... -> GCC extension
1322 // Diagnose extension.
1323 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001324
Chris Lattnerf64b3522008-03-09 01:54:53 +00001325 // Lex the token after the identifier.
1326 LexUnexpandedToken(Tok);
1327 if (Tok.isNot(tok::r_paren)) {
1328 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1329 return true;
1330 }
Mike Stump11289f42009-09-09 15:08:12 +00001331
Chris Lattnerf64b3522008-03-09 01:54:53 +00001332 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001333 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001334 return false;
1335 }
1336 }
1337 }
1338}
1339
1340/// HandleDefineDirective - Implements #define. This consumes the entire macro
1341/// line then lets the caller lex the next real token.
1342void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1343 ++NumDefined;
1344
1345 Token MacroNameTok;
1346 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001347
Chris Lattnerf64b3522008-03-09 01:54:53 +00001348 // Error reading macro name? If so, diagnostic already issued.
1349 if (MacroNameTok.is(tok::eom))
1350 return;
1351
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001352 Token LastTok = MacroNameTok;
1353
Chris Lattnerf64b3522008-03-09 01:54:53 +00001354 // If we are supposed to keep comments in #defines, reenable comment saving
1355 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001356 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001357
Chris Lattnerf64b3522008-03-09 01:54:53 +00001358 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001359 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattnerf64b3522008-03-09 01:54:53 +00001361 Token Tok;
1362 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001363
Chris Lattnerf64b3522008-03-09 01:54:53 +00001364 // If this is a function-like macro definition, parse the argument list,
1365 // marking each of the identifiers as being used as macro arguments. Also,
1366 // check other constraints on the first token of the macro body.
1367 if (Tok.is(tok::eom)) {
1368 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001369 } else if (Tok.hasLeadingSpace()) {
1370 // This is a normal token with leading space. Clear the leading space
1371 // marker on the first token to get proper expansion.
1372 Tok.clearFlag(Token::LeadingSpace);
1373 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001374 // This is a function-like macro definition. Read the argument list.
1375 MI->setIsFunctionLike();
1376 if (ReadMacroDefinitionArgList(MI)) {
1377 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001378 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001379 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001380 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001381 DiscardUntilEndOfDirective();
1382 return;
1383 }
1384
Chris Lattner249c38b2009-04-19 18:26:34 +00001385 // If this is a definition of a variadic C99 function-like macro, not using
1386 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001387
Chris Lattner249c38b2009-04-19 18:26:34 +00001388 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1389 // This gets unpoisoned where it is allowed.
1390 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1391 if (MI->isC99Varargs())
1392 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001393
Chris Lattnerf64b3522008-03-09 01:54:53 +00001394 // Read the first token after the arg list for down below.
1395 LexUnexpandedToken(Tok);
Chris Lattner2425bcb2009-04-18 02:23:25 +00001396 } else if (Features.C99) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001397 // C99 requires whitespace between the macro definition and the body. Emit
1398 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001399 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001400 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001401 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1402 // first character of a replacement list is not a character required by
1403 // subclause 5.2.1, then there shall be white-space separation between the
1404 // identifier and the replacement list.". 5.2.1 lists this set:
1405 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1406 // is irrelevant here.
1407 bool isInvalid = false;
1408 if (Tok.is(tok::at)) // @ is not in the list above.
1409 isInvalid = true;
1410 else if (Tok.is(tok::unknown)) {
1411 // If we have an unknown token, it is something strange like "`". Since
1412 // all of valid characters would have lexed into a single character
1413 // token of some sort, we know this is not a valid case.
1414 isInvalid = true;
1415 }
1416 if (isInvalid)
1417 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1418 else
1419 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001420 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001421
1422 if (!Tok.is(tok::eom))
1423 LastTok = Tok;
1424
Chris Lattnerf64b3522008-03-09 01:54:53 +00001425 // Read the rest of the macro body.
1426 if (MI->isObjectLike()) {
1427 // Object-like macros are very simple, just read their body.
1428 while (Tok.isNot(tok::eom)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001429 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001430 MI->AddTokenToBody(Tok);
1431 // Get the next token of the macro.
1432 LexUnexpandedToken(Tok);
1433 }
Mike Stump11289f42009-09-09 15:08:12 +00001434
Chris Lattnerf64b3522008-03-09 01:54:53 +00001435 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001436 // Otherwise, read the body of a function-like macro. While we are at it,
1437 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1438 // parameters in function-like macro expansions.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001439 while (Tok.isNot(tok::eom)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001440 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001441
Chris Lattnerf64b3522008-03-09 01:54:53 +00001442 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001443 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001444
Chris Lattnerf64b3522008-03-09 01:54:53 +00001445 // Get the next token of the macro.
1446 LexUnexpandedToken(Tok);
1447 continue;
1448 }
Mike Stump11289f42009-09-09 15:08:12 +00001449
Chris Lattnerf64b3522008-03-09 01:54:53 +00001450 // Get the next token of the macro.
1451 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001452
Chris Lattner83bd8282009-05-25 17:16:10 +00001453 // Check for a valid macro arg identifier.
1454 if (Tok.getIdentifierInfo() == 0 ||
1455 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1456
1457 // If this is assembler-with-cpp mode, we accept random gibberish after
1458 // the '#' because '#' is often a comment character. However, change
1459 // the kind of the token to tok::unknown so that the preprocessor isn't
1460 // confused.
1461 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1462 LastTok.setKind(tok::unknown);
1463 } else {
1464 Diag(Tok, diag::err_pp_stringize_not_parameter);
1465 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001466
Chris Lattner83bd8282009-05-25 17:16:10 +00001467 // Disable __VA_ARGS__ again.
1468 Ident__VA_ARGS__->setIsPoisoned(true);
1469 return;
1470 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001471 }
Mike Stump11289f42009-09-09 15:08:12 +00001472
Chris Lattner83bd8282009-05-25 17:16:10 +00001473 // Things look ok, add the '#' and param name tokens to the macro.
1474 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001475 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001476 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001477
Chris Lattnerf64b3522008-03-09 01:54:53 +00001478 // Get the next token of the macro.
1479 LexUnexpandedToken(Tok);
1480 }
1481 }
Mike Stump11289f42009-09-09 15:08:12 +00001482
1483
Chris Lattnerf64b3522008-03-09 01:54:53 +00001484 // Disable __VA_ARGS__ again.
1485 Ident__VA_ARGS__->setIsPoisoned(true);
1486
1487 // Check that there is no paste (##) operator at the begining or end of the
1488 // replacement list.
1489 unsigned NumTokens = MI->getNumTokens();
1490 if (NumTokens != 0) {
1491 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1492 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001493 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001494 return;
1495 }
1496 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1497 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001498 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001499 return;
1500 }
1501 }
Mike Stump11289f42009-09-09 15:08:12 +00001502
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001503 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001504
Chris Lattnerf64b3522008-03-09 01:54:53 +00001505 // Finally, if this identifier already had a macro defined for it, verify that
1506 // the macro bodies are identical and free the old definition.
1507 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001508 // It is very common for system headers to have tons of macro redefinitions
1509 // and for warnings to be disabled in system headers. If this is the case,
1510 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001511 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001512 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1513 if (!OtherMI->isUsed())
1514 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001515
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001516 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001517 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001518 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001519 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001520 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1521 << MacroNameTok.getIdentifierInfo();
1522 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1523 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001524 }
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001525 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001526 }
Mike Stump11289f42009-09-09 15:08:12 +00001527
Chris Lattnerf64b3522008-03-09 01:54:53 +00001528 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001529
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001530 assert(!MI->isUsed());
1531 // If we need warning for not using the macro, add its location in the
1532 // warn-because-unused-macro set. If it gets used it will be removed from set.
1533 if (isInPrimaryFile() && // don't warn for include'd macros.
1534 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1535 MI->getDefinitionLoc()) != Diagnostic::Ignored) {
1536 MI->setIsWarnIfUnused(true);
1537 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1538 }
1539
Chris Lattner928e9092009-04-12 01:39:54 +00001540 // If the callbacks want to know, tell them about the macro definition.
1541 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001542 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001543}
1544
1545/// HandleUndefDirective - Implements #undef.
1546///
1547void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1548 ++NumUndefined;
1549
1550 Token MacroNameTok;
1551 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001552
Chris Lattnerf64b3522008-03-09 01:54:53 +00001553 // Error reading macro name? If so, diagnostic already issued.
1554 if (MacroNameTok.is(tok::eom))
1555 return;
Mike Stump11289f42009-09-09 15:08:12 +00001556
Chris Lattnerf64b3522008-03-09 01:54:53 +00001557 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001558 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001559
Chris Lattnerf64b3522008-03-09 01:54:53 +00001560 // Okay, we finally have a valid identifier to undef.
1561 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001562
Chris Lattnerf64b3522008-03-09 01:54:53 +00001563 // If the macro is not defined, this is a noop undef, just return.
1564 if (MI == 0) return;
1565
1566 if (!MI->isUsed())
1567 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001568
1569 // If the callbacks want to know, tell them about the macro #undef.
1570 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001571 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001572
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001573 if (MI->isWarnIfUnused())
1574 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1575
Chris Lattnerf64b3522008-03-09 01:54:53 +00001576 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001577 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001578 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1579}
1580
1581
1582//===----------------------------------------------------------------------===//
1583// Preprocessor Conditional Directive Handling.
1584//===----------------------------------------------------------------------===//
1585
1586/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1587/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1588/// if any tokens have been returned or pp-directives activated before this
1589/// #ifndef has been lexed.
1590///
1591void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1592 bool ReadAnyTokensBeforeDirective) {
1593 ++NumIf;
1594 Token DirectiveTok = Result;
1595
1596 Token MacroNameTok;
1597 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001598
Chris Lattnerf64b3522008-03-09 01:54:53 +00001599 // Error reading macro name? If so, diagnostic already issued.
1600 if (MacroNameTok.is(tok::eom)) {
1601 // Skip code until we get to #endif. This helps with recovery by not
1602 // emitting an error when the #endif is reached.
1603 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1604 /*Foundnonskip*/false, /*FoundElse*/false);
1605 return;
1606 }
Mike Stump11289f42009-09-09 15:08:12 +00001607
Chris Lattnerf64b3522008-03-09 01:54:53 +00001608 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001609 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001610
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001611 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1612 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001613
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001614 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001615 // If the start of a top-level #ifdef and if the macro is not defined,
1616 // inform MIOpt that this might be the start of a proper include guard.
1617 // Otherwise it is some other form of unknown conditional which we can't
1618 // handle.
1619 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001620 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001621 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001622 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001623 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001624 }
1625
Chris Lattnerf64b3522008-03-09 01:54:53 +00001626 // If there is a macro, process it.
1627 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001628 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001629
Chris Lattnerf64b3522008-03-09 01:54:53 +00001630 // Should we include the stuff contained by this directive?
1631 if (!MI == isIfndef) {
1632 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001633 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1634 /*wasskip*/false, /*foundnonskip*/true,
1635 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001636 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001637 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001638 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001639 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001640 /*FoundElse*/false);
1641 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001642
1643 if (Callbacks) {
1644 if (isIfndef)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001645 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001646 else
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001647 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001648 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001649}
1650
1651/// HandleIfDirective - Implements the #if directive.
1652///
1653void Preprocessor::HandleIfDirective(Token &IfToken,
1654 bool ReadAnyTokensBeforeDirective) {
1655 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001656
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001657 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001658 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001659 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1660 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1661 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001662
1663 // If this condition is equivalent to #ifndef X, and if this is the first
1664 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001665 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001666 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001667 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001668 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001669 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001670 }
1671
Chris Lattnerf64b3522008-03-09 01:54:53 +00001672 // Should we include the stuff contained by this directive?
1673 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001674 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001675 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001676 /*foundnonskip*/true, /*foundelse*/false);
1677 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001678 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00001679 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001680 /*FoundElse*/false);
1681 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001682
1683 if (Callbacks)
1684 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001685}
1686
1687/// HandleEndifDirective - Implements the #endif directive.
1688///
1689void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1690 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00001691
Chris Lattnerf64b3522008-03-09 01:54:53 +00001692 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001693 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00001694
Chris Lattnerf64b3522008-03-09 01:54:53 +00001695 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001696 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001697 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00001698 Diag(EndifToken, diag::err_pp_endif_without_if);
1699 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001700 }
Mike Stump11289f42009-09-09 15:08:12 +00001701
Chris Lattnerf64b3522008-03-09 01:54:53 +00001702 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001703 if (CurPPLexer->getConditionalStackDepth() == 0)
1704 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001705
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001706 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00001707 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001708
1709 if (Callbacks)
1710 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001711}
1712
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001713/// HandleElseDirective - Implements the #else directive.
1714///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001715void Preprocessor::HandleElseDirective(Token &Result) {
1716 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001717
Chris Lattnerf64b3522008-03-09 01:54:53 +00001718 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001719 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00001720
Chris Lattnerf64b3522008-03-09 01:54:53 +00001721 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001722 if (CurPPLexer->popConditionalLevel(CI)) {
1723 Diag(Result, diag::pp_err_else_without_if);
1724 return;
1725 }
Mike Stump11289f42009-09-09 15:08:12 +00001726
Chris Lattnerf64b3522008-03-09 01:54:53 +00001727 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001728 if (CurPPLexer->getConditionalStackDepth() == 0)
1729 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001730
1731 // If this is a #else with a #else before it, report the error.
1732 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00001733
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001734 // Finally, skip the rest of the contents of this block.
1735 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1736 /*FoundElse*/true);
1737
1738 if (Callbacks)
1739 Callbacks->Else();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001740}
1741
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001742/// HandleElifDirective - Implements the #elif directive.
1743///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001744void Preprocessor::HandleElifDirective(Token &ElifToken) {
1745 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001746
Chris Lattnerf64b3522008-03-09 01:54:53 +00001747 // #elif directive in a non-skipping conditional... start skipping.
1748 // We don't care what the condition is, because we will always skip it (since
1749 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001750 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001751 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001752 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001753
1754 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001755 if (CurPPLexer->popConditionalLevel(CI)) {
1756 Diag(ElifToken, diag::pp_err_elif_without_if);
1757 return;
1758 }
Mike Stump11289f42009-09-09 15:08:12 +00001759
Chris Lattnerf64b3522008-03-09 01:54:53 +00001760 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001761 if (CurPPLexer->getConditionalStackDepth() == 0)
1762 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001763
Chris Lattnerf64b3522008-03-09 01:54:53 +00001764 // If this is a #elif with a #else before it, report the error.
1765 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1766
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001767 // Finally, skip the rest of the contents of this block.
1768 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1769 /*FoundElse*/CI.FoundElse);
1770
1771 if (Callbacks)
1772 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001773}