blob: 9446d51f9d2b71e650a43439574c653faefd6704 [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 Gregorfba18aa2011-09-15 22:00:41 +000020#include "clang/Lex/ModuleLoader.h"
Douglas Gregor80c60f72010-09-09 22:45:38 +000021#include "clang/Lex/Pragma.h"
Chris Lattner6e290142009-11-30 04:18:44 +000022#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000023#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000024#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000025using namespace clang;
26
27//===----------------------------------------------------------------------===//
28// Utility Methods for Preprocessor Directive Handling.
29//===----------------------------------------------------------------------===//
30
Chris Lattnerf47724b2010-08-17 15:55:45 +000031MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenek9714a232010-10-19 22:15:20 +000032 MacroInfoChain *MIChain;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Ted Kremenek9714a232010-10-19 22:15:20 +000034 if (MICache) {
35 MIChain = MICache;
36 MICache = MICache->Next;
Ted Kremenekaf8fa252010-10-19 18:16:54 +000037 }
Ted Kremenek9714a232010-10-19 22:15:20 +000038 else {
39 MIChain = BP.Allocate<MacroInfoChain>();
40 }
41
42 MIChain->Next = MIChainHead;
43 MIChain->Prev = 0;
44 if (MIChainHead)
45 MIChainHead->Prev = MIChain;
46 MIChainHead = MIChain;
47
48 return &(MIChain->MI);
Chris Lattnerf47724b2010-08-17 15:55:45 +000049}
50
51MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
52 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000053 new (MI) MacroInfo(L);
54 return MI;
55}
56
Chris Lattnerf47724b2010-08-17 15:55:45 +000057MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
58 MacroInfo *MI = AllocateMacroInfo();
59 new (MI) MacroInfo(MacroToClone, BP);
60 return MI;
61}
62
Chris Lattner0301b3f2009-02-20 22:19:20 +000063/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
64/// be reused for allocating new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000065void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenek9714a232010-10-19 22:15:20 +000066 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
67 if (MacroInfoChain *Prev = MIChain->Prev) {
68 MacroInfoChain *Next = MIChain->Next;
69 Prev->Next = Next;
70 if (Next)
71 Next->Prev = Prev;
72 }
73 else {
74 assert(MIChainHead == MIChain);
75 MIChainHead = MIChain->Next;
76 MIChainHead->Prev = 0;
77 }
78 MIChain->Next = MICache;
79 MICache = MIChain;
Chris Lattner0301b3f2009-02-20 22:19:20 +000080
Ted Kremenek9714a232010-10-19 22:15:20 +000081 MI->Destroy();
82}
Chris Lattner0301b3f2009-02-20 22:19:20 +000083
Chris Lattner141e71f2008-03-09 01:54:53 +000084/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
Peter Collingbourne84021552011-02-28 02:37:51 +000085/// current line until the tok::eod token is found.
Chris Lattner141e71f2008-03-09 01:54:53 +000086void Preprocessor::DiscardUntilEndOfDirective() {
87 Token Tmp;
88 do {
89 LexUnexpandedToken(Tmp);
Peter Collingbournea5ef5842011-02-22 13:49:06 +000090 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne84021552011-02-28 02:37:51 +000091 } while (Tmp.isNot(tok::eod));
Chris Lattner141e71f2008-03-09 01:54:53 +000092}
93
Chris Lattner141e71f2008-03-09 01:54:53 +000094/// ReadMacroName - Lex and validate a macro name, which occurs after a
Peter Collingbourne84021552011-02-28 02:37:51 +000095/// #define or #undef. This sets the token kind to eod and discards the rest
Chris Lattner141e71f2008-03-09 01:54:53 +000096/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
97/// this is due to a a #define, 2 if #undef directive, 0 if it is something
98/// else (e.g. #ifdef).
99void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
100 // Read the token, don't allow macro expansion on it.
101 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000103 if (MacroNameTok.is(tok::code_completion)) {
104 if (CodeComplete)
105 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000106 setCodeCompletionReached();
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000107 LexUnexpandedToken(MacroNameTok);
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000108 }
109
Chris Lattner141e71f2008-03-09 01:54:53 +0000110 // Missing macro name?
Peter Collingbourne84021552011-02-28 02:37:51 +0000111 if (MacroNameTok.is(tok::eod)) {
Chris Lattner3692b092008-11-18 07:59:24 +0000112 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
113 return;
114 }
Mike Stump1eb44332009-09-09 15:08:12 +0000115
Chris Lattner141e71f2008-03-09 01:54:53 +0000116 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
117 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +0000118 bool Invalid = false;
119 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
120 if (Invalid)
121 return;
122
Chris Lattner9485d232008-12-13 20:12:40 +0000123 const IdentifierInfo &Info = Identifiers.get(Spelling);
124 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000125 // C++ 2.5p2: Alternative tokens behave the same as its primary token
126 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000127 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +0000128 else
129 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
130 // Fall through on error.
131 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
132 // Error if defining "defined": C99 6.10.8.4.
133 Diag(MacroNameTok, diag::err_defined_macro_name);
134 } else if (isDefineUndef && II->hasMacroDefinition() &&
135 getMacroInfo(II)->isBuiltinMacro()) {
136 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
137 if (isDefineUndef == 1)
138 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
139 else
140 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
141 } else {
142 // Okay, we got a good identifier node. Return it.
143 return;
144 }
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Chris Lattner141e71f2008-03-09 01:54:53 +0000146 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne84021552011-02-28 02:37:51 +0000147 // token kind to tok::eod.
148 MacroNameTok.setKind(tok::eod);
Chris Lattner141e71f2008-03-09 01:54:53 +0000149 return DiscardUntilEndOfDirective();
150}
151
Peter Collingbourne84021552011-02-28 02:37:51 +0000152/// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
153/// not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattnerab82f412009-04-17 23:30:53 +0000154/// true, then we consider macros that expand to zero tokens as being ok.
155void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000156 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000157 // Lex unexpanded tokens for most directives: macros might expand to zero
158 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
159 // #line) allow empty macros.
160 if (EnableMacros)
161 Lex(Tmp);
162 else
163 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattner141e71f2008-03-09 01:54:53 +0000165 // There should be no tokens after the directive, but we allow them as an
166 // extension.
167 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
168 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Peter Collingbourne84021552011-02-28 02:37:51 +0000170 if (Tmp.isNot(tok::eod)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000171 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000172 // or if this is a macro-style preprocessing directive, because it is more
173 // trouble than it is worth to insert /**/ and check that there is no /**/
174 // in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000175 FixItHint Hint;
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000176 if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
177 !CurTokenLexer)
Douglas Gregor849b2432010-03-31 17:46:05 +0000178 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
179 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000180 DiscardUntilEndOfDirective();
181 }
182}
183
184
185
186/// SkipExcludedConditionalBlock - We just read a #if or related directive and
187/// decided that the subsequent tokens are in the #if'd out portion of the
188/// file. Lex the rest of the file, until we see an #endif. If
189/// FoundNonSkipPortion is true, then we have already emitted code for part of
190/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
191/// is true, then #else directives are ok, if not, then we have already seen one
192/// so a #else directive is a duplicate. When this returns, the caller can lex
193/// the first valid token.
194void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
195 bool FoundNonSkipPortion,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000196 bool FoundElse,
197 SourceLocation ElseLoc) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000198 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000199 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000200
Ted Kremenek60e45d42008-11-18 00:34:22 +0000201 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000202 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Ted Kremenek268ee702008-12-12 18:34:08 +0000204 if (CurPTHLexer) {
205 PTHSkipExcludedConditionalBlock();
206 return;
207 }
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Chris Lattner141e71f2008-03-09 01:54:53 +0000209 // Enter raw mode to disable identifier lookup (and thus macro expansion),
210 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000211 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000212 Token Tok;
213 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000214 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Douglas Gregorf44e8542010-08-24 19:08:16 +0000216 if (Tok.is(tok::code_completion)) {
217 if (CodeComplete)
218 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000219 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000220 continue;
221 }
222
Chris Lattner141e71f2008-03-09 01:54:53 +0000223 // If this is the end of the buffer, we have an error.
224 if (Tok.is(tok::eof)) {
225 // Emit errors for each unterminated conditional on the stack, including
226 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000227 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000228 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000229 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
230 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000231 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000232 }
233
Chris Lattner141e71f2008-03-09 01:54:53 +0000234 // Just return and let the caller lex after this #include.
235 break;
236 }
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Chris Lattner141e71f2008-03-09 01:54:53 +0000238 // If this token is not a preprocessor directive, just skip it.
239 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
240 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattner141e71f2008-03-09 01:54:53 +0000242 // We just parsed a # character at the start of a line, so we're in
243 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne84021552011-02-28 02:37:51 +0000244 // converted into an EOD token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000245 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000246 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000247
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Chris Lattner141e71f2008-03-09 01:54:53 +0000249 // Read the next token, the directive flavor.
250 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattner141e71f2008-03-09 01:54:53 +0000252 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
253 // something bogus), skip it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000254 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000255 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000256 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000257 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000258 continue;
259 }
260
261 // If the first letter isn't i or e, it isn't intesting to us. We know that
262 // this is safe in the face of spelling differences, because there is no way
263 // to spell an i/e in a strange way that is another letter. Skipping this
264 // allows us to avoid looking up the identifier info for #define/#undef and
265 // other common directives.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000266 const char *RawCharData = Tok.getRawIdentifierData();
267
Chris Lattner141e71f2008-03-09 01:54:53 +0000268 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000269 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000270 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000271 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000272 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000273 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000274 continue;
275 }
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Chris Lattner141e71f2008-03-09 01:54:53 +0000277 // Get the identifier name without trigraphs or embedded newlines. Note
278 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
279 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000280 char DirectiveBuf[20];
Chris Lattner5f9e2722011-07-23 10:55:15 +0000281 StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000282 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000283 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000284 } else {
285 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000286 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000287 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000288 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000289 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000290 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000291 continue;
292 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000293 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000294 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000295 }
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000297 if (Directive.startswith("if")) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000298 StringRef Sub = Directive.substr(2);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000299 if (Sub.empty() || // "if"
300 Sub == "def" || // "ifdef"
301 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000302 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
303 // bother parsing the condition.
304 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000305 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000306 /*foundnonskip*/false,
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000307 /*foundelse*/false);
308
309 if (Callbacks)
310 Callbacks->Endif();
Chris Lattner141e71f2008-03-09 01:54:53 +0000311 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000312 } else if (Directive[0] == 'e') {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000313 StringRef Sub = Directive.substr(1);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000314 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000315 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000316 PPConditionalInfo CondInfo;
317 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000318 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000319 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattner141e71f2008-03-09 01:54:53 +0000320 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner141e71f2008-03-09 01:54:53 +0000322 // If we popped the outermost skipping block, we're done skipping!
323 if (!CondInfo.WasSkipping)
324 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000325 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000326 // #else directive in a skipping conditional. If not in some other
327 // skipping conditional, and if #else hasn't already been seen, enter it
328 // as a non-skipping conditional.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000329 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Chris Lattner141e71f2008-03-09 01:54:53 +0000331 // If this is a #else with a #else before it, report the error.
332 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chris Lattner141e71f2008-03-09 01:54:53 +0000334 // Note that we've seen a #else in this conditional.
335 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000337 if (Callbacks)
338 Callbacks->Else();
339
Chris Lattner141e71f2008-03-09 01:54:53 +0000340 // If the conditional is at the top level, and the #if block wasn't
341 // entered, enter the #else block now.
342 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
343 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000344 CheckEndOfDirective("else");
Chris Lattner141e71f2008-03-09 01:54:53 +0000345 break;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000346 } else {
347 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattner141e71f2008-03-09 01:54:53 +0000348 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000349 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000350 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000351
352 bool ShouldEnter;
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000353 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +0000354 // If this is in a skipping block or if we're already handled this #if
355 // block, don't bother parsing the condition.
356 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
357 DiscardUntilEndOfDirective();
358 ShouldEnter = false;
359 } else {
360 // Restore the value of LexingRawMode so that identifiers are
361 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000362 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
363 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000364 IdentifierInfo *IfNDefMacro = 0;
365 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000366 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000367 }
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000368 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Chris Lattner141e71f2008-03-09 01:54:53 +0000370 // If this is a #elif with a #else before it, report the error.
371 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000373 if (Callbacks)
374 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
375
Chris Lattner141e71f2008-03-09 01:54:53 +0000376 // If this condition is true, enter it!
377 if (ShouldEnter) {
378 CondInfo.FoundNonSkip = true;
379 break;
380 }
381 }
382 }
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Ted Kremenek60e45d42008-11-18 00:34:22 +0000384 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000385 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000386 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000387 }
388
389 // Finally, if we are out of the conditional (saw an #endif or ran off the end
390 // of the file, just stop skipping and return to lexing whatever came after
391 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000392 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000393
394 if (Callbacks) {
395 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
396 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
397 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000398}
399
Ted Kremenek268ee702008-12-12 18:34:08 +0000400void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000401
402 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000403 assert(CurPTHLexer);
404 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Ted Kremenek268ee702008-12-12 18:34:08 +0000406 // Skip to the next '#else', '#elif', or #endif.
407 if (CurPTHLexer->SkipBlock()) {
408 // We have reached an #endif. Both the '#' and 'endif' tokens
409 // have been consumed by the PTHLexer. Just pop off the condition level.
410 PPConditionalInfo CondInfo;
411 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000412 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek268ee702008-12-12 18:34:08 +0000413 assert(!InCond && "Can't be skipping if not in a conditional!");
414 break;
415 }
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Ted Kremenek268ee702008-12-12 18:34:08 +0000417 // We have reached a '#else' or '#elif'. Lex the next token to get
418 // the directive flavor.
419 Token Tok;
420 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Ted Kremenek268ee702008-12-12 18:34:08 +0000422 // We can actually look up the IdentifierInfo here since we aren't in
423 // raw mode.
424 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
425
426 if (K == tok::pp_else) {
427 // #else: Enter the else condition. We aren't in a nested condition
428 // since we skip those. We're always in the one matching the last
429 // blocked we skipped.
430 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
431 // Note that we've seen a #else in this conditional.
432 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Ted Kremenek268ee702008-12-12 18:34:08 +0000434 // If the #if block wasn't entered then enter the #else block now.
435 if (!CondInfo.FoundNonSkip) {
436 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Peter Collingbourne84021552011-02-28 02:37:51 +0000438 // Scan until the eod token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000439 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000440 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000441 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Ted Kremenek268ee702008-12-12 18:34:08 +0000443 break;
444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Ted Kremenek268ee702008-12-12 18:34:08 +0000446 // Otherwise skip this block.
447 continue;
448 }
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Ted Kremenek268ee702008-12-12 18:34:08 +0000450 assert(K == tok::pp_elif);
451 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
452
453 // If this is a #elif with a #else before it, report the error.
454 if (CondInfo.FoundElse)
455 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Ted Kremenek268ee702008-12-12 18:34:08 +0000457 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000458 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000459 if (CondInfo.FoundNonSkip)
460 continue;
461
462 // Evaluate the condition of the #elif.
463 IdentifierInfo *IfNDefMacro = 0;
464 CurPTHLexer->ParsingPreprocessorDirective = true;
465 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
466 CurPTHLexer->ParsingPreprocessorDirective = false;
467
468 // If this condition is true, enter it!
469 if (ShouldEnter) {
470 CondInfo.FoundNonSkip = true;
471 break;
472 }
473
474 // Otherwise, skip this block and go to the next one.
475 continue;
476 }
477}
478
Chris Lattner10725092008-03-09 04:17:44 +0000479/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
480/// return null on failure. isAngled indicates whether the file reference is
481/// for system #include's or not (i.e. using <> instead of "").
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000482const FileEntry *Preprocessor::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000483 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000484 bool isAngled,
485 const DirectoryLookup *FromDir,
486 const DirectoryLookup *&CurDir,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000487 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000488 SmallVectorImpl<char> *RelativePath,
489 StringRef *SuggestedModule) {
Chris Lattner10725092008-03-09 04:17:44 +0000490 // If the header lookup mechanism may be relative to the current file, pass in
491 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000492 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000493 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000494 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000495 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000497 // If there is no file entry associated with this file, it must be the
498 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000499 // it won't be scanned for preprocessor directives. If we have the
500 // predefines buffer, resolve #include references (which come from the
501 // -include command line argument) as if they came from the main file, this
502 // affects file lookup etc.
503 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000504 FID = SourceMgr.getMainFileID();
505 CurFileEnt = SourceMgr.getFileEntryForID(FID);
506 }
Chris Lattner10725092008-03-09 04:17:44 +0000507 }
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Chris Lattner10725092008-03-09 04:17:44 +0000509 // Do a standard file entry lookup.
510 CurDir = CurDirLookup;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000511 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +0000512 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000513 SearchPath, RelativePath, SuggestedModule);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000514 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Chris Lattner10725092008-03-09 04:17:44 +0000516 // Otherwise, see if this is a subframework header. If so, this is relative
517 // to one of the headers on the #include stack. Walk the list of the current
518 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000519 // FIXME: SuggestedModule!
Ted Kremenek81d24e12008-11-20 16:19:53 +0000520 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000521 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000522 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek74124942011-04-26 21:50:03 +0000523 SearchPath, RelativePath)))
Chris Lattner10725092008-03-09 04:17:44 +0000524 return FE;
525 }
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner10725092008-03-09 04:17:44 +0000527 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
528 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000529 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000530 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000531 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek74124942011-04-26 21:50:03 +0000532 if ((FE = HeaderInfo.LookupSubframeworkHeader(
533 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattner10725092008-03-09 04:17:44 +0000534 return FE;
535 }
536 }
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattner10725092008-03-09 04:17:44 +0000538 // Otherwise, we really couldn't find the file.
539 return 0;
540}
541
Chris Lattner141e71f2008-03-09 01:54:53 +0000542
543//===----------------------------------------------------------------------===//
544// Preprocessor Directive Handling.
545//===----------------------------------------------------------------------===//
546
547/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000548/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000549/// lexer/preprocessor state, and advances the lexer(s) so that the next token
550/// read is the correct one.
551void Preprocessor::HandleDirective(Token &Result) {
552 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Chris Lattner141e71f2008-03-09 01:54:53 +0000554 // We just parsed a # character at the start of a line, so we're in directive
555 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne84021552011-02-28 02:37:51 +0000556 // EOD token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000557 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattner141e71f2008-03-09 01:54:53 +0000559 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000560
Chris Lattner141e71f2008-03-09 01:54:53 +0000561 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000562 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000563 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000564 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Chris Lattner42aa16c2009-03-18 21:00:25 +0000566 // Save the '#' token in case we need to return it later.
567 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattner141e71f2008-03-09 01:54:53 +0000569 // Read the next token, the directive flavor. This isn't expanded due to
570 // C99 6.10.3p8.
571 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Chris Lattner141e71f2008-03-09 01:54:53 +0000573 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
574 // #define A(x) #x
575 // A(abc
576 // #warning blah
577 // def)
578 // If so, the user is relying on non-portable behavior, emit a diagnostic.
579 if (InMacroArgs)
580 Diag(Result, diag::ext_embedded_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Chris Lattner141e71f2008-03-09 01:54:53 +0000582TryAgain:
583 switch (Result.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000584 case tok::eod:
Chris Lattner141e71f2008-03-09 01:54:53 +0000585 return; // null directive.
586 case tok::comment:
587 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
588 LexUnexpandedToken(Result);
589 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000590 case tok::code_completion:
591 if (CodeComplete)
592 CodeComplete->CodeCompleteDirective(
593 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000594 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000595 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000596 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000597 if (getLangOptions().AsmPreprocessor)
598 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000599 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000600 default:
601 IdentifierInfo *II = Result.getIdentifierInfo();
602 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Chris Lattner141e71f2008-03-09 01:54:53 +0000604 // Ask what the preprocessor keyword ID is.
605 switch (II->getPPKeywordID()) {
606 default: break;
607 // C99 6.10.1 - Conditional Inclusion.
608 case tok::pp_if:
609 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
610 case tok::pp_ifdef:
611 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
612 case tok::pp_ifndef:
613 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
614 case tok::pp_elif:
615 return HandleElifDirective(Result);
616 case tok::pp_else:
617 return HandleElseDirective(Result);
618 case tok::pp_endif:
619 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattner141e71f2008-03-09 01:54:53 +0000621 // C99 6.10.2 - Source File Inclusion.
622 case tok::pp_include:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000623 // Handle #include.
624 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000625 case tok::pp___include_macros:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000626 // Handle -imacros.
627 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattner141e71f2008-03-09 01:54:53 +0000629 // C99 6.10.3 - Macro Replacement.
630 case tok::pp_define:
631 return HandleDefineDirective(Result);
632 case tok::pp_undef:
633 return HandleUndefDirective(Result);
634
635 // C99 6.10.4 - Line Control.
636 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000637 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattner141e71f2008-03-09 01:54:53 +0000639 // C99 6.10.5 - Error Directive.
640 case tok::pp_error:
641 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Chris Lattner141e71f2008-03-09 01:54:53 +0000643 // C99 6.10.6 - Pragma Directive.
644 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000645 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattner141e71f2008-03-09 01:54:53 +0000647 // GNU Extensions.
648 case tok::pp_import:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000649 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000650 case tok::pp_include_next:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000651 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Chris Lattner141e71f2008-03-09 01:54:53 +0000653 case tok::pp_warning:
654 Diag(Result, diag::ext_pp_warning_directive);
655 return HandleUserDiagnosticDirective(Result, true);
656 case tok::pp_ident:
657 return HandleIdentSCCSDirective(Result);
658 case tok::pp_sccs:
659 return HandleIdentSCCSDirective(Result);
660 case tok::pp_assert:
661 //isExtension = true; // FIXME: implement #assert
662 break;
663 case tok::pp_unassert:
664 //isExtension = true; // FIXME: implement #unassert
665 break;
Douglas Gregor7143aab2011-09-01 17:04:32 +0000666
667 case tok::pp___export_macro__:
668 return HandleMacroExportDirective(Result);
Douglas Gregoraa93a872011-10-17 15:32:29 +0000669 case tok::pp___private_macro__:
670 return HandleMacroPrivateDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000671 }
672 break;
673 }
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Chris Lattner42aa16c2009-03-18 21:00:25 +0000675 // If this is a .S file, treat unknown # directives as non-preprocessor
676 // directives. This is important because # may be a comment or introduce
677 // various pseudo-ops. Just return the # token and push back the following
678 // token to be lexed next time.
679 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000680 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000681 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000682 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000683 Toks[1] = Result;
Chris Lattnerba3ca522011-01-06 05:01:51 +0000684
685 // If the second token is a hashhash token, then we need to translate it to
686 // unknown so the token lexer doesn't try to perform token pasting.
687 if (Result.is(tok::hashhash))
688 Toks[1].setKind(tok::unknown);
689
Chris Lattner42aa16c2009-03-18 21:00:25 +0000690 // Enter this token stream so that we re-lex the tokens. Make sure to
691 // enable macro expansion, in case the token after the # is an identifier
692 // that is expanded.
693 EnterTokenStream(Toks, 2, false, true);
694 return;
695 }
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattner141e71f2008-03-09 01:54:53 +0000697 // If we reached here, the preprocessing token is not valid!
698 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Chris Lattner141e71f2008-03-09 01:54:53 +0000700 // Read the rest of the PP line.
701 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattner141e71f2008-03-09 01:54:53 +0000703 // Okay, we're done parsing the directive.
704}
705
Chris Lattner478a18e2009-01-26 06:19:46 +0000706/// GetLineValue - Convert a numeric token into an unsigned value, emitting
707/// Diagnostic DiagID if it is invalid, and returning the value in Val.
708static bool GetLineValue(Token &DigitTok, unsigned &Val,
709 unsigned DiagID, Preprocessor &PP) {
710 if (DigitTok.isNot(tok::numeric_constant)) {
711 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Peter Collingbourne84021552011-02-28 02:37:51 +0000713 if (DigitTok.isNot(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000714 PP.DiscardUntilEndOfDirective();
715 return true;
716 }
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattner478a18e2009-01-26 06:19:46 +0000718 llvm::SmallString<64> IntegerBuffer;
719 IntegerBuffer.resize(DigitTok.getLength());
720 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000721 bool Invalid = false;
722 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
723 if (Invalid)
724 return true;
725
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000726 // Verify that we have a simple digit-sequence, and compute the value. This
727 // is always a simple digit string computed in decimal, so we do this manually
728 // here.
729 Val = 0;
730 for (unsigned i = 0; i != ActualLength; ++i) {
731 if (!isdigit(DigitTokBegin[i])) {
732 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
733 diag::err_pp_line_digit_sequence);
734 PP.DiscardUntilEndOfDirective();
735 return true;
736 }
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000738 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
739 if (NextVal < Val) { // overflow.
740 PP.Diag(DigitTok, DiagID);
741 PP.DiscardUntilEndOfDirective();
742 return true;
743 }
744 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000745 }
Mike Stump1eb44332009-09-09 15:08:12 +0000746
747 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000748 if (Val == 0) {
749 PP.Diag(DigitTok, DiagID);
750 PP.DiscardUntilEndOfDirective();
751 return true;
752 }
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000754 if (DigitTokBegin[0] == '0')
755 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Chris Lattner478a18e2009-01-26 06:19:46 +0000757 return false;
758}
759
Mike Stump1eb44332009-09-09 15:08:12 +0000760/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000761/// acceptable forms are:
762/// # line digit-sequence
763/// # line digit-sequence "s-char-sequence"
764void Preprocessor::HandleLineDirective(Token &Tok) {
765 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
766 // expanded.
767 Token DigitTok;
768 Lex(DigitTok);
769
Chris Lattner359cc442009-01-26 05:29:08 +0000770 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000771 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000772 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000773 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000774
Chris Lattner478a18e2009-01-26 06:19:46 +0000775 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
776 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman158ebfb2011-10-10 23:35:28 +0000777 unsigned LineLimit = 32768U;
778 if (Features.C99 || Features.CPlusPlus0x)
779 LineLimit = 2147483648U;
Chris Lattner359cc442009-01-26 05:29:08 +0000780 if (LineNo >= LineLimit)
781 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith661a9962011-10-15 01:18:56 +0000782 else if (Features.CPlusPlus0x && LineNo >= 32768U)
783 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Chris Lattner5b9a5042009-01-26 07:57:50 +0000785 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000786 Token StrTok;
787 Lex(StrTok);
788
Peter Collingbourne84021552011-02-28 02:37:51 +0000789 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
790 // string followed by eod.
791 if (StrTok.is(tok::eod))
Chris Lattner359cc442009-01-26 05:29:08 +0000792 ; // ok
793 else if (StrTok.isNot(tok::string_literal)) {
794 Diag(StrTok, diag::err_pp_line_invalid_filename);
795 DiscardUntilEndOfDirective();
796 return;
797 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000798 // Parse and validate the string, converting it into a unique ID.
799 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000800 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000801 if (Literal.hadError)
802 return DiscardUntilEndOfDirective();
803 if (Literal.Pascal) {
804 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
805 return DiscardUntilEndOfDirective();
806 }
Jay Foad65aa6882011-06-21 15:13:30 +0000807 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Peter Collingbourne84021552011-02-28 02:37:51 +0000809 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattnerab82f412009-04-17 23:30:53 +0000810 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
811 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000812 }
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattner4c4ea172009-02-03 21:52:55 +0000814 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Chris Lattner16629382009-03-27 17:13:49 +0000816 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000817 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
818 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000819 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000820}
821
Chris Lattner478a18e2009-01-26 06:19:46 +0000822/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
823/// marker directive.
824static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
825 bool &IsSystemHeader, bool &IsExternCHeader,
826 Preprocessor &PP) {
827 unsigned FlagVal;
828 Token FlagTok;
829 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000830 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000831 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
832 return true;
833
834 if (FlagVal == 1) {
835 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Chris Lattner478a18e2009-01-26 06:19:46 +0000837 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000838 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000839 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
840 return true;
841 } else if (FlagVal == 2) {
842 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Chris Lattner137b6a62009-02-04 06:25:26 +0000844 SourceManager &SM = PP.getSourceManager();
845 // If we are leaving the current presumed file, check to make sure the
846 // presumed include stack isn't empty!
847 FileID CurFileID =
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000848 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner137b6a62009-02-04 06:25:26 +0000849 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000850 if (PLoc.isInvalid())
851 return true;
852
Chris Lattner137b6a62009-02-04 06:25:26 +0000853 // If there is no include loc (main file) or if the include loc is in a
854 // different physical file, then we aren't in a "1" line marker flag region.
855 SourceLocation IncLoc = PLoc.getIncludeLoc();
856 if (IncLoc.isInvalid() ||
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000857 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner137b6a62009-02-04 06:25:26 +0000858 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
859 PP.DiscardUntilEndOfDirective();
860 return true;
861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Chris Lattner478a18e2009-01-26 06:19:46 +0000863 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000864 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000865 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
866 return true;
867 }
868
869 // We must have 3 if there are still flags.
870 if (FlagVal != 3) {
871 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000872 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000873 return true;
874 }
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Chris Lattner478a18e2009-01-26 06:19:46 +0000876 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Chris Lattner478a18e2009-01-26 06:19:46 +0000878 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000879 if (FlagTok.is(tok::eod)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000880 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000881 return true;
882
883 // We must have 4 if there is yet another flag.
884 if (FlagVal != 4) {
885 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000886 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000887 return true;
888 }
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Chris Lattner478a18e2009-01-26 06:19:46 +0000890 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Chris Lattner478a18e2009-01-26 06:19:46 +0000892 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000893 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000894
895 // There are no more valid flags here.
896 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000897 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000898 return true;
899}
900
901/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
902/// one of the following forms:
903///
904/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000905/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000906/// # 42 "file" ('1' | '2')? '3' '4'?
907///
908void Preprocessor::HandleDigitDirective(Token &DigitTok) {
909 // Validate the number and convert it to an unsigned. GNU does not have a
910 // line # limit other than it fit in 32-bits.
911 unsigned LineNo;
912 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
913 *this))
914 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Chris Lattner478a18e2009-01-26 06:19:46 +0000916 Token StrTok;
917 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Chris Lattner478a18e2009-01-26 06:19:46 +0000919 bool IsFileEntry = false, IsFileExit = false;
920 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000921 int FilenameID = -1;
922
Peter Collingbourne84021552011-02-28 02:37:51 +0000923 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
924 // string followed by eod.
925 if (StrTok.is(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000926 ; // ok
927 else if (StrTok.isNot(tok::string_literal)) {
928 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000929 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000930 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000931 // Parse and validate the string, converting it into a unique ID.
932 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000933 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000934 if (Literal.hadError)
935 return DiscardUntilEndOfDirective();
936 if (Literal.Pascal) {
937 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
938 return DiscardUntilEndOfDirective();
939 }
Jay Foad65aa6882011-06-21 15:13:30 +0000940 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Chris Lattner478a18e2009-01-26 06:19:46 +0000942 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000943 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000944 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000945 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000946 }
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Chris Lattner9d79eba2009-02-04 05:21:58 +0000948 // Create a line note with this information.
949 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000950 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000951 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Chris Lattner16629382009-03-27 17:13:49 +0000953 // If the preprocessor has callbacks installed, notify them of the #line
954 // change. This is used so that the line marker comes out in -E mode for
955 // example.
956 if (Callbacks) {
957 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
958 if (IsFileEntry)
959 Reason = PPCallbacks::EnterFile;
960 else if (IsFileExit)
961 Reason = PPCallbacks::ExitFile;
962 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
963 if (IsExternCHeader)
964 FileKind = SrcMgr::C_ExternCSystem;
965 else if (IsSystemHeader)
966 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Chris Lattner86d0ef72010-04-14 04:28:50 +0000968 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000969 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000970}
971
972
Chris Lattner099dd052009-01-26 05:30:54 +0000973/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
974///
Mike Stump1eb44332009-09-09 15:08:12 +0000975void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000976 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000977 // PTH doesn't emit #warning or #error directives.
978 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000979 return CurPTHLexer->DiscardToEndOfLine();
980
Chris Lattner141e71f2008-03-09 01:54:53 +0000981 // Read the rest of the line raw. We do this because we don't want macros
982 // to be expanded and we don't require that the tokens be valid preprocessing
983 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
984 // collapse multiple consequtive white space between tokens, but this isn't
985 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000986 std::string Message = CurLexer->ReadToEndOfLine();
987 if (isWarning)
988 Diag(Tok, diag::pp_hash_warning) << Message;
989 else
990 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000991}
992
993/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
994///
995void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
996 // Yes, this directive is an extension.
997 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner141e71f2008-03-09 01:54:53 +0000999 // Read the string argument.
1000 Token StrTok;
1001 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Chris Lattner141e71f2008-03-09 01:54:53 +00001003 // If the token kind isn't a string, it's a malformed directive.
1004 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +00001005 StrTok.isNot(tok::wide_string_literal)) {
1006 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne84021552011-02-28 02:37:51 +00001007 if (StrTok.isNot(tok::eod))
Chris Lattner099dd052009-01-26 05:30:54 +00001008 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +00001009 return;
1010 }
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Peter Collingbourne84021552011-02-28 02:37:51 +00001012 // Verify that there is nothing after the string, other than EOD.
Chris Lattner35410d52009-04-14 05:07:49 +00001013 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +00001014
Douglas Gregor453091c2010-03-16 22:30:13 +00001015 if (Callbacks) {
1016 bool Invalid = false;
1017 std::string Str = getSpelling(StrTok, &Invalid);
1018 if (!Invalid)
1019 Callbacks->Ident(Tok.getLocation(), Str);
1020 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001021}
1022
Douglas Gregor7143aab2011-09-01 17:04:32 +00001023/// \brief Handle a #__export_macro__ directive.
1024void Preprocessor::HandleMacroExportDirective(Token &Tok) {
1025 Token MacroNameTok;
1026 ReadMacroName(MacroNameTok, 2);
1027
1028 // Error reading macro name? If so, diagnostic already issued.
1029 if (MacroNameTok.is(tok::eod))
1030 return;
1031
1032 // Check to see if this is the last token on the #__export_macro__ line.
1033 CheckEndOfDirective("__export_macro__");
1034
1035 // Okay, we finally have a valid identifier to undef.
1036 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1037
1038 // If the macro is not defined, this is an error.
1039 if (MI == 0) {
Douglas Gregoraa93a872011-10-17 15:32:29 +00001040 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor7143aab2011-09-01 17:04:32 +00001041 << MacroNameTok.getIdentifierInfo();
1042 return;
1043 }
1044
1045 // Note that this macro has now been exported.
Douglas Gregoraa93a872011-10-17 15:32:29 +00001046 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1047
1048 // If this macro definition came from a PCH file, mark it
1049 // as having changed since serialization.
1050 if (MI->isFromAST())
1051 MI->setChangedAfterLoad();
1052}
1053
1054/// \brief Handle a #__private_macro__ directive.
1055void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1056 Token MacroNameTok;
1057 ReadMacroName(MacroNameTok, 2);
1058
1059 // Error reading macro name? If so, diagnostic already issued.
1060 if (MacroNameTok.is(tok::eod))
1061 return;
1062
1063 // Check to see if this is the last token on the #__private_macro__ line.
1064 CheckEndOfDirective("__private_macro__");
1065
1066 // Okay, we finally have a valid identifier to undef.
1067 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1068
1069 // If the macro is not defined, this is an error.
1070 if (MI == 0) {
1071 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1072 << MacroNameTok.getIdentifierInfo();
1073 return;
1074 }
1075
1076 // Note that this macro has now been marked private.
1077 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor7143aab2011-09-01 17:04:32 +00001078
1079 // If this macro definition came from a PCH file, mark it
1080 // as having changed since serialization.
1081 if (MI->isFromAST())
1082 MI->setChangedAfterLoad();
1083}
1084
Chris Lattner141e71f2008-03-09 01:54:53 +00001085//===----------------------------------------------------------------------===//
1086// Preprocessor Include Directive Handling.
1087//===----------------------------------------------------------------------===//
1088
1089/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1090/// checked and spelled filename, e.g. as an operand of #include. This returns
1091/// true if the input filename was in <>'s or false if it were in ""'s. The
1092/// caller is expected to provide a buffer that is large enough to hold the
1093/// spelling of the filename, but is also expected to handle the case when
1094/// this method decides to use a different buffer.
1095bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001096 StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001097 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +00001098 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Chris Lattner141e71f2008-03-09 01:54:53 +00001100 // Make sure the filename is <x> or "x".
1101 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +00001102 if (Buffer[0] == '<') {
1103 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001104 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001105 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001106 return true;
1107 }
1108 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +00001109 } else if (Buffer[0] == '"') {
1110 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001111 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001112 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001113 return true;
1114 }
1115 isAngled = false;
1116 } else {
1117 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001118 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001119 return true;
1120 }
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Chris Lattner141e71f2008-03-09 01:54:53 +00001122 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +00001123 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001124 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001125 Buffer = StringRef();
Chris Lattnera1394812010-01-10 01:35:12 +00001126 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001127 }
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Chris Lattner141e71f2008-03-09 01:54:53 +00001129 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001130 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001131 return isAngled;
1132}
1133
1134/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1135/// from a macro as multiple tokens, which need to be glued together. This
1136/// occurs for code like:
1137/// #define FOO <a/b.h>
1138/// #include FOO
1139/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1140///
1141/// This code concatenates and consumes tokens up to the '>' token. It returns
1142/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne84021552011-02-28 02:37:51 +00001143/// the EOD marker.
John Thompsona28cc092009-10-30 13:49:06 +00001144bool Preprocessor::ConcatenateIncludeName(
Douglas Gregorecdcb882010-10-20 22:00:55 +00001145 llvm::SmallString<128> &FilenameBuffer,
1146 SourceLocation &End) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001147 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001148
John Thompsona28cc092009-10-30 13:49:06 +00001149 Lex(CurTok);
Peter Collingbourne84021552011-02-28 02:37:51 +00001150 while (CurTok.isNot(tok::eod)) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001151 End = CurTok.getLocation();
1152
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001153 // FIXME: Provide code completion for #includes.
1154 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001155 setCodeCompletionReached();
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001156 Lex(CurTok);
1157 continue;
1158 }
1159
Chris Lattner141e71f2008-03-09 01:54:53 +00001160 // Append the spelling of this token to the buffer. If there was a space
1161 // before it, add it now.
1162 if (CurTok.hasLeadingSpace())
1163 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Chris Lattner141e71f2008-03-09 01:54:53 +00001165 // Get the spelling of the token, directly into FilenameBuffer if possible.
1166 unsigned PreAppendSize = FilenameBuffer.size();
1167 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Chris Lattner141e71f2008-03-09 01:54:53 +00001169 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001170 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Chris Lattner141e71f2008-03-09 01:54:53 +00001172 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1173 if (BufPtr != &FilenameBuffer[PreAppendSize])
1174 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Chris Lattner141e71f2008-03-09 01:54:53 +00001176 // Resize FilenameBuffer to the correct size.
1177 if (CurTok.getLength() != ActualLen)
1178 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Chris Lattner141e71f2008-03-09 01:54:53 +00001180 // If we found the '>' marker, return success.
1181 if (CurTok.is(tok::greater))
1182 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001183
John Thompsona28cc092009-10-30 13:49:06 +00001184 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001185 }
1186
Peter Collingbourne84021552011-02-28 02:37:51 +00001187 // If we hit the eod marker, emit an error and return true so that the caller
1188 // knows the EOD has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001189 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001190 return true;
1191}
1192
1193/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1194/// file to be included from the lexer, then include it! This is a common
1195/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001196/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001197/// specifies the file to start searching from.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001198void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1199 Token &IncludeTok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001200 const DirectoryLookup *LookupFrom,
1201 bool isImport) {
1202
1203 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001204 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Chris Lattner141e71f2008-03-09 01:54:53 +00001206 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001207 llvm::SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001208 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001209 SourceLocation End;
1210
Chris Lattner141e71f2008-03-09 01:54:53 +00001211 switch (FilenameTok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +00001212 case tok::eod:
1213 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattner141e71f2008-03-09 01:54:53 +00001214 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Chris Lattner141e71f2008-03-09 01:54:53 +00001216 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001217 case tok::string_literal:
1218 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregorecdcb882010-10-20 22:00:55 +00001219 End = FilenameTok.getLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001220 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Chris Lattner141e71f2008-03-09 01:54:53 +00001222 case tok::less:
1223 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1224 // case, glue the tokens together into FilenameBuffer and interpret those.
1225 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +00001226 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne84021552011-02-28 02:37:51 +00001227 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001228 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001229 break;
1230 default:
1231 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1232 DiscardUntilEndOfDirective();
1233 return;
1234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001236 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001237 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001238 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1239 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001240 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001241 DiscardUntilEndOfDirective();
1242 return;
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Peter Collingbourne84021552011-02-28 02:37:51 +00001245 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001246 // we allow macros that expand to nothing after the filename, because this
1247 // falls into the category of "#include pp-tokens new-line" specified in
1248 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001249 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001250
1251 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001252 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1253 Diag(FilenameTok, diag::err_pp_include_too_deep);
1254 return;
1255 }
Mike Stump1eb44332009-09-09 15:08:12 +00001256
John McCall8dfac0b2011-09-30 05:12:12 +00001257 // Complain about attempts to #include files in an audit pragma.
1258 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1259 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1260 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1261
1262 // Immediately leave the pragma.
1263 PragmaARCCFCodeAuditedLoc = SourceLocation();
1264 }
1265
Chris Lattner141e71f2008-03-09 01:54:53 +00001266 // Search include directories.
1267 const DirectoryLookup *CurDir;
Manuel Klimek74124942011-04-26 21:50:03 +00001268 llvm::SmallString<1024> SearchPath;
1269 llvm::SmallString<1024> RelativePath;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001270 // We get the raw path only if we have 'Callbacks' to which we later pass
1271 // the path.
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001272 StringRef SuggestedModule;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001273 const FileEntry *File = LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +00001274 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001275 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
1276 AutoModuleImport? &SuggestedModule : 0);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001277
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001278 // If we are supposed to import a module rather than including the header,
1279 // do so now.
1280 if (!SuggestedModule.empty()) {
1281 TheModuleLoader.loadModule(IncludeTok.getLocation(),
1282 Identifiers.get(SuggestedModule),
1283 FilenameTok.getLocation());
1284 return;
1285 }
1286
Douglas Gregorecdcb882010-10-20 22:00:55 +00001287 // Notify the callback object that we've seen an inclusion directive.
1288 if (Callbacks)
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001289 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
Manuel Klimek74124942011-04-26 21:50:03 +00001290 End, SearchPath, RelativePath);
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001291
Peter Collingbournebb527862011-07-12 19:35:15 +00001292 if (File == 0) {
Eli Friedmanf84139a2011-08-30 23:07:51 +00001293 if (!SuppressIncludeNotFoundError)
1294 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Peter Collingbournebb527862011-07-12 19:35:15 +00001295 return;
1296 }
1297
Chris Lattner72181832008-09-26 20:12:23 +00001298 // The #included file will be considered to be a system header if either it is
1299 // in a system include directory, or if the #includer is a system include
1300 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001301 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001302 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001303 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001305 // Ask HeaderInfo if we should enter this #include file. If not, #including
1306 // this file will have no effect.
1307 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001308 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001309 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001310 return;
1311 }
1312
Chris Lattner141e71f2008-03-09 01:54:53 +00001313 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001314 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1315 FileCharacter);
Peter Collingbourned57b7ff2011-06-30 16:41:03 +00001316 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattner141e71f2008-03-09 01:54:53 +00001317
1318 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001319 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001320}
1321
1322/// HandleIncludeNextDirective - Implements #include_next.
1323///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001324void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1325 Token &IncludeNextTok) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001326 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001327
Chris Lattner141e71f2008-03-09 01:54:53 +00001328 // #include_next is like #include, except that we start searching after
1329 // the current found directory. If we can't do this, issue a
1330 // diagnostic.
1331 const DirectoryLookup *Lookup = CurDirLookup;
1332 if (isInPrimaryFile()) {
1333 Lookup = 0;
1334 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1335 } else if (Lookup == 0) {
1336 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1337 } else {
1338 // Start looking up in the next directory.
1339 ++Lookup;
1340 }
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Douglas Gregorecdcb882010-10-20 22:00:55 +00001342 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattner141e71f2008-03-09 01:54:53 +00001343}
1344
1345/// HandleImportDirective - Implements #import.
1346///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001347void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1348 Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001349 if (!Features.ObjC1) // #import is standard for ObjC.
1350 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Douglas Gregorecdcb882010-10-20 22:00:55 +00001352 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001353}
1354
Chris Lattnerde076652009-04-08 18:46:40 +00001355/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1356/// pseudo directive in the predefines buffer. This handles it by sucking all
1357/// tokens through the preprocessor and discarding them (only keeping the side
1358/// effects on the preprocessor).
Douglas Gregorecdcb882010-10-20 22:00:55 +00001359void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1360 Token &IncludeMacrosTok) {
Chris Lattnerde076652009-04-08 18:46:40 +00001361 // This directive should only occur in the predefines buffer. If not, emit an
1362 // error and reject it.
1363 SourceLocation Loc = IncludeMacrosTok.getLocation();
1364 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1365 Diag(IncludeMacrosTok.getLocation(),
1366 diag::pp_include_macros_out_of_predefines);
1367 DiscardUntilEndOfDirective();
1368 return;
1369 }
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Chris Lattnerfd105112009-04-08 20:53:24 +00001371 // Treat this as a normal #include for checking purposes. If this is
1372 // successful, it will push a new lexer onto the include stack.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001373 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Chris Lattnerfd105112009-04-08 20:53:24 +00001375 Token TmpTok;
1376 do {
1377 Lex(TmpTok);
1378 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1379 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001380}
1381
Chris Lattner141e71f2008-03-09 01:54:53 +00001382//===----------------------------------------------------------------------===//
1383// Preprocessor Macro Directive Handling.
1384//===----------------------------------------------------------------------===//
1385
1386/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1387/// definition has just been read. Lex the rest of the arguments and the
1388/// closing ), updating MI with what we learn. Return true if an error occurs
1389/// parsing the arg list.
1390bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001391 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Chris Lattner141e71f2008-03-09 01:54:53 +00001393 Token Tok;
1394 while (1) {
1395 LexUnexpandedToken(Tok);
1396 switch (Tok.getKind()) {
1397 case tok::r_paren:
1398 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001399 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001400 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001401 // Otherwise we have #define FOO(A,)
1402 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1403 return true;
1404 case tok::ellipsis: // #define X(... -> C99 varargs
Richard Smith661a9962011-10-15 01:18:56 +00001405 if (!Features.C99)
1406 Diag(Tok, Features.CPlusPlus0x ?
1407 diag::warn_cxx98_compat_variadic_macro :
1408 diag::ext_variadic_macro);
Chris Lattner141e71f2008-03-09 01:54:53 +00001409
1410 // Lex the token after the identifier.
1411 LexUnexpandedToken(Tok);
1412 if (Tok.isNot(tok::r_paren)) {
1413 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1414 return true;
1415 }
1416 // Add the __VA_ARGS__ identifier as an argument.
1417 Arguments.push_back(Ident__VA_ARGS__);
1418 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001419 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001420 return false;
Peter Collingbourne84021552011-02-28 02:37:51 +00001421 case tok::eod: // #define X(
Chris Lattner141e71f2008-03-09 01:54:53 +00001422 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1423 return true;
1424 default:
1425 // Handle keywords and identifiers here to accept things like
1426 // #define Foo(for) for.
1427 IdentifierInfo *II = Tok.getIdentifierInfo();
1428 if (II == 0) {
1429 // #define X(1
1430 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1431 return true;
1432 }
1433
1434 // If this is already used as an argument, it is used multiple times (e.g.
1435 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001436 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001437 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001438 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001439 return true;
1440 }
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Chris Lattner141e71f2008-03-09 01:54:53 +00001442 // Add the argument to the macro info.
1443 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Chris Lattner141e71f2008-03-09 01:54:53 +00001445 // Lex the token after the identifier.
1446 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Chris Lattner141e71f2008-03-09 01:54:53 +00001448 switch (Tok.getKind()) {
1449 default: // #define X(A B
1450 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1451 return true;
1452 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001453 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001454 return false;
1455 case tok::comma: // #define X(A,
1456 break;
1457 case tok::ellipsis: // #define X(A... -> GCC extension
1458 // Diagnose extension.
1459 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Chris Lattner141e71f2008-03-09 01:54:53 +00001461 // Lex the token after the identifier.
1462 LexUnexpandedToken(Tok);
1463 if (Tok.isNot(tok::r_paren)) {
1464 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1465 return true;
1466 }
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Chris Lattner141e71f2008-03-09 01:54:53 +00001468 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001469 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001470 return false;
1471 }
1472 }
1473 }
1474}
1475
1476/// HandleDefineDirective - Implements #define. This consumes the entire macro
1477/// line then lets the caller lex the next real token.
1478void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1479 ++NumDefined;
1480
1481 Token MacroNameTok;
1482 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Chris Lattner141e71f2008-03-09 01:54:53 +00001484 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001485 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001486 return;
1487
Chris Lattner2451b522009-04-21 04:46:33 +00001488 Token LastTok = MacroNameTok;
1489
Chris Lattner141e71f2008-03-09 01:54:53 +00001490 // If we are supposed to keep comments in #defines, reenable comment saving
1491 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001492 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Chris Lattner141e71f2008-03-09 01:54:53 +00001494 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001495 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Chris Lattner141e71f2008-03-09 01:54:53 +00001497 Token Tok;
1498 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Chris Lattner141e71f2008-03-09 01:54:53 +00001500 // If this is a function-like macro definition, parse the argument list,
1501 // marking each of the identifiers as being used as macro arguments. Also,
1502 // check other constraints on the first token of the macro body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001503 if (Tok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001504 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001505 } else if (Tok.hasLeadingSpace()) {
1506 // This is a normal token with leading space. Clear the leading space
1507 // marker on the first token to get proper expansion.
1508 Tok.clearFlag(Token::LeadingSpace);
1509 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001510 // This is a function-like macro definition. Read the argument list.
1511 MI->setIsFunctionLike();
1512 if (ReadMacroDefinitionArgList(MI)) {
1513 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001514 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001515 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001516 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001517 DiscardUntilEndOfDirective();
1518 return;
1519 }
1520
Chris Lattner8fde5972009-04-19 18:26:34 +00001521 // If this is a definition of a variadic C99 function-like macro, not using
1522 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Chris Lattner8fde5972009-04-19 18:26:34 +00001524 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1525 // This gets unpoisoned where it is allowed.
1526 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1527 if (MI->isC99Varargs())
1528 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Chris Lattner141e71f2008-03-09 01:54:53 +00001530 // Read the first token after the arg list for down below.
1531 LexUnexpandedToken(Tok);
Eli Friedman158ebfb2011-10-10 23:35:28 +00001532 } else if (Features.C99 || Features.CPlusPlus0x) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001533 // C99 requires whitespace between the macro definition and the body. Emit
1534 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001535 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001536 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001537 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1538 // first character of a replacement list is not a character required by
1539 // subclause 5.2.1, then there shall be white-space separation between the
1540 // identifier and the replacement list.". 5.2.1 lists this set:
1541 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1542 // is irrelevant here.
1543 bool isInvalid = false;
1544 if (Tok.is(tok::at)) // @ is not in the list above.
1545 isInvalid = true;
1546 else if (Tok.is(tok::unknown)) {
1547 // If we have an unknown token, it is something strange like "`". Since
1548 // all of valid characters would have lexed into a single character
1549 // token of some sort, we know this is not a valid case.
1550 isInvalid = true;
1551 }
1552 if (isInvalid)
1553 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1554 else
1555 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001556 }
Chris Lattner2451b522009-04-21 04:46:33 +00001557
Peter Collingbourne84021552011-02-28 02:37:51 +00001558 if (!Tok.is(tok::eod))
Chris Lattner2451b522009-04-21 04:46:33 +00001559 LastTok = Tok;
1560
Chris Lattner141e71f2008-03-09 01:54:53 +00001561 // Read the rest of the macro body.
1562 if (MI->isObjectLike()) {
1563 // Object-like macros are very simple, just read their body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001564 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001565 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001566 MI->AddTokenToBody(Tok);
1567 // Get the next token of the macro.
1568 LexUnexpandedToken(Tok);
1569 }
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Chris Lattner141e71f2008-03-09 01:54:53 +00001571 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001572 // Otherwise, read the body of a function-like macro. While we are at it,
1573 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1574 // parameters in function-like macro expansions.
Peter Collingbourne84021552011-02-28 02:37:51 +00001575 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001576 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001577
Chris Lattner141e71f2008-03-09 01:54:53 +00001578 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001579 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Chris Lattner141e71f2008-03-09 01:54:53 +00001581 // Get the next token of the macro.
1582 LexUnexpandedToken(Tok);
1583 continue;
1584 }
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Chris Lattner141e71f2008-03-09 01:54:53 +00001586 // Get the next token of the macro.
1587 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Chris Lattner32404692009-05-25 17:16:10 +00001589 // Check for a valid macro arg identifier.
1590 if (Tok.getIdentifierInfo() == 0 ||
1591 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1592
1593 // If this is assembler-with-cpp mode, we accept random gibberish after
1594 // the '#' because '#' is often a comment character. However, change
1595 // the kind of the token to tok::unknown so that the preprocessor isn't
1596 // confused.
Peter Collingbourne84021552011-02-28 02:37:51 +00001597 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner32404692009-05-25 17:16:10 +00001598 LastTok.setKind(tok::unknown);
1599 } else {
1600 Diag(Tok, diag::err_pp_stringize_not_parameter);
1601 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Chris Lattner32404692009-05-25 17:16:10 +00001603 // Disable __VA_ARGS__ again.
1604 Ident__VA_ARGS__->setIsPoisoned(true);
1605 return;
1606 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001607 }
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Chris Lattner32404692009-05-25 17:16:10 +00001609 // Things look ok, add the '#' and param name tokens to the macro.
1610 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001611 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001612 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Chris Lattner141e71f2008-03-09 01:54:53 +00001614 // Get the next token of the macro.
1615 LexUnexpandedToken(Tok);
1616 }
1617 }
Mike Stump1eb44332009-09-09 15:08:12 +00001618
1619
Chris Lattner141e71f2008-03-09 01:54:53 +00001620 // Disable __VA_ARGS__ again.
1621 Ident__VA_ARGS__->setIsPoisoned(true);
1622
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001623 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattner141e71f2008-03-09 01:54:53 +00001624 // replacement list.
1625 unsigned NumTokens = MI->getNumTokens();
1626 if (NumTokens != 0) {
1627 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1628 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001629 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001630 return;
1631 }
1632 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1633 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001634 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001635 return;
1636 }
1637 }
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Chris Lattner2451b522009-04-21 04:46:33 +00001639 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Chris Lattner141e71f2008-03-09 01:54:53 +00001641 // Finally, if this identifier already had a macro defined for it, verify that
1642 // the macro bodies are identical and free the old definition.
1643 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001644 // It is very common for system headers to have tons of macro redefinitions
1645 // and for warnings to be disabled in system headers. If this is the case,
1646 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001647 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001648 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001649 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner41c3ae12009-01-16 19:50:11 +00001650 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001651
Chris Lattnerf47724b2010-08-17 15:55:45 +00001652 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001653 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001654 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001655 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001656 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1657 << MacroNameTok.getIdentifierInfo();
1658 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1659 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001660 }
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001661 if (OtherMI->isWarnIfUnused())
1662 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek0ea76722008-12-15 19:56:42 +00001663 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001664 }
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Chris Lattner141e71f2008-03-09 01:54:53 +00001666 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001668 assert(!MI->isUsed());
1669 // If we need warning for not using the macro, add its location in the
1670 // warn-because-unused-macro set. If it gets used it will be removed from set.
1671 if (isInPrimaryFile() && // don't warn for include'd macros.
1672 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikied6471f72011-09-25 23:23:43 +00001673 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001674 MI->setIsWarnIfUnused(true);
1675 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1676 }
1677
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001678 // If the callbacks want to know, tell them about the macro definition.
1679 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001680 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001681}
1682
1683/// HandleUndefDirective - Implements #undef.
1684///
1685void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1686 ++NumUndefined;
1687
1688 Token MacroNameTok;
1689 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Chris Lattner141e71f2008-03-09 01:54:53 +00001691 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001692 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001693 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Chris Lattner141e71f2008-03-09 01:54:53 +00001695 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001696 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Chris Lattner141e71f2008-03-09 01:54:53 +00001698 // Okay, we finally have a valid identifier to undef.
1699 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Chris Lattner141e71f2008-03-09 01:54:53 +00001701 // If the macro is not defined, this is a noop undef, just return.
1702 if (MI == 0) return;
1703
Argyrios Kyrtzidis1f8dcfc2011-07-11 20:39:47 +00001704 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattner141e71f2008-03-09 01:54:53 +00001705 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001706
1707 // If the callbacks want to know, tell them about the macro #undef.
1708 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001709 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001710
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001711 if (MI->isWarnIfUnused())
1712 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1713
Chris Lattner141e71f2008-03-09 01:54:53 +00001714 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001715 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001716 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1717}
1718
1719
1720//===----------------------------------------------------------------------===//
1721// Preprocessor Conditional Directive Handling.
1722//===----------------------------------------------------------------------===//
1723
1724/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1725/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1726/// if any tokens have been returned or pp-directives activated before this
1727/// #ifndef has been lexed.
1728///
1729void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1730 bool ReadAnyTokensBeforeDirective) {
1731 ++NumIf;
1732 Token DirectiveTok = Result;
1733
1734 Token MacroNameTok;
1735 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Chris Lattner141e71f2008-03-09 01:54:53 +00001737 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001738 if (MacroNameTok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001739 // Skip code until we get to #endif. This helps with recovery by not
1740 // emitting an error when the #endif is reached.
1741 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1742 /*Foundnonskip*/false, /*FoundElse*/false);
1743 return;
1744 }
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Chris Lattner141e71f2008-03-09 01:54:53 +00001746 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001747 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001748
Chris Lattner13d283d2010-02-12 08:03:27 +00001749 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1750 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001751
Ted Kremenek60e45d42008-11-18 00:34:22 +00001752 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001753 // If the start of a top-level #ifdef and if the macro is not defined,
1754 // inform MIOpt that this might be the start of a proper include guard.
1755 // Otherwise it is some other form of unknown conditional which we can't
1756 // handle.
1757 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001758 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001759 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001760 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001761 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001762 }
1763
Chris Lattner141e71f2008-03-09 01:54:53 +00001764 // If there is a macro, process it.
1765 if (MI) // Mark it used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001766 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Chris Lattner141e71f2008-03-09 01:54:53 +00001768 // Should we include the stuff contained by this directive?
1769 if (!MI == isIfndef) {
1770 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001771 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1772 /*wasskip*/false, /*foundnonskip*/true,
1773 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001774 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001775 // No, skip the contents of this block.
Chris Lattner141e71f2008-03-09 01:54:53 +00001776 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001777 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001778 /*FoundElse*/false);
1779 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001780
1781 if (Callbacks) {
1782 if (isIfndef)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001783 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001784 else
Craig Silverstein2aa92672010-11-19 21:33:15 +00001785 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001786 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001787}
1788
1789/// HandleIfDirective - Implements the #if directive.
1790///
1791void Preprocessor::HandleIfDirective(Token &IfToken,
1792 bool ReadAnyTokensBeforeDirective) {
1793 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Craig Silverstein08985b92010-11-06 01:19:03 +00001795 // Parse and evaluate the conditional expression.
Chris Lattner141e71f2008-03-09 01:54:53 +00001796 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein08985b92010-11-06 01:19:03 +00001797 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1798 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1799 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes0049db62008-06-01 18:31:24 +00001800
1801 // If this condition is equivalent to #ifndef X, and if this is the first
1802 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001803 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001804 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001805 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001806 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001807 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001808 }
1809
Chris Lattner141e71f2008-03-09 01:54:53 +00001810 // Should we include the stuff contained by this directive?
1811 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001812 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001813 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001814 /*foundnonskip*/true, /*foundelse*/false);
1815 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001816 // No, skip the contents of this block.
Mike Stump1eb44332009-09-09 15:08:12 +00001817 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001818 /*FoundElse*/false);
1819 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001820
1821 if (Callbacks)
1822 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001823}
1824
1825/// HandleEndifDirective - Implements the #endif directive.
1826///
1827void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1828 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Chris Lattner141e71f2008-03-09 01:54:53 +00001830 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001831 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Chris Lattner141e71f2008-03-09 01:54:53 +00001833 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001834 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001835 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001836 Diag(EndifToken, diag::err_pp_endif_without_if);
1837 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001838 }
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Chris Lattner141e71f2008-03-09 01:54:53 +00001840 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001841 if (CurPPLexer->getConditionalStackDepth() == 0)
1842 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Ted Kremenek60e45d42008-11-18 00:34:22 +00001844 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001845 "This code should only be reachable in the non-skipping case!");
Craig Silverstein08985b92010-11-06 01:19:03 +00001846
1847 if (Callbacks)
1848 Callbacks->Endif();
Chris Lattner141e71f2008-03-09 01:54:53 +00001849}
1850
Craig Silverstein08985b92010-11-06 01:19:03 +00001851/// HandleElseDirective - Implements the #else directive.
1852///
Chris Lattner141e71f2008-03-09 01:54:53 +00001853void Preprocessor::HandleElseDirective(Token &Result) {
1854 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Chris Lattner141e71f2008-03-09 01:54:53 +00001856 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001857 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Chris Lattner141e71f2008-03-09 01:54:53 +00001859 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001860 if (CurPPLexer->popConditionalLevel(CI)) {
1861 Diag(Result, diag::pp_err_else_without_if);
1862 return;
1863 }
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Chris Lattner141e71f2008-03-09 01:54:53 +00001865 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001866 if (CurPPLexer->getConditionalStackDepth() == 0)
1867 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001868
1869 // If this is a #else with a #else before it, report the error.
1870 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Craig Silverstein08985b92010-11-06 01:19:03 +00001872 // Finally, skip the rest of the contents of this block.
1873 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00001874 /*FoundElse*/true, Result.getLocation());
Craig Silverstein08985b92010-11-06 01:19:03 +00001875
1876 if (Callbacks)
1877 Callbacks->Else();
Chris Lattner141e71f2008-03-09 01:54:53 +00001878}
1879
Craig Silverstein08985b92010-11-06 01:19:03 +00001880/// HandleElifDirective - Implements the #elif directive.
1881///
Chris Lattner141e71f2008-03-09 01:54:53 +00001882void Preprocessor::HandleElifDirective(Token &ElifToken) {
1883 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Chris Lattner141e71f2008-03-09 01:54:53 +00001885 // #elif directive in a non-skipping conditional... start skipping.
1886 // We don't care what the condition is, because we will always skip it (since
1887 // the block immediately before it was included).
Craig Silverstein08985b92010-11-06 01:19:03 +00001888 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001889 DiscardUntilEndOfDirective();
Craig Silverstein08985b92010-11-06 01:19:03 +00001890 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001891
1892 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001893 if (CurPPLexer->popConditionalLevel(CI)) {
1894 Diag(ElifToken, diag::pp_err_elif_without_if);
1895 return;
1896 }
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Chris Lattner141e71f2008-03-09 01:54:53 +00001898 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001899 if (CurPPLexer->getConditionalStackDepth() == 0)
1900 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Chris Lattner141e71f2008-03-09 01:54:53 +00001902 // If this is a #elif with a #else before it, report the error.
1903 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1904
Craig Silverstein08985b92010-11-06 01:19:03 +00001905 // Finally, skip the rest of the contents of this block.
1906 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00001907 /*FoundElse*/CI.FoundElse,
1908 ElifToken.getLocation());
Craig Silverstein08985b92010-11-06 01:19:03 +00001909
1910 if (Callbacks)
1911 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001912}