blob: 5f4c321715d5ccbf2ffce01917af0d3b046c53cb [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,
Chandler Carruth540960f2011-01-03 17:40:17 +0000301 /*foundelse*/false);
302
303 if (Callbacks)
304 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000305 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000306 } else if (Directive[0] == 'e') {
307 llvm::StringRef Sub = Directive.substr(1);
308 if (Sub == "ndif") { // "endif"
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000309 CheckEndOfDirective("endif");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000310 PPConditionalInfo CondInfo;
311 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000312 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000313 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000315
Chris Lattnerf64b3522008-03-09 01:54:53 +0000316 // If we popped the outermost skipping block, we're done skipping!
317 if (!CondInfo.WasSkipping)
318 break;
Benjamin Kramer144884642009-12-31 13:32:38 +0000319 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000320 // #else directive in a skipping conditional. If not in some other
321 // skipping conditional, and if #else hasn't already been seen, enter it
322 // as a non-skipping conditional.
Chris Lattnerbc63de12009-04-18 01:34:22 +0000323 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000324 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattnerf64b3522008-03-09 01:54:53 +0000326 // If this is a #else with a #else before it, report the error.
327 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000328
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 // Note that we've seen a #else in this conditional.
330 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000331
Chandler Carruth540960f2011-01-03 17:40:17 +0000332 if (Callbacks)
333 Callbacks->Else();
334
Chris Lattnerf64b3522008-03-09 01:54:53 +0000335 // If the conditional is at the top level, and the #if block wasn't
336 // entered, enter the #else block now.
337 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
338 CondInfo.FoundNonSkip = true;
339 break;
340 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000341 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000342 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000343
344 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000345 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000346 // If this is in a skipping block or if we're already handled this #if
347 // block, don't bother parsing the condition.
348 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
349 DiscardUntilEndOfDirective();
350 ShouldEnter = false;
351 } else {
352 // Restore the value of LexingRawMode so that identifiers are
353 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000354 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
355 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000356 IdentifierInfo *IfNDefMacro = 0;
357 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000358 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000359 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000360 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000361
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 // If this is a #elif with a #else before it, report the error.
363 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000364
Chandler Carruth540960f2011-01-03 17:40:17 +0000365 if (Callbacks)
366 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
367
Chris Lattnerf64b3522008-03-09 01:54:53 +0000368 // If this condition is true, enter it!
369 if (ShouldEnter) {
370 CondInfo.FoundNonSkip = true;
371 break;
372 }
373 }
374 }
Mike Stump11289f42009-09-09 15:08:12 +0000375
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000376 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000377 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000378 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000379 }
380
381 // Finally, if we are out of the conditional (saw an #endif or ran off the end
382 // of the file, just stop skipping and return to lexing whatever came after
383 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000384 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385}
386
Ted Kremenek56572ab2008-12-12 18:34:08 +0000387void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000388
389 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000390 assert(CurPTHLexer);
391 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000392
Ted Kremenek56572ab2008-12-12 18:34:08 +0000393 // Skip to the next '#else', '#elif', or #endif.
394 if (CurPTHLexer->SkipBlock()) {
395 // We have reached an #endif. Both the '#' and 'endif' tokens
396 // have been consumed by the PTHLexer. Just pop off the condition level.
397 PPConditionalInfo CondInfo;
398 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000399 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000400 assert(!InCond && "Can't be skipping if not in a conditional!");
401 break;
402 }
Mike Stump11289f42009-09-09 15:08:12 +0000403
Ted Kremenek56572ab2008-12-12 18:34:08 +0000404 // We have reached a '#else' or '#elif'. Lex the next token to get
405 // the directive flavor.
406 Token Tok;
407 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000408
Ted Kremenek56572ab2008-12-12 18:34:08 +0000409 // We can actually look up the IdentifierInfo here since we aren't in
410 // raw mode.
411 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
412
413 if (K == tok::pp_else) {
414 // #else: Enter the else condition. We aren't in a nested condition
415 // since we skip those. We're always in the one matching the last
416 // blocked we skipped.
417 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
418 // Note that we've seen a #else in this conditional.
419 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000420
Ted Kremenek56572ab2008-12-12 18:34:08 +0000421 // If the #if block wasn't entered then enter the #else block now.
422 if (!CondInfo.FoundNonSkip) {
423 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000424
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000425 // Scan until the eom token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000426 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000427 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000428 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000429
Ted Kremenek56572ab2008-12-12 18:34:08 +0000430 break;
431 }
Mike Stump11289f42009-09-09 15:08:12 +0000432
Ted Kremenek56572ab2008-12-12 18:34:08 +0000433 // Otherwise skip this block.
434 continue;
435 }
Mike Stump11289f42009-09-09 15:08:12 +0000436
Ted Kremenek56572ab2008-12-12 18:34:08 +0000437 assert(K == tok::pp_elif);
438 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
439
440 // If this is a #elif with a #else before it, report the error.
441 if (CondInfo.FoundElse)
442 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000443
Ted Kremenek56572ab2008-12-12 18:34:08 +0000444 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000445 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000446 if (CondInfo.FoundNonSkip)
447 continue;
448
449 // Evaluate the condition of the #elif.
450 IdentifierInfo *IfNDefMacro = 0;
451 CurPTHLexer->ParsingPreprocessorDirective = true;
452 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
453 CurPTHLexer->ParsingPreprocessorDirective = false;
454
455 // If this condition is true, enter it!
456 if (ShouldEnter) {
457 CondInfo.FoundNonSkip = true;
458 break;
459 }
460
461 // Otherwise, skip this block and go to the next one.
462 continue;
463 }
464}
465
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000466/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
467/// return null on failure. isAngled indicates whether the file reference is
468/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000469const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000470 bool isAngled,
471 const DirectoryLookup *FromDir,
472 const DirectoryLookup *&CurDir) {
473 // If the header lookup mechanism may be relative to the current file, pass in
474 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000475 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000476 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000477 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000478 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000479
Chris Lattner022923a2009-02-04 19:45:07 +0000480 // If there is no file entry associated with this file, it must be the
481 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000482 // it won't be scanned for preprocessor directives. If we have the
483 // predefines buffer, resolve #include references (which come from the
484 // -include command line argument) as if they came from the main file, this
485 // affects file lookup etc.
486 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000487 FID = SourceMgr.getMainFileID();
488 CurFileEnt = SourceMgr.getFileEntryForID(FID);
489 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000492 // Do a standard file entry lookup.
493 CurDir = CurDirLookup;
494 const FileEntry *FE =
Douglas Gregor618e64a2010-08-08 07:49:23 +0000495 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerfde85352010-01-22 00:14:44 +0000496 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000497
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000498 // Otherwise, see if this is a subframework header. If so, this is relative
499 // to one of the headers on the #include stack. Walk the list of the current
500 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000501 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000502 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000503 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000504 return FE;
505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000507 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
508 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000509 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000510 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000511 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000512 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000513 return FE;
514 }
515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000517 // Otherwise, we really couldn't find the file.
518 return 0;
519}
520
Chris Lattnerf64b3522008-03-09 01:54:53 +0000521
522//===----------------------------------------------------------------------===//
523// Preprocessor Directive Handling.
524//===----------------------------------------------------------------------===//
525
526/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000527/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000528/// lexer/preprocessor state, and advances the lexer(s) so that the next token
529/// read is the correct one.
530void Preprocessor::HandleDirective(Token &Result) {
531 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000532
Chris Lattnerf64b3522008-03-09 01:54:53 +0000533 // We just parsed a # character at the start of a line, so we're in directive
534 // mode. Tell the lexer this so any newlines we see will be converted into an
535 // EOM token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000536 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000537
Chris Lattnerf64b3522008-03-09 01:54:53 +0000538 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000539
Chris Lattnerf64b3522008-03-09 01:54:53 +0000540 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000541 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000542 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000543 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000544
Chris Lattner2d17ab72009-03-18 21:00:25 +0000545 // Save the '#' token in case we need to return it later.
546 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000547
Chris Lattnerf64b3522008-03-09 01:54:53 +0000548 // Read the next token, the directive flavor. This isn't expanded due to
549 // C99 6.10.3p8.
550 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000551
Chris Lattnerf64b3522008-03-09 01:54:53 +0000552 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
553 // #define A(x) #x
554 // A(abc
555 // #warning blah
556 // def)
557 // If so, the user is relying on non-portable behavior, emit a diagnostic.
558 if (InMacroArgs)
559 Diag(Result, diag::ext_embedded_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000560
Chris Lattnerf64b3522008-03-09 01:54:53 +0000561TryAgain:
562 switch (Result.getKind()) {
563 case tok::eom:
564 return; // null directive.
565 case tok::comment:
566 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
567 LexUnexpandedToken(Result);
568 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000569 case tok::code_completion:
570 if (CodeComplete)
571 CodeComplete->CodeCompleteDirective(
572 CurPPLexer->getConditionalStackDepth() > 0);
573 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000574 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000575 if (getLangOptions().AsmPreprocessor)
576 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000577 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000578 default:
579 IdentifierInfo *II = Result.getIdentifierInfo();
580 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000581
Chris Lattnerf64b3522008-03-09 01:54:53 +0000582 // Ask what the preprocessor keyword ID is.
583 switch (II->getPPKeywordID()) {
584 default: break;
585 // C99 6.10.1 - Conditional Inclusion.
586 case tok::pp_if:
587 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
588 case tok::pp_ifdef:
589 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
590 case tok::pp_ifndef:
591 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
592 case tok::pp_elif:
593 return HandleElifDirective(Result);
594 case tok::pp_else:
595 return HandleElseDirective(Result);
596 case tok::pp_endif:
597 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000598
Chris Lattnerf64b3522008-03-09 01:54:53 +0000599 // C99 6.10.2 - Source File Inclusion.
600 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000601 // Handle #include.
602 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000603 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000604 // Handle -imacros.
605 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000606
Chris Lattnerf64b3522008-03-09 01:54:53 +0000607 // C99 6.10.3 - Macro Replacement.
608 case tok::pp_define:
609 return HandleDefineDirective(Result);
610 case tok::pp_undef:
611 return HandleUndefDirective(Result);
612
613 // C99 6.10.4 - Line Control.
614 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000615 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000616
Chris Lattnerf64b3522008-03-09 01:54:53 +0000617 // C99 6.10.5 - Error Directive.
618 case tok::pp_error:
619 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000620
Chris Lattnerf64b3522008-03-09 01:54:53 +0000621 // C99 6.10.6 - Pragma Directive.
622 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000623 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000624
Chris Lattnerf64b3522008-03-09 01:54:53 +0000625 // GNU Extensions.
626 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000627 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000628 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000629 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattnerf64b3522008-03-09 01:54:53 +0000631 case tok::pp_warning:
632 Diag(Result, diag::ext_pp_warning_directive);
633 return HandleUserDiagnosticDirective(Result, true);
634 case tok::pp_ident:
635 return HandleIdentSCCSDirective(Result);
636 case tok::pp_sccs:
637 return HandleIdentSCCSDirective(Result);
638 case tok::pp_assert:
639 //isExtension = true; // FIXME: implement #assert
640 break;
641 case tok::pp_unassert:
642 //isExtension = true; // FIXME: implement #unassert
643 break;
644 }
645 break;
646 }
Mike Stump11289f42009-09-09 15:08:12 +0000647
Chris Lattner2d17ab72009-03-18 21:00:25 +0000648 // If this is a .S file, treat unknown # directives as non-preprocessor
649 // directives. This is important because # may be a comment or introduce
650 // various pseudo-ops. Just return the # token and push back the following
651 // token to be lexed next time.
652 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000653 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000654 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000655 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000656 Toks[1] = Result;
657 // Enter this token stream so that we re-lex the tokens. Make sure to
658 // enable macro expansion, in case the token after the # is an identifier
659 // that is expanded.
660 EnterTokenStream(Toks, 2, false, true);
661 return;
662 }
Mike Stump11289f42009-09-09 15:08:12 +0000663
Chris Lattnerf64b3522008-03-09 01:54:53 +0000664 // If we reached here, the preprocessing token is not valid!
665 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattnerf64b3522008-03-09 01:54:53 +0000667 // Read the rest of the PP line.
668 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000669
Chris Lattnerf64b3522008-03-09 01:54:53 +0000670 // Okay, we're done parsing the directive.
671}
672
Chris Lattner76e68962009-01-26 06:19:46 +0000673/// GetLineValue - Convert a numeric token into an unsigned value, emitting
674/// Diagnostic DiagID if it is invalid, and returning the value in Val.
675static bool GetLineValue(Token &DigitTok, unsigned &Val,
676 unsigned DiagID, Preprocessor &PP) {
677 if (DigitTok.isNot(tok::numeric_constant)) {
678 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000679
Chris Lattner76e68962009-01-26 06:19:46 +0000680 if (DigitTok.isNot(tok::eom))
681 PP.DiscardUntilEndOfDirective();
682 return true;
683 }
Mike Stump11289f42009-09-09 15:08:12 +0000684
Chris Lattner76e68962009-01-26 06:19:46 +0000685 llvm::SmallString<64> IntegerBuffer;
686 IntegerBuffer.resize(DigitTok.getLength());
687 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000688 bool Invalid = false;
689 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
690 if (Invalid)
691 return true;
692
Chris Lattnerd66f1722009-04-18 18:35:15 +0000693 // Verify that we have a simple digit-sequence, and compute the value. This
694 // is always a simple digit string computed in decimal, so we do this manually
695 // here.
696 Val = 0;
697 for (unsigned i = 0; i != ActualLength; ++i) {
698 if (!isdigit(DigitTokBegin[i])) {
699 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
700 diag::err_pp_line_digit_sequence);
701 PP.DiscardUntilEndOfDirective();
702 return true;
703 }
Mike Stump11289f42009-09-09 15:08:12 +0000704
Chris Lattnerd66f1722009-04-18 18:35:15 +0000705 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
706 if (NextVal < Val) { // overflow.
707 PP.Diag(DigitTok, DiagID);
708 PP.DiscardUntilEndOfDirective();
709 return true;
710 }
711 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000712 }
Mike Stump11289f42009-09-09 15:08:12 +0000713
714 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000715 if (Val == 0) {
716 PP.Diag(DigitTok, DiagID);
717 PP.DiscardUntilEndOfDirective();
718 return true;
719 }
Mike Stump11289f42009-09-09 15:08:12 +0000720
Chris Lattnerd66f1722009-04-18 18:35:15 +0000721 if (DigitTokBegin[0] == '0')
722 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000723
Chris Lattner76e68962009-01-26 06:19:46 +0000724 return false;
725}
726
Mike Stump11289f42009-09-09 15:08:12 +0000727/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner100c65e2009-01-26 05:29:08 +0000728/// acceptable forms are:
729/// # line digit-sequence
730/// # line digit-sequence "s-char-sequence"
731void Preprocessor::HandleLineDirective(Token &Tok) {
732 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
733 // expanded.
734 Token DigitTok;
735 Lex(DigitTok);
736
Chris Lattner100c65e2009-01-26 05:29:08 +0000737 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000738 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000739 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000740 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000741
Chris Lattner76e68962009-01-26 06:19:46 +0000742 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
743 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner100c65e2009-01-26 05:29:08 +0000744 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
745 if (LineNo >= LineLimit)
746 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump11289f42009-09-09 15:08:12 +0000747
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000748 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000749 Token StrTok;
750 Lex(StrTok);
751
752 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
753 // string followed by eom.
Mike Stump11289f42009-09-09 15:08:12 +0000754 if (StrTok.is(tok::eom))
Chris Lattner100c65e2009-01-26 05:29:08 +0000755 ; // ok
756 else if (StrTok.isNot(tok::string_literal)) {
757 Diag(StrTok, diag::err_pp_line_invalid_filename);
758 DiscardUntilEndOfDirective();
759 return;
760 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000761 // Parse and validate the string, converting it into a unique ID.
762 StringLiteralParser Literal(&StrTok, 1, *this);
763 assert(!Literal.AnyWide && "Didn't allow wide strings in");
764 if (Literal.hadError)
765 return DiscardUntilEndOfDirective();
766 if (Literal.Pascal) {
767 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
768 return DiscardUntilEndOfDirective();
769 }
770 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
771 Literal.GetStringLength());
Mike Stump11289f42009-09-09 15:08:12 +0000772
Chris Lattner0003c272009-04-17 23:30:53 +0000773 // Verify that there is nothing after the string, other than EOM. Because
774 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
775 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000776 }
Mike Stump11289f42009-09-09 15:08:12 +0000777
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000778 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000779
Chris Lattner839150e2009-03-27 17:13:49 +0000780 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000781 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
782 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000783 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000784}
785
Chris Lattner76e68962009-01-26 06:19:46 +0000786/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
787/// marker directive.
788static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
789 bool &IsSystemHeader, bool &IsExternCHeader,
790 Preprocessor &PP) {
791 unsigned FlagVal;
792 Token FlagTok;
793 PP.Lex(FlagTok);
794 if (FlagTok.is(tok::eom)) return false;
795 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
796 return true;
797
798 if (FlagVal == 1) {
799 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000800
Chris Lattner76e68962009-01-26 06:19:46 +0000801 PP.Lex(FlagTok);
802 if (FlagTok.is(tok::eom)) return false;
803 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
804 return true;
805 } else if (FlagVal == 2) {
806 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000807
Chris Lattner1c967782009-02-04 06:25:26 +0000808 SourceManager &SM = PP.getSourceManager();
809 // If we are leaving the current presumed file, check to make sure the
810 // presumed include stack isn't empty!
811 FileID CurFileID =
812 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
813 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000814 if (PLoc.isInvalid())
815 return true;
816
Chris Lattner1c967782009-02-04 06:25:26 +0000817 // If there is no include loc (main file) or if the include loc is in a
818 // different physical file, then we aren't in a "1" line marker flag region.
819 SourceLocation IncLoc = PLoc.getIncludeLoc();
820 if (IncLoc.isInvalid() ||
821 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
822 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
823 PP.DiscardUntilEndOfDirective();
824 return true;
825 }
Mike Stump11289f42009-09-09 15:08:12 +0000826
Chris Lattner76e68962009-01-26 06:19:46 +0000827 PP.Lex(FlagTok);
828 if (FlagTok.is(tok::eom)) return false;
829 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
830 return true;
831 }
832
833 // We must have 3 if there are still flags.
834 if (FlagVal != 3) {
835 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000836 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000837 return true;
838 }
Mike Stump11289f42009-09-09 15:08:12 +0000839
Chris Lattner76e68962009-01-26 06:19:46 +0000840 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000841
Chris Lattner76e68962009-01-26 06:19:46 +0000842 PP.Lex(FlagTok);
843 if (FlagTok.is(tok::eom)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000844 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000845 return true;
846
847 // We must have 4 if there is yet another flag.
848 if (FlagVal != 4) {
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 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Chris Lattner76e68962009-01-26 06:19:46 +0000854 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000855
Chris Lattner76e68962009-01-26 06:19:46 +0000856 PP.Lex(FlagTok);
857 if (FlagTok.is(tok::eom)) return false;
858
859 // There are no more valid flags here.
860 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000861 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000862 return true;
863}
864
865/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
866/// one of the following forms:
867///
868/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000869/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000870/// # 42 "file" ('1' | '2')? '3' '4'?
871///
872void Preprocessor::HandleDigitDirective(Token &DigitTok) {
873 // Validate the number and convert it to an unsigned. GNU does not have a
874 // line # limit other than it fit in 32-bits.
875 unsigned LineNo;
876 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
877 *this))
878 return;
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattner76e68962009-01-26 06:19:46 +0000880 Token StrTok;
881 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000882
Chris Lattner76e68962009-01-26 06:19:46 +0000883 bool IsFileEntry = false, IsFileExit = false;
884 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000885 int FilenameID = -1;
886
Chris Lattner76e68962009-01-26 06:19:46 +0000887 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
888 // string followed by eom.
Mike Stump11289f42009-09-09 15:08:12 +0000889 if (StrTok.is(tok::eom))
Chris Lattner76e68962009-01-26 06:19:46 +0000890 ; // ok
891 else if (StrTok.isNot(tok::string_literal)) {
892 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000893 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000894 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000895 // Parse and validate the string, converting it into a unique ID.
896 StringLiteralParser Literal(&StrTok, 1, *this);
897 assert(!Literal.AnyWide && "Didn't allow wide strings in");
898 if (Literal.hadError)
899 return DiscardUntilEndOfDirective();
900 if (Literal.Pascal) {
901 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
902 return DiscardUntilEndOfDirective();
903 }
904 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
905 Literal.GetStringLength());
Mike Stump11289f42009-09-09 15:08:12 +0000906
Chris Lattner76e68962009-01-26 06:19:46 +0000907 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +0000908 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000909 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +0000910 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000911 }
Mike Stump11289f42009-09-09 15:08:12 +0000912
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000913 // Create a line note with this information.
914 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +0000915 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000916 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +0000917
Chris Lattner839150e2009-03-27 17:13:49 +0000918 // If the preprocessor has callbacks installed, notify them of the #line
919 // change. This is used so that the line marker comes out in -E mode for
920 // example.
921 if (Callbacks) {
922 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
923 if (IsFileEntry)
924 Reason = PPCallbacks::EnterFile;
925 else if (IsFileExit)
926 Reason = PPCallbacks::ExitFile;
927 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
928 if (IsExternCHeader)
929 FileKind = SrcMgr::C_ExternCSystem;
930 else if (IsSystemHeader)
931 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +0000932
Chris Lattnerc745cec2010-04-14 04:28:50 +0000933 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +0000934 }
Chris Lattner76e68962009-01-26 06:19:46 +0000935}
936
937
Chris Lattner38d7fd22009-01-26 05:30:54 +0000938/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
939///
Mike Stump11289f42009-09-09 15:08:12 +0000940void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000941 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +0000942 // PTH doesn't emit #warning or #error directives.
943 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +0000944 return CurPTHLexer->DiscardToEndOfLine();
945
Chris Lattnerf64b3522008-03-09 01:54:53 +0000946 // Read the rest of the line raw. We do this because we don't want macros
947 // to be expanded and we don't require that the tokens be valid preprocessing
948 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
949 // collapse multiple consequtive white space between tokens, but this isn't
950 // specified by the standard.
Chris Lattner100c65e2009-01-26 05:29:08 +0000951 std::string Message = CurLexer->ReadToEndOfLine();
952 if (isWarning)
953 Diag(Tok, diag::pp_hash_warning) << Message;
954 else
955 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000956}
957
958/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
959///
960void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
961 // Yes, this directive is an extension.
962 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000963
Chris Lattnerf64b3522008-03-09 01:54:53 +0000964 // Read the string argument.
965 Token StrTok;
966 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Chris Lattnerf64b3522008-03-09 01:54:53 +0000968 // If the token kind isn't a string, it's a malformed directive.
969 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +0000970 StrTok.isNot(tok::wide_string_literal)) {
971 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner38d7fd22009-01-26 05:30:54 +0000972 if (StrTok.isNot(tok::eom))
973 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000974 return;
975 }
Mike Stump11289f42009-09-09 15:08:12 +0000976
Chris Lattnerf64b3522008-03-09 01:54:53 +0000977 // Verify that there is nothing after the string, other than EOM.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000978 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000979
Douglas Gregordc970f02010-03-16 22:30:13 +0000980 if (Callbacks) {
981 bool Invalid = false;
982 std::string Str = getSpelling(StrTok, &Invalid);
983 if (!Invalid)
984 Callbacks->Ident(Tok.getLocation(), Str);
985 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000986}
987
988//===----------------------------------------------------------------------===//
989// Preprocessor Include Directive Handling.
990//===----------------------------------------------------------------------===//
991
992/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
993/// checked and spelled filename, e.g. as an operand of #include. This returns
994/// true if the input filename was in <>'s or false if it were in ""'s. The
995/// caller is expected to provide a buffer that is large enough to hold the
996/// spelling of the filename, but is also expected to handle the case when
997/// this method decides to use a different buffer.
998bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000999 llvm::StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001000 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001001 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001002
Chris Lattnerf64b3522008-03-09 01:54:53 +00001003 // Make sure the filename is <x> or "x".
1004 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001005 if (Buffer[0] == '<') {
1006 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001007 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001008 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001009 return true;
1010 }
1011 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001012 } else if (Buffer[0] == '"') {
1013 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001014 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001015 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001016 return true;
1017 }
1018 isAngled = false;
1019 } else {
1020 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001021 Buffer = llvm::StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001022 return true;
1023 }
Mike Stump11289f42009-09-09 15:08:12 +00001024
Chris Lattnerf64b3522008-03-09 01:54:53 +00001025 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001026 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001027 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001028 Buffer = llvm::StringRef();
1029 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001030 }
Mike Stump11289f42009-09-09 15:08:12 +00001031
Chris Lattnerf64b3522008-03-09 01:54:53 +00001032 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001033 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001034 return isAngled;
1035}
1036
1037/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1038/// from a macro as multiple tokens, which need to be glued together. This
1039/// occurs for code like:
1040/// #define FOO <a/b.h>
1041/// #include FOO
1042/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1043///
1044/// This code concatenates and consumes tokens up to the '>' token. It returns
1045/// false if the > was found, otherwise it returns true if it finds and consumes
1046/// the EOM marker.
John Thompsonb5353522009-10-30 13:49:06 +00001047bool Preprocessor::ConcatenateIncludeName(
Douglas Gregor796d76a2010-10-20 22:00:55 +00001048 llvm::SmallString<128> &FilenameBuffer,
1049 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001050 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001051
John Thompsonb5353522009-10-30 13:49:06 +00001052 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001053 while (CurTok.isNot(tok::eom)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001054 End = CurTok.getLocation();
1055
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001056 // FIXME: Provide code completion for #includes.
1057 if (CurTok.is(tok::code_completion)) {
1058 Lex(CurTok);
1059 continue;
1060 }
1061
Chris Lattnerf64b3522008-03-09 01:54:53 +00001062 // Append the spelling of this token to the buffer. If there was a space
1063 // before it, add it now.
1064 if (CurTok.hasLeadingSpace())
1065 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001066
Chris Lattnerf64b3522008-03-09 01:54:53 +00001067 // Get the spelling of the token, directly into FilenameBuffer if possible.
1068 unsigned PreAppendSize = FilenameBuffer.size();
1069 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chris Lattnerf64b3522008-03-09 01:54:53 +00001071 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001072 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001073
Chris Lattnerf64b3522008-03-09 01:54:53 +00001074 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1075 if (BufPtr != &FilenameBuffer[PreAppendSize])
1076 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001077
Chris Lattnerf64b3522008-03-09 01:54:53 +00001078 // Resize FilenameBuffer to the correct size.
1079 if (CurTok.getLength() != ActualLen)
1080 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001081
Chris Lattnerf64b3522008-03-09 01:54:53 +00001082 // If we found the '>' marker, return success.
1083 if (CurTok.is(tok::greater))
1084 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001085
John Thompsonb5353522009-10-30 13:49:06 +00001086 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001087 }
1088
1089 // If we hit the eom marker, emit an error and return true so that the caller
1090 // knows the EOM has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001091 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001092 return true;
1093}
1094
1095/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1096/// file to be included from the lexer, then include it! This is a common
1097/// routine with functionality shared between #include, #include_next and
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001098/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001099/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001100void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1101 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001102 const DirectoryLookup *LookupFrom,
1103 bool isImport) {
1104
1105 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001106 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001107
Chris Lattnerf64b3522008-03-09 01:54:53 +00001108 // Reserve a buffer to get the spelling.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001109 llvm::SmallString<128> FilenameBuffer;
1110 llvm::StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001111 SourceLocation End;
1112
Chris Lattnerf64b3522008-03-09 01:54:53 +00001113 switch (FilenameTok.getKind()) {
1114 case tok::eom:
1115 // If the token kind is EOM, the error has already been diagnosed.
1116 return;
Mike Stump11289f42009-09-09 15:08:12 +00001117
Chris Lattnerf64b3522008-03-09 01:54:53 +00001118 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001119 case tok::string_literal:
1120 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001121 End = FilenameTok.getLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001122 break;
Mike Stump11289f42009-09-09 15:08:12 +00001123
Chris Lattnerf64b3522008-03-09 01:54:53 +00001124 case tok::less:
1125 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1126 // case, glue the tokens together into FilenameBuffer and interpret those.
1127 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001128 if (ConcatenateIncludeName(FilenameBuffer, End))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001129 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001130 Filename = FilenameBuffer.str();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001131 break;
1132 default:
1133 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1134 DiscardUntilEndOfDirective();
1135 return;
1136 }
Mike Stump11289f42009-09-09 15:08:12 +00001137
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001138 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001139 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001140 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1141 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001142 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001143 DiscardUntilEndOfDirective();
1144 return;
1145 }
Mike Stump11289f42009-09-09 15:08:12 +00001146
Chris Lattnerb40289b2009-04-17 23:56:52 +00001147 // Verify that there is nothing after the filename, other than EOM. Note that
1148 // we allow macros that expand to nothing after the filename, because this
1149 // falls into the category of "#include pp-tokens new-line" specified in
1150 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001151 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001152
1153 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001154 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1155 Diag(FilenameTok, diag::err_pp_include_too_deep);
1156 return;
1157 }
Mike Stump11289f42009-09-09 15:08:12 +00001158
Chris Lattnerf64b3522008-03-09 01:54:53 +00001159 // Search include directories.
1160 const DirectoryLookup *CurDir;
Chris Lattnerfde85352010-01-22 00:14:44 +00001161 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner907dfe92008-11-18 07:59:24 +00001162 if (File == 0) {
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001163 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner907dfe92008-11-18 07:59:24 +00001164 return;
1165 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001166
Douglas Gregor796d76a2010-10-20 22:00:55 +00001167 // Notify the callback object that we've seen an inclusion directive.
1168 if (Callbacks)
1169 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1170 End);
1171
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001172 // The #included file will be considered to be a system header if either it is
1173 // in a system include directory, or if the #includer is a system include
1174 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001175 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001176 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001177 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001178
Chris Lattner72286d62010-04-19 20:44:31 +00001179 // Ask HeaderInfo if we should enter this #include file. If not, #including
1180 // this file will have no effect.
1181 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001182 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001183 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001184 return;
1185 }
1186
Chris Lattnerf64b3522008-03-09 01:54:53 +00001187 // Look up the file, create a File ID for it.
Chris Lattnerd32480d2009-01-17 06:22:33 +00001188 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1189 FileCharacter);
1190 if (FID.isInvalid()) {
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001191 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +00001192 return;
1193 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001194
1195 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001196 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001197}
1198
1199/// HandleIncludeNextDirective - Implements #include_next.
1200///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001201void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1202 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001203 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001204
Chris Lattnerf64b3522008-03-09 01:54:53 +00001205 // #include_next is like #include, except that we start searching after
1206 // the current found directory. If we can't do this, issue a
1207 // diagnostic.
1208 const DirectoryLookup *Lookup = CurDirLookup;
1209 if (isInPrimaryFile()) {
1210 Lookup = 0;
1211 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1212 } else if (Lookup == 0) {
1213 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1214 } else {
1215 // Start looking up in the next directory.
1216 ++Lookup;
1217 }
Mike Stump11289f42009-09-09 15:08:12 +00001218
Douglas Gregor796d76a2010-10-20 22:00:55 +00001219 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001220}
1221
1222/// HandleImportDirective - Implements #import.
1223///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001224void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1225 Token &ImportTok) {
Chris Lattnerd4a96732009-03-06 04:28:03 +00001226 if (!Features.ObjC1) // #import is standard for ObjC.
1227 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001228
Douglas Gregor796d76a2010-10-20 22:00:55 +00001229 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001230}
1231
Chris Lattner58a1eb02009-04-08 18:46:40 +00001232/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1233/// pseudo directive in the predefines buffer. This handles it by sucking all
1234/// tokens through the preprocessor and discarding them (only keeping the side
1235/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001236void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1237 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001238 // This directive should only occur in the predefines buffer. If not, emit an
1239 // error and reject it.
1240 SourceLocation Loc = IncludeMacrosTok.getLocation();
1241 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1242 Diag(IncludeMacrosTok.getLocation(),
1243 diag::pp_include_macros_out_of_predefines);
1244 DiscardUntilEndOfDirective();
1245 return;
1246 }
Mike Stump11289f42009-09-09 15:08:12 +00001247
Chris Lattnere01d82b2009-04-08 20:53:24 +00001248 // Treat this as a normal #include for checking purposes. If this is
1249 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001250 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001251
Chris Lattnere01d82b2009-04-08 20:53:24 +00001252 Token TmpTok;
1253 do {
1254 Lex(TmpTok);
1255 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1256 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001257}
1258
Chris Lattnerf64b3522008-03-09 01:54:53 +00001259//===----------------------------------------------------------------------===//
1260// Preprocessor Macro Directive Handling.
1261//===----------------------------------------------------------------------===//
1262
1263/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1264/// definition has just been read. Lex the rest of the arguments and the
1265/// closing ), updating MI with what we learn. Return true if an error occurs
1266/// parsing the arg list.
1267bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1268 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001269
Chris Lattnerf64b3522008-03-09 01:54:53 +00001270 Token Tok;
1271 while (1) {
1272 LexUnexpandedToken(Tok);
1273 switch (Tok.getKind()) {
1274 case tok::r_paren:
1275 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001276 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001277 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001278 // Otherwise we have #define FOO(A,)
1279 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1280 return true;
1281 case tok::ellipsis: // #define X(... -> C99 varargs
1282 // Warn if use of C99 feature in non-C99 mode.
1283 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1284
1285 // Lex the token after the identifier.
1286 LexUnexpandedToken(Tok);
1287 if (Tok.isNot(tok::r_paren)) {
1288 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1289 return true;
1290 }
1291 // Add the __VA_ARGS__ identifier as an argument.
1292 Arguments.push_back(Ident__VA_ARGS__);
1293 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001294 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001295 return false;
1296 case tok::eom: // #define X(
1297 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1298 return true;
1299 default:
1300 // Handle keywords and identifiers here to accept things like
1301 // #define Foo(for) for.
1302 IdentifierInfo *II = Tok.getIdentifierInfo();
1303 if (II == 0) {
1304 // #define X(1
1305 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1306 return true;
1307 }
1308
1309 // If this is already used as an argument, it is used multiple times (e.g.
1310 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001311 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001312 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001313 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001314 return true;
1315 }
Mike Stump11289f42009-09-09 15:08:12 +00001316
Chris Lattnerf64b3522008-03-09 01:54:53 +00001317 // Add the argument to the macro info.
1318 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001319
Chris Lattnerf64b3522008-03-09 01:54:53 +00001320 // Lex the token after the identifier.
1321 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattnerf64b3522008-03-09 01:54:53 +00001323 switch (Tok.getKind()) {
1324 default: // #define X(A B
1325 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1326 return true;
1327 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001328 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001329 return false;
1330 case tok::comma: // #define X(A,
1331 break;
1332 case tok::ellipsis: // #define X(A... -> GCC extension
1333 // Diagnose extension.
1334 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001335
Chris Lattnerf64b3522008-03-09 01:54:53 +00001336 // Lex the token after the identifier.
1337 LexUnexpandedToken(Tok);
1338 if (Tok.isNot(tok::r_paren)) {
1339 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1340 return true;
1341 }
Mike Stump11289f42009-09-09 15:08:12 +00001342
Chris Lattnerf64b3522008-03-09 01:54:53 +00001343 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001344 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001345 return false;
1346 }
1347 }
1348 }
1349}
1350
1351/// HandleDefineDirective - Implements #define. This consumes the entire macro
1352/// line then lets the caller lex the next real token.
1353void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1354 ++NumDefined;
1355
1356 Token MacroNameTok;
1357 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001358
Chris Lattnerf64b3522008-03-09 01:54:53 +00001359 // Error reading macro name? If so, diagnostic already issued.
1360 if (MacroNameTok.is(tok::eom))
1361 return;
1362
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001363 Token LastTok = MacroNameTok;
1364
Chris Lattnerf64b3522008-03-09 01:54:53 +00001365 // If we are supposed to keep comments in #defines, reenable comment saving
1366 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001367 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattnerf64b3522008-03-09 01:54:53 +00001369 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001370 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001371
Chris Lattnerf64b3522008-03-09 01:54:53 +00001372 Token Tok;
1373 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001374
Chris Lattnerf64b3522008-03-09 01:54:53 +00001375 // If this is a function-like macro definition, parse the argument list,
1376 // marking each of the identifiers as being used as macro arguments. Also,
1377 // check other constraints on the first token of the macro body.
1378 if (Tok.is(tok::eom)) {
1379 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001380 } else if (Tok.hasLeadingSpace()) {
1381 // This is a normal token with leading space. Clear the leading space
1382 // marker on the first token to get proper expansion.
1383 Tok.clearFlag(Token::LeadingSpace);
1384 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001385 // This is a function-like macro definition. Read the argument list.
1386 MI->setIsFunctionLike();
1387 if (ReadMacroDefinitionArgList(MI)) {
1388 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001389 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001390 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001391 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001392 DiscardUntilEndOfDirective();
1393 return;
1394 }
1395
Chris Lattner249c38b2009-04-19 18:26:34 +00001396 // If this is a definition of a variadic C99 function-like macro, not using
1397 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001398
Chris Lattner249c38b2009-04-19 18:26:34 +00001399 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1400 // This gets unpoisoned where it is allowed.
1401 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1402 if (MI->isC99Varargs())
1403 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001404
Chris Lattnerf64b3522008-03-09 01:54:53 +00001405 // Read the first token after the arg list for down below.
1406 LexUnexpandedToken(Tok);
Chris Lattner2425bcb2009-04-18 02:23:25 +00001407 } else if (Features.C99) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001408 // C99 requires whitespace between the macro definition and the body. Emit
1409 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001410 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001411 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001412 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1413 // first character of a replacement list is not a character required by
1414 // subclause 5.2.1, then there shall be white-space separation between the
1415 // identifier and the replacement list.". 5.2.1 lists this set:
1416 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1417 // is irrelevant here.
1418 bool isInvalid = false;
1419 if (Tok.is(tok::at)) // @ is not in the list above.
1420 isInvalid = true;
1421 else if (Tok.is(tok::unknown)) {
1422 // If we have an unknown token, it is something strange like "`". Since
1423 // all of valid characters would have lexed into a single character
1424 // token of some sort, we know this is not a valid case.
1425 isInvalid = true;
1426 }
1427 if (isInvalid)
1428 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1429 else
1430 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001431 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001432
1433 if (!Tok.is(tok::eom))
1434 LastTok = Tok;
1435
Chris Lattnerf64b3522008-03-09 01:54:53 +00001436 // Read the rest of the macro body.
1437 if (MI->isObjectLike()) {
1438 // Object-like macros are very simple, just read their body.
1439 while (Tok.isNot(tok::eom)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001440 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001441 MI->AddTokenToBody(Tok);
1442 // Get the next token of the macro.
1443 LexUnexpandedToken(Tok);
1444 }
Mike Stump11289f42009-09-09 15:08:12 +00001445
Chris Lattnerf64b3522008-03-09 01:54:53 +00001446 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001447 // Otherwise, read the body of a function-like macro. While we are at it,
1448 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1449 // parameters in function-like macro expansions.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001450 while (Tok.isNot(tok::eom)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001451 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001452
Chris Lattnerf64b3522008-03-09 01:54:53 +00001453 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001454 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001455
Chris Lattnerf64b3522008-03-09 01:54:53 +00001456 // Get the next token of the macro.
1457 LexUnexpandedToken(Tok);
1458 continue;
1459 }
Mike Stump11289f42009-09-09 15:08:12 +00001460
Chris Lattnerf64b3522008-03-09 01:54:53 +00001461 // Get the next token of the macro.
1462 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001463
Chris Lattner83bd8282009-05-25 17:16:10 +00001464 // Check for a valid macro arg identifier.
1465 if (Tok.getIdentifierInfo() == 0 ||
1466 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1467
1468 // If this is assembler-with-cpp mode, we accept random gibberish after
1469 // the '#' because '#' is often a comment character. However, change
1470 // the kind of the token to tok::unknown so that the preprocessor isn't
1471 // confused.
1472 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1473 LastTok.setKind(tok::unknown);
1474 } else {
1475 Diag(Tok, diag::err_pp_stringize_not_parameter);
1476 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001477
Chris Lattner83bd8282009-05-25 17:16:10 +00001478 // Disable __VA_ARGS__ again.
1479 Ident__VA_ARGS__->setIsPoisoned(true);
1480 return;
1481 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001482 }
Mike Stump11289f42009-09-09 15:08:12 +00001483
Chris Lattner83bd8282009-05-25 17:16:10 +00001484 // Things look ok, add the '#' and param name tokens to the macro.
1485 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001486 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001487 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001488
Chris Lattnerf64b3522008-03-09 01:54:53 +00001489 // Get the next token of the macro.
1490 LexUnexpandedToken(Tok);
1491 }
1492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493
1494
Chris Lattnerf64b3522008-03-09 01:54:53 +00001495 // Disable __VA_ARGS__ again.
1496 Ident__VA_ARGS__->setIsPoisoned(true);
1497
1498 // Check that there is no paste (##) operator at the begining or end of the
1499 // replacement list.
1500 unsigned NumTokens = MI->getNumTokens();
1501 if (NumTokens != 0) {
1502 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1503 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001504 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001505 return;
1506 }
1507 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1508 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001509 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001510 return;
1511 }
1512 }
Mike Stump11289f42009-09-09 15:08:12 +00001513
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001514 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001515
Chris Lattnerf64b3522008-03-09 01:54:53 +00001516 // Finally, if this identifier already had a macro defined for it, verify that
1517 // the macro bodies are identical and free the old definition.
1518 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001519 // It is very common for system headers to have tons of macro redefinitions
1520 // and for warnings to be disabled in system headers. If this is the case,
1521 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001522 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001523 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1524 if (!OtherMI->isUsed())
1525 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001526
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001527 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001528 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001529 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001530 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001531 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1532 << MacroNameTok.getIdentifierInfo();
1533 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1534 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001535 }
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001536 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001537 }
Mike Stump11289f42009-09-09 15:08:12 +00001538
Chris Lattnerf64b3522008-03-09 01:54:53 +00001539 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001540
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001541 assert(!MI->isUsed());
1542 // If we need warning for not using the macro, add its location in the
1543 // warn-because-unused-macro set. If it gets used it will be removed from set.
1544 if (isInPrimaryFile() && // don't warn for include'd macros.
1545 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1546 MI->getDefinitionLoc()) != Diagnostic::Ignored) {
1547 MI->setIsWarnIfUnused(true);
1548 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1549 }
1550
Chris Lattner928e9092009-04-12 01:39:54 +00001551 // If the callbacks want to know, tell them about the macro definition.
1552 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001553 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001554}
1555
1556/// HandleUndefDirective - Implements #undef.
1557///
1558void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1559 ++NumUndefined;
1560
1561 Token MacroNameTok;
1562 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001563
Chris Lattnerf64b3522008-03-09 01:54:53 +00001564 // Error reading macro name? If so, diagnostic already issued.
1565 if (MacroNameTok.is(tok::eom))
1566 return;
Mike Stump11289f42009-09-09 15:08:12 +00001567
Chris Lattnerf64b3522008-03-09 01:54:53 +00001568 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001569 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001570
Chris Lattnerf64b3522008-03-09 01:54:53 +00001571 // Okay, we finally have a valid identifier to undef.
1572 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001573
Chris Lattnerf64b3522008-03-09 01:54:53 +00001574 // If the macro is not defined, this is a noop undef, just return.
1575 if (MI == 0) return;
1576
1577 if (!MI->isUsed())
1578 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001579
1580 // If the callbacks want to know, tell them about the macro #undef.
1581 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001582 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001583
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001584 if (MI->isWarnIfUnused())
1585 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1586
Chris Lattnerf64b3522008-03-09 01:54:53 +00001587 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001588 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001589 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1590}
1591
1592
1593//===----------------------------------------------------------------------===//
1594// Preprocessor Conditional Directive Handling.
1595//===----------------------------------------------------------------------===//
1596
1597/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1598/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1599/// if any tokens have been returned or pp-directives activated before this
1600/// #ifndef has been lexed.
1601///
1602void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1603 bool ReadAnyTokensBeforeDirective) {
1604 ++NumIf;
1605 Token DirectiveTok = Result;
1606
1607 Token MacroNameTok;
1608 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001609
Chris Lattnerf64b3522008-03-09 01:54:53 +00001610 // Error reading macro name? If so, diagnostic already issued.
1611 if (MacroNameTok.is(tok::eom)) {
1612 // Skip code until we get to #endif. This helps with recovery by not
1613 // emitting an error when the #endif is reached.
1614 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1615 /*Foundnonskip*/false, /*FoundElse*/false);
1616 return;
1617 }
Mike Stump11289f42009-09-09 15:08:12 +00001618
Chris Lattnerf64b3522008-03-09 01:54:53 +00001619 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001620 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001621
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001622 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1623 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001624
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001625 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001626 // If the start of a top-level #ifdef and if the macro is not defined,
1627 // inform MIOpt that this might be the start of a proper include guard.
1628 // Otherwise it is some other form of unknown conditional which we can't
1629 // handle.
1630 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001631 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001632 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001633 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001634 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001635 }
1636
Chris Lattnerf64b3522008-03-09 01:54:53 +00001637 // If there is a macro, process it.
1638 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001639 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001640
Chris Lattnerf64b3522008-03-09 01:54:53 +00001641 // Should we include the stuff contained by this directive?
1642 if (!MI == isIfndef) {
1643 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001644 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1645 /*wasskip*/false, /*foundnonskip*/true,
1646 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001647 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001648 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001649 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001650 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001651 /*FoundElse*/false);
1652 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001653
1654 if (Callbacks) {
1655 if (isIfndef)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001656 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001657 else
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001658 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001659 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001660}
1661
1662/// HandleIfDirective - Implements the #if directive.
1663///
1664void Preprocessor::HandleIfDirective(Token &IfToken,
1665 bool ReadAnyTokensBeforeDirective) {
1666 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001667
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001668 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001669 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001670 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1671 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1672 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001673
1674 // If this condition is equivalent to #ifndef X, and if this is the first
1675 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001676 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001677 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001678 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001679 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001680 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001681 }
1682
Chris Lattnerf64b3522008-03-09 01:54:53 +00001683 // Should we include the stuff contained by this directive?
1684 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001685 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001686 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001687 /*foundnonskip*/true, /*foundelse*/false);
1688 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001689 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00001690 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001691 /*FoundElse*/false);
1692 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001693
1694 if (Callbacks)
1695 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001696}
1697
1698/// HandleEndifDirective - Implements the #endif directive.
1699///
1700void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1701 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00001702
Chris Lattnerf64b3522008-03-09 01:54:53 +00001703 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001704 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00001705
Chris Lattnerf64b3522008-03-09 01:54:53 +00001706 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001707 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001708 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00001709 Diag(EndifToken, diag::err_pp_endif_without_if);
1710 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001711 }
Mike Stump11289f42009-09-09 15:08:12 +00001712
Chris Lattnerf64b3522008-03-09 01:54:53 +00001713 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001714 if (CurPPLexer->getConditionalStackDepth() == 0)
1715 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001716
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001717 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00001718 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001719
1720 if (Callbacks)
1721 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001722}
1723
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001724/// HandleElseDirective - Implements the #else directive.
1725///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001726void Preprocessor::HandleElseDirective(Token &Result) {
1727 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001728
Chris Lattnerf64b3522008-03-09 01:54:53 +00001729 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001730 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00001731
Chris Lattnerf64b3522008-03-09 01:54:53 +00001732 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001733 if (CurPPLexer->popConditionalLevel(CI)) {
1734 Diag(Result, diag::pp_err_else_without_if);
1735 return;
1736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
Chris Lattnerf64b3522008-03-09 01:54:53 +00001738 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001739 if (CurPPLexer->getConditionalStackDepth() == 0)
1740 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001741
1742 // If this is a #else with a #else before it, report the error.
1743 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00001744
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001745 // Finally, skip the rest of the contents of this block.
1746 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1747 /*FoundElse*/true);
1748
1749 if (Callbacks)
1750 Callbacks->Else();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001751}
1752
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001753/// HandleElifDirective - Implements the #elif directive.
1754///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001755void Preprocessor::HandleElifDirective(Token &ElifToken) {
1756 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001757
Chris Lattnerf64b3522008-03-09 01:54:53 +00001758 // #elif directive in a non-skipping conditional... start skipping.
1759 // We don't care what the condition is, because we will always skip it (since
1760 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001761 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001762 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001763 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001764
1765 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001766 if (CurPPLexer->popConditionalLevel(CI)) {
1767 Diag(ElifToken, diag::pp_err_elif_without_if);
1768 return;
1769 }
Mike Stump11289f42009-09-09 15:08:12 +00001770
Chris Lattnerf64b3522008-03-09 01:54:53 +00001771 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001772 if (CurPPLexer->getConditionalStackDepth() == 0)
1773 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001774
Chris Lattnerf64b3522008-03-09 01:54:53 +00001775 // If this is a #elif with a #else before it, report the error.
1776 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1777
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001778 // Finally, skip the rest of the contents of this block.
1779 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1780 /*FoundElse*/CI.FoundElse);
1781
1782 if (Callbacks)
1783 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001784}