blob: 467d48588837fc29c37269f296065796a38c3e01 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Chris Lattner359cc442009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf44e8542010-08-24 19:08:16 +000019#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor80c60f72010-09-09 22:45:38 +000020#include "clang/Lex/Pragma.h"
Chris Lattner6e290142009-11-30 04:18:44 +000021#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000023#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000024using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Utility Methods for Preprocessor Directive Handling.
28//===----------------------------------------------------------------------===//
29
Chris Lattnerf47724b2010-08-17 15:55:45 +000030MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenek9714a232010-10-19 22:15:20 +000031 MacroInfoChain *MIChain;
Mike Stump1eb44332009-09-09 15:08:12 +000032
Ted Kremenek9714a232010-10-19 22:15:20 +000033 if (MICache) {
34 MIChain = MICache;
35 MICache = MICache->Next;
Ted Kremenekaf8fa252010-10-19 18:16:54 +000036 }
Ted Kremenek9714a232010-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 Lattnerf47724b2010-08-17 15:55:45 +000048}
49
50MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
51 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000052 new (MI) MacroInfo(L);
53 return MI;
54}
55
Chris Lattnerf47724b2010-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 Lattner0301b3f2009-02-20 22:19:20 +000062/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
63/// be reused for allocating new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000064void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenek9714a232010-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 Lattner0301b3f2009-02-20 22:19:20 +000079
Ted Kremenek9714a232010-10-19 22:15:20 +000080 MI->Destroy();
81}
Chris Lattner0301b3f2009-02-20 22:19:20 +000082
Chris Lattner141e71f2008-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 Lattner141e71f2008-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 Stump1eb44332009-09-09 15:08:12 +0000100
Douglas Gregor1fbb4472010-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 Lattner141e71f2008-03-09 01:54:53 +0000108 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +0000109 if (MacroNameTok.is(tok::eom)) {
110 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
111 return;
112 }
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Chris Lattner141e71f2008-03-09 01:54:53 +0000114 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
115 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +0000116 bool Invalid = false;
117 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
118 if (Invalid)
119 return;
120
Chris Lattner9485d232008-12-13 20:12:40 +0000121 const IdentifierInfo &Info = Identifiers.get(Spelling);
122 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000123 // C++ 2.5p2: Alternative tokens behave the same as its primary token
124 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000125 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-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 Stump1eb44332009-09-09 15:08:12 +0000143
Chris Lattner141e71f2008-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 Lattnerab82f412009-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 Lattner141e71f2008-03-09 01:54:53 +0000154 Token Tmp;
Chris Lattnerab82f412009-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 Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner141e71f2008-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 Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattner141e71f2008-03-09 01:54:53 +0000168 if (Tmp.isNot(tok::eom)) {
Chris Lattner959875a2009-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 Gregor849b2432010-03-31 17:46:05 +0000172 FixItHint Hint;
Chris Lattner959875a2009-04-14 05:15:20 +0000173 if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
Douglas Gregor849b2432010-03-31 17:46:05 +0000174 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
175 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-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 Kremenekf6452c52008-11-18 01:04:47 +0000194 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000195
Ted Kremenek60e45d42008-11-18 00:34:22 +0000196 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000197 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Ted Kremenek268ee702008-12-12 18:34:08 +0000199 if (CurPTHLexer) {
200 PTHSkipExcludedConditionalBlock();
201 return;
202 }
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Chris Lattner141e71f2008-03-09 01:54:53 +0000204 // Enter raw mode to disable identifier lookup (and thus macro expansion),
205 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000206 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000207 Token Tok;
208 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000209 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Douglas Gregorf44e8542010-08-24 19:08:16 +0000211 if (Tok.is(tok::code_completion)) {
212 if (CodeComplete)
213 CodeComplete->CodeCompleteInConditionalExclusion();
214 continue;
215 }
216
Chris Lattner141e71f2008-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 Kremenek60e45d42008-11-18 00:34:22 +0000221 while (!CurPPLexer->ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000222 if (!isCodeCompletionFile(Tok.getLocation()))
223 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
224 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000225 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000226 }
227
Chris Lattner141e71f2008-03-09 01:54:53 +0000228 // Just return and let the caller lex after this #include.
229 break;
230 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattner141e71f2008-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 Stump1eb44332009-09-09 15:08:12 +0000235
Chris Lattner141e71f2008-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 Kremenek60e45d42008-11-18 00:34:22 +0000239 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000240 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000241
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chris Lattner141e71f2008-03-09 01:54:53 +0000243 // Read the next token, the directive flavor.
244 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattner141e71f2008-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.
248 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000249 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000250 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000251 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-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.
Douglas Gregora5430162010-03-16 20:46:42 +0000260 bool Invalid = false;
261 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation(),
262 &Invalid);
263 if (Invalid)
264 return;
265
Chris Lattner141e71f2008-03-09 01:54:53 +0000266 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000267 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000268 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000269 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000270 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000271 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000272 continue;
273 }
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattner141e71f2008-03-09 01:54:53 +0000275 // Get the identifier name without trigraphs or embedded newlines. Note
276 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
277 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000278 char DirectiveBuf[20];
279 llvm::StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000280 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000281 Directive = llvm::StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000282 } else {
283 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000284 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000285 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000286 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000287 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000288 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000289 continue;
290 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000291 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
292 Directive = llvm::StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000293 }
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000295 if (Directive.startswith("if")) {
296 llvm::StringRef Sub = Directive.substr(2);
297 if (Sub.empty() || // "if"
298 Sub == "def" || // "ifdef"
299 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000300 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
301 // bother parsing the condition.
302 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000303 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000304 /*foundnonskip*/false,
305 /*fnddelse*/false);
306 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000307 } else if (Directive[0] == 'e') {
308 llvm::StringRef Sub = Directive.substr(1);
309 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000310 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000311 PPConditionalInfo CondInfo;
312 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000313 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000314 InCond = InCond; // Silence warning in no-asserts mode.
315 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Chris Lattner141e71f2008-03-09 01:54:53 +0000317 // If we popped the outermost skipping block, we're done skipping!
318 if (!CondInfo.WasSkipping)
319 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000320 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000321 // #else directive in a skipping conditional. If not in some other
322 // skipping conditional, and if #else hasn't already been seen, enter it
323 // as a non-skipping conditional.
Chris Lattner8fe00e72009-04-18 01:34:22 +0000324 DiscardUntilEndOfDirective(); // C99 6.10p4.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000325 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Chris Lattner141e71f2008-03-09 01:54:53 +0000327 // If this is a #else with a #else before it, report the error.
328 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Chris Lattner141e71f2008-03-09 01:54:53 +0000330 // Note that we've seen a #else in this conditional.
331 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattner141e71f2008-03-09 01:54:53 +0000333 // If the conditional is at the top level, and the #if block wasn't
334 // entered, enter the #else block now.
335 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
336 CondInfo.FoundNonSkip = true;
337 break;
338 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000339 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000340 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000341
342 bool ShouldEnter;
343 // If this is in a skipping block or if we're already handled this #if
344 // block, don't bother parsing the condition.
345 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
346 DiscardUntilEndOfDirective();
347 ShouldEnter = false;
348 } else {
349 // Restore the value of LexingRawMode so that identifiers are
350 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000351 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
352 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000353 IdentifierInfo *IfNDefMacro = 0;
354 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000355 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000356 }
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Chris Lattner141e71f2008-03-09 01:54:53 +0000358 // If this is a #elif with a #else before it, report the error.
359 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Chris Lattner141e71f2008-03-09 01:54:53 +0000361 // If this condition is true, enter it!
362 if (ShouldEnter) {
363 CondInfo.FoundNonSkip = true;
364 break;
365 }
366 }
367 }
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Ted Kremenek60e45d42008-11-18 00:34:22 +0000369 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000370 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000371 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000372 }
373
374 // Finally, if we are out of the conditional (saw an #endif or ran off the end
375 // of the file, just stop skipping and return to lexing whatever came after
376 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000377 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000378}
379
Ted Kremenek268ee702008-12-12 18:34:08 +0000380void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000381
382 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000383 assert(CurPTHLexer);
384 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Ted Kremenek268ee702008-12-12 18:34:08 +0000386 // Skip to the next '#else', '#elif', or #endif.
387 if (CurPTHLexer->SkipBlock()) {
388 // We have reached an #endif. Both the '#' and 'endif' tokens
389 // have been consumed by the PTHLexer. Just pop off the condition level.
390 PPConditionalInfo CondInfo;
391 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
392 InCond = InCond; // Silence warning in no-asserts mode.
393 assert(!InCond && "Can't be skipping if not in a conditional!");
394 break;
395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Ted Kremenek268ee702008-12-12 18:34:08 +0000397 // We have reached a '#else' or '#elif'. Lex the next token to get
398 // the directive flavor.
399 Token Tok;
400 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Ted Kremenek268ee702008-12-12 18:34:08 +0000402 // We can actually look up the IdentifierInfo here since we aren't in
403 // raw mode.
404 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
405
406 if (K == tok::pp_else) {
407 // #else: Enter the else condition. We aren't in a nested condition
408 // since we skip those. We're always in the one matching the last
409 // blocked we skipped.
410 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
411 // Note that we've seen a #else in this conditional.
412 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Ted Kremenek268ee702008-12-12 18:34:08 +0000414 // If the #if block wasn't entered then enter the #else block now.
415 if (!CondInfo.FoundNonSkip) {
416 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000418 // Scan until the eom token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000419 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000420 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000421 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Ted Kremenek268ee702008-12-12 18:34:08 +0000423 break;
424 }
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Ted Kremenek268ee702008-12-12 18:34:08 +0000426 // Otherwise skip this block.
427 continue;
428 }
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Ted Kremenek268ee702008-12-12 18:34:08 +0000430 assert(K == tok::pp_elif);
431 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
432
433 // If this is a #elif with a #else before it, report the error.
434 if (CondInfo.FoundElse)
435 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Ted Kremenek268ee702008-12-12 18:34:08 +0000437 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000438 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000439 if (CondInfo.FoundNonSkip)
440 continue;
441
442 // Evaluate the condition of the #elif.
443 IdentifierInfo *IfNDefMacro = 0;
444 CurPTHLexer->ParsingPreprocessorDirective = true;
445 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
446 CurPTHLexer->ParsingPreprocessorDirective = false;
447
448 // If this condition is true, enter it!
449 if (ShouldEnter) {
450 CondInfo.FoundNonSkip = true;
451 break;
452 }
453
454 // Otherwise, skip this block and go to the next one.
455 continue;
456 }
457}
458
Chris Lattner10725092008-03-09 04:17:44 +0000459/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
460/// return null on failure. isAngled indicates whether the file reference is
461/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnera1394812010-01-10 01:35:12 +0000462const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
Chris Lattner10725092008-03-09 04:17:44 +0000463 bool isAngled,
464 const DirectoryLookup *FromDir,
465 const DirectoryLookup *&CurDir) {
466 // If the header lookup mechanism may be relative to the current file, pass in
467 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000468 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000469 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000470 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000471 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000473 // If there is no file entry associated with this file, it must be the
474 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000475 // it won't be scanned for preprocessor directives. If we have the
476 // predefines buffer, resolve #include references (which come from the
477 // -include command line argument) as if they came from the main file, this
478 // affects file lookup etc.
479 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000480 FID = SourceMgr.getMainFileID();
481 CurFileEnt = SourceMgr.getFileEntryForID(FID);
482 }
Chris Lattner10725092008-03-09 04:17:44 +0000483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattner10725092008-03-09 04:17:44 +0000485 // Do a standard file entry lookup.
486 CurDir = CurDirLookup;
487 const FileEntry *FE =
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000488 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000489 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Chris Lattner10725092008-03-09 04:17:44 +0000491 // Otherwise, see if this is a subframework header. If so, this is relative
492 // to one of the headers on the #include stack. Walk the list of the current
493 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000494 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000495 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000496 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000497 return FE;
498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Chris Lattner10725092008-03-09 04:17:44 +0000500 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
501 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000502 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000503 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000504 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattnera1394812010-01-10 01:35:12 +0000505 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
Chris Lattner10725092008-03-09 04:17:44 +0000506 return FE;
507 }
508 }
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Chris Lattner10725092008-03-09 04:17:44 +0000510 // Otherwise, we really couldn't find the file.
511 return 0;
512}
513
Chris Lattner141e71f2008-03-09 01:54:53 +0000514
515//===----------------------------------------------------------------------===//
516// Preprocessor Directive Handling.
517//===----------------------------------------------------------------------===//
518
519/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000520/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000521/// lexer/preprocessor state, and advances the lexer(s) so that the next token
522/// read is the correct one.
523void Preprocessor::HandleDirective(Token &Result) {
524 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Chris Lattner141e71f2008-03-09 01:54:53 +0000526 // We just parsed a # character at the start of a line, so we're in directive
527 // mode. Tell the lexer this so any newlines we see will be converted into an
528 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000529 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner141e71f2008-03-09 01:54:53 +0000531 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000532
Chris Lattner141e71f2008-03-09 01:54:53 +0000533 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000534 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000535 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000536 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattner42aa16c2009-03-18 21:00:25 +0000538 // Save the '#' token in case we need to return it later.
539 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Chris Lattner141e71f2008-03-09 01:54:53 +0000541 // Read the next token, the directive flavor. This isn't expanded due to
542 // C99 6.10.3p8.
543 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner141e71f2008-03-09 01:54:53 +0000545 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
546 // #define A(x) #x
547 // A(abc
548 // #warning blah
549 // def)
550 // If so, the user is relying on non-portable behavior, emit a diagnostic.
551 if (InMacroArgs)
552 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Chris Lattner141e71f2008-03-09 01:54:53 +0000554TryAgain:
555 switch (Result.getKind()) {
556 case tok::eom:
557 return; // null directive.
558 case tok::comment:
559 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
560 LexUnexpandedToken(Result);
561 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000562 case tok::code_completion:
563 if (CodeComplete)
564 CodeComplete->CodeCompleteDirective(
565 CurPPLexer->getConditionalStackDepth() > 0);
566 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000567 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000568 if (getLangOptions().AsmPreprocessor)
569 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000570 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000571 default:
572 IdentifierInfo *II = Result.getIdentifierInfo();
573 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Chris Lattner141e71f2008-03-09 01:54:53 +0000575 // Ask what the preprocessor keyword ID is.
576 switch (II->getPPKeywordID()) {
577 default: break;
578 // C99 6.10.1 - Conditional Inclusion.
579 case tok::pp_if:
580 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
581 case tok::pp_ifdef:
582 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
583 case tok::pp_ifndef:
584 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
585 case tok::pp_elif:
586 return HandleElifDirective(Result);
587 case tok::pp_else:
588 return HandleElseDirective(Result);
589 case tok::pp_endif:
590 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattner141e71f2008-03-09 01:54:53 +0000592 // C99 6.10.2 - Source File Inclusion.
593 case tok::pp_include:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000594 // Handle #include.
595 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000596 case tok::pp___include_macros:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000597 // Handle -imacros.
598 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Chris Lattner141e71f2008-03-09 01:54:53 +0000600 // C99 6.10.3 - Macro Replacement.
601 case tok::pp_define:
602 return HandleDefineDirective(Result);
603 case tok::pp_undef:
604 return HandleUndefDirective(Result);
605
606 // C99 6.10.4 - Line Control.
607 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000608 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Chris Lattner141e71f2008-03-09 01:54:53 +0000610 // C99 6.10.5 - Error Directive.
611 case tok::pp_error:
612 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Chris Lattner141e71f2008-03-09 01:54:53 +0000614 // C99 6.10.6 - Pragma Directive.
615 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000616 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Chris Lattner141e71f2008-03-09 01:54:53 +0000618 // GNU Extensions.
619 case tok::pp_import:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000620 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000621 case tok::pp_include_next:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000622 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattner141e71f2008-03-09 01:54:53 +0000624 case tok::pp_warning:
625 Diag(Result, diag::ext_pp_warning_directive);
626 return HandleUserDiagnosticDirective(Result, true);
627 case tok::pp_ident:
628 return HandleIdentSCCSDirective(Result);
629 case tok::pp_sccs:
630 return HandleIdentSCCSDirective(Result);
631 case tok::pp_assert:
632 //isExtension = true; // FIXME: implement #assert
633 break;
634 case tok::pp_unassert:
635 //isExtension = true; // FIXME: implement #unassert
636 break;
637 }
638 break;
639 }
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Chris Lattner42aa16c2009-03-18 21:00:25 +0000641 // If this is a .S file, treat unknown # directives as non-preprocessor
642 // directives. This is important because # may be a comment or introduce
643 // various pseudo-ops. Just return the # token and push back the following
644 // token to be lexed next time.
645 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000646 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000647 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000648 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000649 Toks[1] = Result;
650 // Enter this token stream so that we re-lex the tokens. Make sure to
651 // enable macro expansion, in case the token after the # is an identifier
652 // that is expanded.
653 EnterTokenStream(Toks, 2, false, true);
654 return;
655 }
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Chris Lattner141e71f2008-03-09 01:54:53 +0000657 // If we reached here, the preprocessing token is not valid!
658 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Chris Lattner141e71f2008-03-09 01:54:53 +0000660 // Read the rest of the PP line.
661 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner141e71f2008-03-09 01:54:53 +0000663 // Okay, we're done parsing the directive.
664}
665
Chris Lattner478a18e2009-01-26 06:19:46 +0000666/// GetLineValue - Convert a numeric token into an unsigned value, emitting
667/// Diagnostic DiagID if it is invalid, and returning the value in Val.
668static bool GetLineValue(Token &DigitTok, unsigned &Val,
669 unsigned DiagID, Preprocessor &PP) {
670 if (DigitTok.isNot(tok::numeric_constant)) {
671 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattner478a18e2009-01-26 06:19:46 +0000673 if (DigitTok.isNot(tok::eom))
674 PP.DiscardUntilEndOfDirective();
675 return true;
676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Chris Lattner478a18e2009-01-26 06:19:46 +0000678 llvm::SmallString<64> IntegerBuffer;
679 IntegerBuffer.resize(DigitTok.getLength());
680 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000681 bool Invalid = false;
682 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
683 if (Invalid)
684 return true;
685
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000686 // Verify that we have a simple digit-sequence, and compute the value. This
687 // is always a simple digit string computed in decimal, so we do this manually
688 // here.
689 Val = 0;
690 for (unsigned i = 0; i != ActualLength; ++i) {
691 if (!isdigit(DigitTokBegin[i])) {
692 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
693 diag::err_pp_line_digit_sequence);
694 PP.DiscardUntilEndOfDirective();
695 return true;
696 }
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000698 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
699 if (NextVal < Val) { // overflow.
700 PP.Diag(DigitTok, DiagID);
701 PP.DiscardUntilEndOfDirective();
702 return true;
703 }
704 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000705 }
Mike Stump1eb44332009-09-09 15:08:12 +0000706
707 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000708 if (Val == 0) {
709 PP.Diag(DigitTok, DiagID);
710 PP.DiscardUntilEndOfDirective();
711 return true;
712 }
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000714 if (DigitTokBegin[0] == '0')
715 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattner478a18e2009-01-26 06:19:46 +0000717 return false;
718}
719
Mike Stump1eb44332009-09-09 15:08:12 +0000720/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000721/// acceptable forms are:
722/// # line digit-sequence
723/// # line digit-sequence "s-char-sequence"
724void Preprocessor::HandleLineDirective(Token &Tok) {
725 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
726 // expanded.
727 Token DigitTok;
728 Lex(DigitTok);
729
Chris Lattner359cc442009-01-26 05:29:08 +0000730 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000731 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000732 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000733 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000734
Chris Lattner478a18e2009-01-26 06:19:46 +0000735 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
736 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner359cc442009-01-26 05:29:08 +0000737 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
738 if (LineNo >= LineLimit)
739 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Chris Lattner5b9a5042009-01-26 07:57:50 +0000741 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000742 Token StrTok;
743 Lex(StrTok);
744
745 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
746 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000747 if (StrTok.is(tok::eom))
Chris Lattner359cc442009-01-26 05:29:08 +0000748 ; // ok
749 else if (StrTok.isNot(tok::string_literal)) {
750 Diag(StrTok, diag::err_pp_line_invalid_filename);
751 DiscardUntilEndOfDirective();
752 return;
753 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000754 // Parse and validate the string, converting it into a unique ID.
755 StringLiteralParser Literal(&StrTok, 1, *this);
756 assert(!Literal.AnyWide && "Didn't allow wide strings in");
757 if (Literal.hadError)
758 return DiscardUntilEndOfDirective();
759 if (Literal.Pascal) {
760 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
761 return DiscardUntilEndOfDirective();
762 }
763 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
764 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Chris Lattnerab82f412009-04-17 23:30:53 +0000766 // Verify that there is nothing after the string, other than EOM. Because
767 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
768 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000769 }
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Chris Lattner4c4ea172009-02-03 21:52:55 +0000771 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Chris Lattner16629382009-03-27 17:13:49 +0000773 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000774 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
775 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000776 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000777}
778
Chris Lattner478a18e2009-01-26 06:19:46 +0000779/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
780/// marker directive.
781static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
782 bool &IsSystemHeader, bool &IsExternCHeader,
783 Preprocessor &PP) {
784 unsigned FlagVal;
785 Token FlagTok;
786 PP.Lex(FlagTok);
787 if (FlagTok.is(tok::eom)) return false;
788 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
789 return true;
790
791 if (FlagVal == 1) {
792 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Chris Lattner478a18e2009-01-26 06:19:46 +0000794 PP.Lex(FlagTok);
795 if (FlagTok.is(tok::eom)) return false;
796 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
797 return true;
798 } else if (FlagVal == 2) {
799 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Chris Lattner137b6a62009-02-04 06:25:26 +0000801 SourceManager &SM = PP.getSourceManager();
802 // If we are leaving the current presumed file, check to make sure the
803 // presumed include stack isn't empty!
804 FileID CurFileID =
805 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
806 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000807 if (PLoc.isInvalid())
808 return true;
809
Chris Lattner137b6a62009-02-04 06:25:26 +0000810 // If there is no include loc (main file) or if the include loc is in a
811 // different physical file, then we aren't in a "1" line marker flag region.
812 SourceLocation IncLoc = PLoc.getIncludeLoc();
813 if (IncLoc.isInvalid() ||
814 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
815 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
816 PP.DiscardUntilEndOfDirective();
817 return true;
818 }
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Chris Lattner478a18e2009-01-26 06:19:46 +0000820 PP.Lex(FlagTok);
821 if (FlagTok.is(tok::eom)) return false;
822 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
823 return true;
824 }
825
826 // We must have 3 if there are still flags.
827 if (FlagVal != 3) {
828 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000829 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000830 return true;
831 }
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Chris Lattner478a18e2009-01-26 06:19:46 +0000833 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Chris Lattner478a18e2009-01-26 06:19:46 +0000835 PP.Lex(FlagTok);
836 if (FlagTok.is(tok::eom)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000837 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000838 return true;
839
840 // We must have 4 if there is yet another flag.
841 if (FlagVal != 4) {
842 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000843 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000844 return true;
845 }
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Chris Lattner478a18e2009-01-26 06:19:46 +0000847 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Chris Lattner478a18e2009-01-26 06:19:46 +0000849 PP.Lex(FlagTok);
850 if (FlagTok.is(tok::eom)) return false;
851
852 // There are no more valid flags here.
853 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000854 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000855 return true;
856}
857
858/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
859/// one of the following forms:
860///
861/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000862/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000863/// # 42 "file" ('1' | '2')? '3' '4'?
864///
865void Preprocessor::HandleDigitDirective(Token &DigitTok) {
866 // Validate the number and convert it to an unsigned. GNU does not have a
867 // line # limit other than it fit in 32-bits.
868 unsigned LineNo;
869 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
870 *this))
871 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Chris Lattner478a18e2009-01-26 06:19:46 +0000873 Token StrTok;
874 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Chris Lattner478a18e2009-01-26 06:19:46 +0000876 bool IsFileEntry = false, IsFileExit = false;
877 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000878 int FilenameID = -1;
879
Chris Lattner478a18e2009-01-26 06:19:46 +0000880 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
881 // string followed by eom.
Mike Stump1eb44332009-09-09 15:08:12 +0000882 if (StrTok.is(tok::eom))
Chris Lattner478a18e2009-01-26 06:19:46 +0000883 ; // ok
884 else if (StrTok.isNot(tok::string_literal)) {
885 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000886 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000887 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000888 // Parse and validate the string, converting it into a unique ID.
889 StringLiteralParser Literal(&StrTok, 1, *this);
890 assert(!Literal.AnyWide && "Didn't allow wide strings in");
891 if (Literal.hadError)
892 return DiscardUntilEndOfDirective();
893 if (Literal.Pascal) {
894 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
895 return DiscardUntilEndOfDirective();
896 }
897 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
898 Literal.GetStringLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner478a18e2009-01-26 06:19:46 +0000900 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000901 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000902 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000903 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000904 }
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Chris Lattner9d79eba2009-02-04 05:21:58 +0000906 // Create a line note with this information.
907 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000908 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000909 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Chris Lattner16629382009-03-27 17:13:49 +0000911 // If the preprocessor has callbacks installed, notify them of the #line
912 // change. This is used so that the line marker comes out in -E mode for
913 // example.
914 if (Callbacks) {
915 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
916 if (IsFileEntry)
917 Reason = PPCallbacks::EnterFile;
918 else if (IsFileExit)
919 Reason = PPCallbacks::ExitFile;
920 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
921 if (IsExternCHeader)
922 FileKind = SrcMgr::C_ExternCSystem;
923 else if (IsSystemHeader)
924 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Chris Lattner86d0ef72010-04-14 04:28:50 +0000926 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000927 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000928}
929
930
Chris Lattner099dd052009-01-26 05:30:54 +0000931/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
932///
Mike Stump1eb44332009-09-09 15:08:12 +0000933void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000934 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000935 // PTH doesn't emit #warning or #error directives.
936 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000937 return CurPTHLexer->DiscardToEndOfLine();
938
Chris Lattner141e71f2008-03-09 01:54:53 +0000939 // Read the rest of the line raw. We do this because we don't want macros
940 // to be expanded and we don't require that the tokens be valid preprocessing
941 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
942 // collapse multiple consequtive white space between tokens, but this isn't
943 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000944 std::string Message = CurLexer->ReadToEndOfLine();
945 if (isWarning)
946 Diag(Tok, diag::pp_hash_warning) << Message;
947 else
948 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000949}
950
951/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
952///
953void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
954 // Yes, this directive is an extension.
955 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Chris Lattner141e71f2008-03-09 01:54:53 +0000957 // Read the string argument.
958 Token StrTok;
959 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattner141e71f2008-03-09 01:54:53 +0000961 // If the token kind isn't a string, it's a malformed directive.
962 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000963 StrTok.isNot(tok::wide_string_literal)) {
964 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000965 if (StrTok.isNot(tok::eom))
966 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000967 return;
968 }
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattner141e71f2008-03-09 01:54:53 +0000970 // Verify that there is nothing after the string, other than EOM.
Chris Lattner35410d52009-04-14 05:07:49 +0000971 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +0000972
Douglas Gregor453091c2010-03-16 22:30:13 +0000973 if (Callbacks) {
974 bool Invalid = false;
975 std::string Str = getSpelling(StrTok, &Invalid);
976 if (!Invalid)
977 Callbacks->Ident(Tok.getLocation(), Str);
978 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000979}
980
981//===----------------------------------------------------------------------===//
982// Preprocessor Include Directive Handling.
983//===----------------------------------------------------------------------===//
984
985/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
986/// checked and spelled filename, e.g. as an operand of #include. This returns
987/// true if the input filename was in <>'s or false if it were in ""'s. The
988/// caller is expected to provide a buffer that is large enough to hold the
989/// spelling of the filename, but is also expected to handle the case when
990/// this method decides to use a different buffer.
991bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnera1394812010-01-10 01:35:12 +0000992 llvm::StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000993 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000994 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Chris Lattner141e71f2008-03-09 01:54:53 +0000996 // Make sure the filename is <x> or "x".
997 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +0000998 if (Buffer[0] == '<') {
999 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001000 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +00001001 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001002 return true;
1003 }
1004 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +00001005 } else if (Buffer[0] == '"') {
1006 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001007 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +00001008 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001009 return true;
1010 }
1011 isAngled = false;
1012 } else {
1013 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnera1394812010-01-10 01:35:12 +00001014 Buffer = llvm::StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001015 return true;
1016 }
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Chris Lattner141e71f2008-03-09 01:54:53 +00001018 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +00001019 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001020 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnera1394812010-01-10 01:35:12 +00001021 Buffer = llvm::StringRef();
1022 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001023 }
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Chris Lattner141e71f2008-03-09 01:54:53 +00001025 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001026 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001027 return isAngled;
1028}
1029
1030/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1031/// from a macro as multiple tokens, which need to be glued together. This
1032/// occurs for code like:
1033/// #define FOO <a/b.h>
1034/// #include FOO
1035/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1036///
1037/// This code concatenates and consumes tokens up to the '>' token. It returns
1038/// false if the > was found, otherwise it returns true if it finds and consumes
1039/// the EOM marker.
John Thompsona28cc092009-10-30 13:49:06 +00001040bool Preprocessor::ConcatenateIncludeName(
Douglas Gregorecdcb882010-10-20 22:00:55 +00001041 llvm::SmallString<128> &FilenameBuffer,
1042 SourceLocation &End) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001043 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001044
John Thompsona28cc092009-10-30 13:49:06 +00001045 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001046 while (CurTok.isNot(tok::eom)) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001047 End = CurTok.getLocation();
1048
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001049 // FIXME: Provide code completion for #includes.
1050 if (CurTok.is(tok::code_completion)) {
1051 Lex(CurTok);
1052 continue;
1053 }
1054
Chris Lattner141e71f2008-03-09 01:54:53 +00001055 // Append the spelling of this token to the buffer. If there was a space
1056 // before it, add it now.
1057 if (CurTok.hasLeadingSpace())
1058 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Chris Lattner141e71f2008-03-09 01:54:53 +00001060 // Get the spelling of the token, directly into FilenameBuffer if possible.
1061 unsigned PreAppendSize = FilenameBuffer.size();
1062 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Chris Lattner141e71f2008-03-09 01:54:53 +00001064 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001065 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Chris Lattner141e71f2008-03-09 01:54:53 +00001067 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1068 if (BufPtr != &FilenameBuffer[PreAppendSize])
1069 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattner141e71f2008-03-09 01:54:53 +00001071 // Resize FilenameBuffer to the correct size.
1072 if (CurTok.getLength() != ActualLen)
1073 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Chris Lattner141e71f2008-03-09 01:54:53 +00001075 // If we found the '>' marker, return success.
1076 if (CurTok.is(tok::greater))
1077 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001078
John Thompsona28cc092009-10-30 13:49:06 +00001079 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001080 }
1081
1082 // If we hit the eom marker, emit an error and return true so that the caller
1083 // knows the EOM has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001084 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001085 return true;
1086}
1087
1088/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1089/// file to be included from the lexer, then include it! This is a common
1090/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001091/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001092/// specifies the file to start searching from.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001093void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1094 Token &IncludeTok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001095 const DirectoryLookup *LookupFrom,
1096 bool isImport) {
1097
1098 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001099 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Chris Lattner141e71f2008-03-09 01:54:53 +00001101 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001102 llvm::SmallString<128> FilenameBuffer;
1103 llvm::StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001104 SourceLocation End;
1105
Chris Lattner141e71f2008-03-09 01:54:53 +00001106 switch (FilenameTok.getKind()) {
1107 case tok::eom:
1108 // If the token kind is EOM, the error has already been diagnosed.
1109 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Chris Lattner141e71f2008-03-09 01:54:53 +00001111 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001112 case tok::string_literal:
1113 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregorecdcb882010-10-20 22:00:55 +00001114 End = FilenameTok.getLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001115 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Chris Lattner141e71f2008-03-09 01:54:53 +00001117 case tok::less:
1118 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1119 // case, glue the tokens together into FilenameBuffer and interpret those.
1120 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +00001121 if (ConcatenateIncludeName(FilenameBuffer, End))
Chris Lattner141e71f2008-03-09 01:54:53 +00001122 return; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001123 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001124 break;
1125 default:
1126 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1127 DiscardUntilEndOfDirective();
1128 return;
1129 }
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001131 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001132 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001133 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1134 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001135 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001136 DiscardUntilEndOfDirective();
1137 return;
1138 }
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001140 // Verify that there is nothing after the filename, other than EOM. Note that
1141 // we allow macros that expand to nothing after the filename, because this
1142 // falls into the category of "#include pp-tokens new-line" specified in
1143 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001144 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001145
1146 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001147 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1148 Diag(FilenameTok, diag::err_pp_include_too_deep);
1149 return;
1150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Chris Lattner141e71f2008-03-09 01:54:53 +00001152 // Search include directories.
1153 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +00001154 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +00001155 if (File == 0) {
Chris Lattnera1394812010-01-10 01:35:12 +00001156 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner3692b092008-11-18 07:59:24 +00001157 return;
1158 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001159
Douglas Gregorecdcb882010-10-20 22:00:55 +00001160 // Notify the callback object that we've seen an inclusion directive.
1161 if (Callbacks)
1162 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1163 End);
1164
Chris Lattner72181832008-09-26 20:12:23 +00001165 // The #included file will be considered to be a system header if either it is
1166 // in a system include directory, or if the #includer is a system include
1167 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001168 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001169 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001170 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001172 // Ask HeaderInfo if we should enter this #include file. If not, #including
1173 // this file will have no effect.
1174 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001175 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001176 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001177 return;
1178 }
1179
Chris Lattner141e71f2008-03-09 01:54:53 +00001180 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001181 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1182 FileCharacter);
1183 if (FID.isInvalid()) {
Chris Lattnera1394812010-01-10 01:35:12 +00001184 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +00001185 return;
1186 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001187
1188 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001189 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001190}
1191
1192/// HandleIncludeNextDirective - Implements #include_next.
1193///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001194void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1195 Token &IncludeNextTok) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001196 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Chris Lattner141e71f2008-03-09 01:54:53 +00001198 // #include_next is like #include, except that we start searching after
1199 // the current found directory. If we can't do this, issue a
1200 // diagnostic.
1201 const DirectoryLookup *Lookup = CurDirLookup;
1202 if (isInPrimaryFile()) {
1203 Lookup = 0;
1204 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1205 } else if (Lookup == 0) {
1206 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1207 } else {
1208 // Start looking up in the next directory.
1209 ++Lookup;
1210 }
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Douglas Gregorecdcb882010-10-20 22:00:55 +00001212 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattner141e71f2008-03-09 01:54:53 +00001213}
1214
1215/// HandleImportDirective - Implements #import.
1216///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001217void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1218 Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001219 if (!Features.ObjC1) // #import is standard for ObjC.
1220 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Douglas Gregorecdcb882010-10-20 22:00:55 +00001222 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001223}
1224
Chris Lattnerde076652009-04-08 18:46:40 +00001225/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1226/// pseudo directive in the predefines buffer. This handles it by sucking all
1227/// tokens through the preprocessor and discarding them (only keeping the side
1228/// effects on the preprocessor).
Douglas Gregorecdcb882010-10-20 22:00:55 +00001229void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1230 Token &IncludeMacrosTok) {
Chris Lattnerde076652009-04-08 18:46:40 +00001231 // This directive should only occur in the predefines buffer. If not, emit an
1232 // error and reject it.
1233 SourceLocation Loc = IncludeMacrosTok.getLocation();
1234 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1235 Diag(IncludeMacrosTok.getLocation(),
1236 diag::pp_include_macros_out_of_predefines);
1237 DiscardUntilEndOfDirective();
1238 return;
1239 }
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Chris Lattnerfd105112009-04-08 20:53:24 +00001241 // Treat this as a normal #include for checking purposes. If this is
1242 // successful, it will push a new lexer onto the include stack.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001243 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Chris Lattnerfd105112009-04-08 20:53:24 +00001245 Token TmpTok;
1246 do {
1247 Lex(TmpTok);
1248 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1249 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001250}
1251
Chris Lattner141e71f2008-03-09 01:54:53 +00001252//===----------------------------------------------------------------------===//
1253// Preprocessor Macro Directive Handling.
1254//===----------------------------------------------------------------------===//
1255
1256/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1257/// definition has just been read. Lex the rest of the arguments and the
1258/// closing ), updating MI with what we learn. Return true if an error occurs
1259/// parsing the arg list.
1260bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1261 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Chris Lattner141e71f2008-03-09 01:54:53 +00001263 Token Tok;
1264 while (1) {
1265 LexUnexpandedToken(Tok);
1266 switch (Tok.getKind()) {
1267 case tok::r_paren:
1268 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001269 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001270 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001271 // Otherwise we have #define FOO(A,)
1272 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1273 return true;
1274 case tok::ellipsis: // #define X(... -> C99 varargs
1275 // Warn if use of C99 feature in non-C99 mode.
1276 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1277
1278 // Lex the token after the identifier.
1279 LexUnexpandedToken(Tok);
1280 if (Tok.isNot(tok::r_paren)) {
1281 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1282 return true;
1283 }
1284 // Add the __VA_ARGS__ identifier as an argument.
1285 Arguments.push_back(Ident__VA_ARGS__);
1286 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001287 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001288 return false;
1289 case tok::eom: // #define X(
1290 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1291 return true;
1292 default:
1293 // Handle keywords and identifiers here to accept things like
1294 // #define Foo(for) for.
1295 IdentifierInfo *II = Tok.getIdentifierInfo();
1296 if (II == 0) {
1297 // #define X(1
1298 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1299 return true;
1300 }
1301
1302 // If this is already used as an argument, it is used multiple times (e.g.
1303 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001304 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001305 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001306 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001307 return true;
1308 }
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Chris Lattner141e71f2008-03-09 01:54:53 +00001310 // Add the argument to the macro info.
1311 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Chris Lattner141e71f2008-03-09 01:54:53 +00001313 // Lex the token after the identifier.
1314 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Chris Lattner141e71f2008-03-09 01:54:53 +00001316 switch (Tok.getKind()) {
1317 default: // #define X(A B
1318 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1319 return true;
1320 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001321 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001322 return false;
1323 case tok::comma: // #define X(A,
1324 break;
1325 case tok::ellipsis: // #define X(A... -> GCC extension
1326 // Diagnose extension.
1327 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Chris Lattner141e71f2008-03-09 01:54:53 +00001329 // Lex the token after the identifier.
1330 LexUnexpandedToken(Tok);
1331 if (Tok.isNot(tok::r_paren)) {
1332 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1333 return true;
1334 }
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Chris Lattner141e71f2008-03-09 01:54:53 +00001336 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001337 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001338 return false;
1339 }
1340 }
1341 }
1342}
1343
1344/// HandleDefineDirective - Implements #define. This consumes the entire macro
1345/// line then lets the caller lex the next real token.
1346void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1347 ++NumDefined;
1348
1349 Token MacroNameTok;
1350 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Chris Lattner141e71f2008-03-09 01:54:53 +00001352 // Error reading macro name? If so, diagnostic already issued.
1353 if (MacroNameTok.is(tok::eom))
1354 return;
1355
Chris Lattner2451b522009-04-21 04:46:33 +00001356 Token LastTok = MacroNameTok;
1357
Chris Lattner141e71f2008-03-09 01:54:53 +00001358 // If we are supposed to keep comments in #defines, reenable comment saving
1359 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001360 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Chris Lattner141e71f2008-03-09 01:54:53 +00001362 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001363 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Chris Lattner141e71f2008-03-09 01:54:53 +00001365 Token Tok;
1366 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Chris Lattner141e71f2008-03-09 01:54:53 +00001368 // If this is a function-like macro definition, parse the argument list,
1369 // marking each of the identifiers as being used as macro arguments. Also,
1370 // check other constraints on the first token of the macro body.
1371 if (Tok.is(tok::eom)) {
1372 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001373 } else if (Tok.hasLeadingSpace()) {
1374 // This is a normal token with leading space. Clear the leading space
1375 // marker on the first token to get proper expansion.
1376 Tok.clearFlag(Token::LeadingSpace);
1377 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001378 // This is a function-like macro definition. Read the argument list.
1379 MI->setIsFunctionLike();
1380 if (ReadMacroDefinitionArgList(MI)) {
1381 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001382 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001383 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001384 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001385 DiscardUntilEndOfDirective();
1386 return;
1387 }
1388
Chris Lattner8fde5972009-04-19 18:26:34 +00001389 // If this is a definition of a variadic C99 function-like macro, not using
1390 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Chris Lattner8fde5972009-04-19 18:26:34 +00001392 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1393 // This gets unpoisoned where it is allowed.
1394 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1395 if (MI->isC99Varargs())
1396 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Chris Lattner141e71f2008-03-09 01:54:53 +00001398 // Read the first token after the arg list for down below.
1399 LexUnexpandedToken(Tok);
Chris Lattner6272bcf2009-04-18 02:23:25 +00001400 } else if (Features.C99) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001401 // C99 requires whitespace between the macro definition and the body. Emit
1402 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001403 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001404 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001405 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1406 // first character of a replacement list is not a character required by
1407 // subclause 5.2.1, then there shall be white-space separation between the
1408 // identifier and the replacement list.". 5.2.1 lists this set:
1409 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1410 // is irrelevant here.
1411 bool isInvalid = false;
1412 if (Tok.is(tok::at)) // @ is not in the list above.
1413 isInvalid = true;
1414 else if (Tok.is(tok::unknown)) {
1415 // If we have an unknown token, it is something strange like "`". Since
1416 // all of valid characters would have lexed into a single character
1417 // token of some sort, we know this is not a valid case.
1418 isInvalid = true;
1419 }
1420 if (isInvalid)
1421 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1422 else
1423 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001424 }
Chris Lattner2451b522009-04-21 04:46:33 +00001425
1426 if (!Tok.is(tok::eom))
1427 LastTok = Tok;
1428
Chris Lattner141e71f2008-03-09 01:54:53 +00001429 // Read the rest of the macro body.
1430 if (MI->isObjectLike()) {
1431 // Object-like macros are very simple, just read their body.
1432 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001433 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001434 MI->AddTokenToBody(Tok);
1435 // Get the next token of the macro.
1436 LexUnexpandedToken(Tok);
1437 }
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Chris Lattner141e71f2008-03-09 01:54:53 +00001439 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001440 // Otherwise, read the body of a function-like macro. While we are at it,
1441 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1442 // parameters in function-like macro expansions.
Chris Lattner141e71f2008-03-09 01:54:53 +00001443 while (Tok.isNot(tok::eom)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001444 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001445
Chris Lattner141e71f2008-03-09 01:54:53 +00001446 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001447 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Chris Lattner141e71f2008-03-09 01:54:53 +00001449 // Get the next token of the macro.
1450 LexUnexpandedToken(Tok);
1451 continue;
1452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Chris Lattner141e71f2008-03-09 01:54:53 +00001454 // Get the next token of the macro.
1455 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Chris Lattner32404692009-05-25 17:16:10 +00001457 // Check for a valid macro arg identifier.
1458 if (Tok.getIdentifierInfo() == 0 ||
1459 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1460
1461 // If this is assembler-with-cpp mode, we accept random gibberish after
1462 // the '#' because '#' is often a comment character. However, change
1463 // the kind of the token to tok::unknown so that the preprocessor isn't
1464 // confused.
1465 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
1466 LastTok.setKind(tok::unknown);
1467 } else {
1468 Diag(Tok, diag::err_pp_stringize_not_parameter);
1469 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Chris Lattner32404692009-05-25 17:16:10 +00001471 // Disable __VA_ARGS__ again.
1472 Ident__VA_ARGS__->setIsPoisoned(true);
1473 return;
1474 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001475 }
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Chris Lattner32404692009-05-25 17:16:10 +00001477 // Things look ok, add the '#' and param name tokens to the macro.
1478 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001479 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001480 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Chris Lattner141e71f2008-03-09 01:54:53 +00001482 // Get the next token of the macro.
1483 LexUnexpandedToken(Tok);
1484 }
1485 }
Mike Stump1eb44332009-09-09 15:08:12 +00001486
1487
Chris Lattner141e71f2008-03-09 01:54:53 +00001488 // Disable __VA_ARGS__ again.
1489 Ident__VA_ARGS__->setIsPoisoned(true);
1490
1491 // Check that there is no paste (##) operator at the begining or end of the
1492 // replacement list.
1493 unsigned NumTokens = MI->getNumTokens();
1494 if (NumTokens != 0) {
1495 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1496 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001497 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001498 return;
1499 }
1500 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1501 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001502 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001503 return;
1504 }
1505 }
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Chris Lattner2451b522009-04-21 04:46:33 +00001507 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Chris Lattner141e71f2008-03-09 01:54:53 +00001509 // Finally, if this identifier already had a macro defined for it, verify that
1510 // the macro bodies are identical and free the old definition.
1511 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001512 // It is very common for system headers to have tons of macro redefinitions
1513 // and for warnings to be disabled in system headers. If this is the case,
1514 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001515 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001516 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1517 if (!OtherMI->isUsed())
1518 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001519
Chris Lattnerf47724b2010-08-17 15:55:45 +00001520 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001521 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001522 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001523 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001524 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1525 << MacroNameTok.getIdentifierInfo();
1526 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1527 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001528 }
Ted Kremenek0ea76722008-12-15 19:56:42 +00001529 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001530 }
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Chris Lattner141e71f2008-03-09 01:54:53 +00001532 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001534 assert(!MI->isUsed());
1535 // If we need warning for not using the macro, add its location in the
1536 // warn-because-unused-macro set. If it gets used it will be removed from set.
1537 if (isInPrimaryFile() && // don't warn for include'd macros.
1538 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1539 MI->getDefinitionLoc()) != Diagnostic::Ignored) {
1540 MI->setIsWarnIfUnused(true);
1541 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1542 }
1543
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001544 // If the callbacks want to know, tell them about the macro definition.
1545 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001546 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001547}
1548
1549/// HandleUndefDirective - Implements #undef.
1550///
1551void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1552 ++NumUndefined;
1553
1554 Token MacroNameTok;
1555 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Chris Lattner141e71f2008-03-09 01:54:53 +00001557 // Error reading macro name? If so, diagnostic already issued.
1558 if (MacroNameTok.is(tok::eom))
1559 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Chris Lattner141e71f2008-03-09 01:54:53 +00001561 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001562 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Chris Lattner141e71f2008-03-09 01:54:53 +00001564 // Okay, we finally have a valid identifier to undef.
1565 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Chris Lattner141e71f2008-03-09 01:54:53 +00001567 // If the macro is not defined, this is a noop undef, just return.
1568 if (MI == 0) return;
1569
1570 if (!MI->isUsed())
1571 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001572
1573 // If the callbacks want to know, tell them about the macro #undef.
1574 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001575 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001576
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001577 if (MI->isWarnIfUnused())
1578 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1579
Chris Lattner141e71f2008-03-09 01:54:53 +00001580 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001581 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001582 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1583}
1584
1585
1586//===----------------------------------------------------------------------===//
1587// Preprocessor Conditional Directive Handling.
1588//===----------------------------------------------------------------------===//
1589
1590/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1591/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1592/// if any tokens have been returned or pp-directives activated before this
1593/// #ifndef has been lexed.
1594///
1595void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1596 bool ReadAnyTokensBeforeDirective) {
1597 ++NumIf;
1598 Token DirectiveTok = Result;
1599
1600 Token MacroNameTok;
1601 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Chris Lattner141e71f2008-03-09 01:54:53 +00001603 // Error reading macro name? If so, diagnostic already issued.
1604 if (MacroNameTok.is(tok::eom)) {
1605 // Skip code until we get to #endif. This helps with recovery by not
1606 // emitting an error when the #endif is reached.
1607 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1608 /*Foundnonskip*/false, /*FoundElse*/false);
1609 return;
1610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Chris Lattner141e71f2008-03-09 01:54:53 +00001612 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001613 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001614
Chris Lattner13d283d2010-02-12 08:03:27 +00001615 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1616 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001617
Ted Kremenek60e45d42008-11-18 00:34:22 +00001618 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001619 // If the start of a top-level #ifdef and if the macro is not defined,
1620 // inform MIOpt that this might be the start of a proper include guard.
1621 // Otherwise it is some other form of unknown conditional which we can't
1622 // handle.
1623 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001624 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001625 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001626 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001627 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001628 }
1629
Chris Lattner141e71f2008-03-09 01:54:53 +00001630 // If there is a macro, process it.
1631 if (MI) // Mark it used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001632 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Chris Lattner141e71f2008-03-09 01:54:53 +00001634 // Should we include the stuff contained by this directive?
1635 if (!MI == isIfndef) {
1636 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001637 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1638 /*wasskip*/false, /*foundnonskip*/true,
1639 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001640 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001641 // No, skip the contents of this block.
Chris Lattner141e71f2008-03-09 01:54:53 +00001642 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001643 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001644 /*FoundElse*/false);
1645 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001646
1647 if (Callbacks) {
1648 if (isIfndef)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001649 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001650 else
Craig Silverstein2aa92672010-11-19 21:33:15 +00001651 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001652 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001653}
1654
1655/// HandleIfDirective - Implements the #if directive.
1656///
1657void Preprocessor::HandleIfDirective(Token &IfToken,
1658 bool ReadAnyTokensBeforeDirective) {
1659 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Craig Silverstein08985b92010-11-06 01:19:03 +00001661 // Parse and evaluate the conditional expression.
Chris Lattner141e71f2008-03-09 01:54:53 +00001662 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein08985b92010-11-06 01:19:03 +00001663 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1664 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1665 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes0049db62008-06-01 18:31:24 +00001666
1667 // If this condition is equivalent to #ifndef X, and if this is the first
1668 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001669 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001670 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001671 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001672 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001673 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001674 }
1675
Chris Lattner141e71f2008-03-09 01:54:53 +00001676 // Should we include the stuff contained by this directive?
1677 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001678 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001679 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001680 /*foundnonskip*/true, /*foundelse*/false);
1681 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001682 // No, skip the contents of this block.
Mike Stump1eb44332009-09-09 15:08:12 +00001683 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001684 /*FoundElse*/false);
1685 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001686
1687 if (Callbacks)
1688 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001689}
1690
1691/// HandleEndifDirective - Implements the #endif directive.
1692///
1693void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1694 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Chris Lattner141e71f2008-03-09 01:54:53 +00001696 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001697 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Chris Lattner141e71f2008-03-09 01:54:53 +00001699 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001700 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001701 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001702 Diag(EndifToken, diag::err_pp_endif_without_if);
1703 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001704 }
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Chris Lattner141e71f2008-03-09 01:54:53 +00001706 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001707 if (CurPPLexer->getConditionalStackDepth() == 0)
1708 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Ted Kremenek60e45d42008-11-18 00:34:22 +00001710 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001711 "This code should only be reachable in the non-skipping case!");
Craig Silverstein08985b92010-11-06 01:19:03 +00001712
1713 if (Callbacks)
1714 Callbacks->Endif();
Chris Lattner141e71f2008-03-09 01:54:53 +00001715}
1716
Craig Silverstein08985b92010-11-06 01:19:03 +00001717/// HandleElseDirective - Implements the #else directive.
1718///
Chris Lattner141e71f2008-03-09 01:54:53 +00001719void Preprocessor::HandleElseDirective(Token &Result) {
1720 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Chris Lattner141e71f2008-03-09 01:54:53 +00001722 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001723 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Chris Lattner141e71f2008-03-09 01:54:53 +00001725 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001726 if (CurPPLexer->popConditionalLevel(CI)) {
1727 Diag(Result, diag::pp_err_else_without_if);
1728 return;
1729 }
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Chris Lattner141e71f2008-03-09 01:54:53 +00001731 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001732 if (CurPPLexer->getConditionalStackDepth() == 0)
1733 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001734
1735 // If this is a #else with a #else before it, report the error.
1736 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Craig Silverstein08985b92010-11-06 01:19:03 +00001738 // Finally, skip the rest of the contents of this block.
1739 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1740 /*FoundElse*/true);
1741
1742 if (Callbacks)
1743 Callbacks->Else();
Chris Lattner141e71f2008-03-09 01:54:53 +00001744}
1745
Craig Silverstein08985b92010-11-06 01:19:03 +00001746/// HandleElifDirective - Implements the #elif directive.
1747///
Chris Lattner141e71f2008-03-09 01:54:53 +00001748void Preprocessor::HandleElifDirective(Token &ElifToken) {
1749 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Chris Lattner141e71f2008-03-09 01:54:53 +00001751 // #elif directive in a non-skipping conditional... start skipping.
1752 // We don't care what the condition is, because we will always skip it (since
1753 // the block immediately before it was included).
Craig Silverstein08985b92010-11-06 01:19:03 +00001754 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001755 DiscardUntilEndOfDirective();
Craig Silverstein08985b92010-11-06 01:19:03 +00001756 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001757
1758 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001759 if (CurPPLexer->popConditionalLevel(CI)) {
1760 Diag(ElifToken, diag::pp_err_elif_without_if);
1761 return;
1762 }
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Chris Lattner141e71f2008-03-09 01:54:53 +00001764 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001765 if (CurPPLexer->getConditionalStackDepth() == 0)
1766 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Chris Lattner141e71f2008-03-09 01:54:53 +00001768 // If this is a #elif with a #else before it, report the error.
1769 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1770
Craig Silverstein08985b92010-11-06 01:19:03 +00001771 // Finally, skip the rest of the contents of this block.
1772 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1773 /*FoundElse*/CI.FoundElse);
1774
1775 if (Callbacks)
1776 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001777}