blob: de50c750e4d6653a56b4481cb432e3fd86cdfdd7 [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);
Chris Lattner141e71f2008-03-09 01:54:53 +0000669 }
670 break;
671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattner42aa16c2009-03-18 21:00:25 +0000673 // If this is a .S file, treat unknown # directives as non-preprocessor
674 // directives. This is important because # may be a comment or introduce
675 // various pseudo-ops. Just return the # token and push back the following
676 // token to be lexed next time.
677 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000678 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000679 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000680 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000681 Toks[1] = Result;
Chris Lattnerba3ca522011-01-06 05:01:51 +0000682
683 // If the second token is a hashhash token, then we need to translate it to
684 // unknown so the token lexer doesn't try to perform token pasting.
685 if (Result.is(tok::hashhash))
686 Toks[1].setKind(tok::unknown);
687
Chris Lattner42aa16c2009-03-18 21:00:25 +0000688 // Enter this token stream so that we re-lex the tokens. Make sure to
689 // enable macro expansion, in case the token after the # is an identifier
690 // that is expanded.
691 EnterTokenStream(Toks, 2, false, true);
692 return;
693 }
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner141e71f2008-03-09 01:54:53 +0000695 // If we reached here, the preprocessing token is not valid!
696 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Chris Lattner141e71f2008-03-09 01:54:53 +0000698 // Read the rest of the PP line.
699 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Chris Lattner141e71f2008-03-09 01:54:53 +0000701 // Okay, we're done parsing the directive.
702}
703
Chris Lattner478a18e2009-01-26 06:19:46 +0000704/// GetLineValue - Convert a numeric token into an unsigned value, emitting
705/// Diagnostic DiagID if it is invalid, and returning the value in Val.
706static bool GetLineValue(Token &DigitTok, unsigned &Val,
707 unsigned DiagID, Preprocessor &PP) {
708 if (DigitTok.isNot(tok::numeric_constant)) {
709 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Peter Collingbourne84021552011-02-28 02:37:51 +0000711 if (DigitTok.isNot(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000712 PP.DiscardUntilEndOfDirective();
713 return true;
714 }
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Chris Lattner478a18e2009-01-26 06:19:46 +0000716 llvm::SmallString<64> IntegerBuffer;
717 IntegerBuffer.resize(DigitTok.getLength());
718 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000719 bool Invalid = false;
720 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
721 if (Invalid)
722 return true;
723
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000724 // Verify that we have a simple digit-sequence, and compute the value. This
725 // is always a simple digit string computed in decimal, so we do this manually
726 // here.
727 Val = 0;
728 for (unsigned i = 0; i != ActualLength; ++i) {
729 if (!isdigit(DigitTokBegin[i])) {
730 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
731 diag::err_pp_line_digit_sequence);
732 PP.DiscardUntilEndOfDirective();
733 return true;
734 }
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000736 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
737 if (NextVal < Val) { // overflow.
738 PP.Diag(DigitTok, DiagID);
739 PP.DiscardUntilEndOfDirective();
740 return true;
741 }
742 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000743 }
Mike Stump1eb44332009-09-09 15:08:12 +0000744
745 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000746 if (Val == 0) {
747 PP.Diag(DigitTok, DiagID);
748 PP.DiscardUntilEndOfDirective();
749 return true;
750 }
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000752 if (DigitTokBegin[0] == '0')
753 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Chris Lattner478a18e2009-01-26 06:19:46 +0000755 return false;
756}
757
Mike Stump1eb44332009-09-09 15:08:12 +0000758/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000759/// acceptable forms are:
760/// # line digit-sequence
761/// # line digit-sequence "s-char-sequence"
762void Preprocessor::HandleLineDirective(Token &Tok) {
763 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
764 // expanded.
765 Token DigitTok;
766 Lex(DigitTok);
767
Chris Lattner359cc442009-01-26 05:29:08 +0000768 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000769 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000770 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000771 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000772
Chris Lattner478a18e2009-01-26 06:19:46 +0000773 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
774 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman158ebfb2011-10-10 23:35:28 +0000775 unsigned LineLimit = 32768U;
776 if (Features.C99 || Features.CPlusPlus0x)
777 LineLimit = 2147483648U;
Chris Lattner359cc442009-01-26 05:29:08 +0000778 if (LineNo >= LineLimit)
779 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith661a9962011-10-15 01:18:56 +0000780 else if (Features.CPlusPlus0x && LineNo >= 32768U)
781 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Chris Lattner5b9a5042009-01-26 07:57:50 +0000783 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000784 Token StrTok;
785 Lex(StrTok);
786
Peter Collingbourne84021552011-02-28 02:37:51 +0000787 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
788 // string followed by eod.
789 if (StrTok.is(tok::eod))
Chris Lattner359cc442009-01-26 05:29:08 +0000790 ; // ok
791 else if (StrTok.isNot(tok::string_literal)) {
792 Diag(StrTok, diag::err_pp_line_invalid_filename);
793 DiscardUntilEndOfDirective();
794 return;
795 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000796 // Parse and validate the string, converting it into a unique ID.
797 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000798 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000799 if (Literal.hadError)
800 return DiscardUntilEndOfDirective();
801 if (Literal.Pascal) {
802 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
803 return DiscardUntilEndOfDirective();
804 }
Jay Foad65aa6882011-06-21 15:13:30 +0000805 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Peter Collingbourne84021552011-02-28 02:37:51 +0000807 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattnerab82f412009-04-17 23:30:53 +0000808 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
809 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000810 }
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Chris Lattner4c4ea172009-02-03 21:52:55 +0000812 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattner16629382009-03-27 17:13:49 +0000814 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000815 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
816 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000817 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000818}
819
Chris Lattner478a18e2009-01-26 06:19:46 +0000820/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
821/// marker directive.
822static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
823 bool &IsSystemHeader, bool &IsExternCHeader,
824 Preprocessor &PP) {
825 unsigned FlagVal;
826 Token FlagTok;
827 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000828 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000829 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
830 return true;
831
832 if (FlagVal == 1) {
833 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Chris Lattner478a18e2009-01-26 06:19:46 +0000835 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000836 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000837 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
838 return true;
839 } else if (FlagVal == 2) {
840 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Chris Lattner137b6a62009-02-04 06:25:26 +0000842 SourceManager &SM = PP.getSourceManager();
843 // If we are leaving the current presumed file, check to make sure the
844 // presumed include stack isn't empty!
845 FileID CurFileID =
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000846 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner137b6a62009-02-04 06:25:26 +0000847 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000848 if (PLoc.isInvalid())
849 return true;
850
Chris Lattner137b6a62009-02-04 06:25:26 +0000851 // If there is no include loc (main file) or if the include loc is in a
852 // different physical file, then we aren't in a "1" line marker flag region.
853 SourceLocation IncLoc = PLoc.getIncludeLoc();
854 if (IncLoc.isInvalid() ||
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000855 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner137b6a62009-02-04 06:25:26 +0000856 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
857 PP.DiscardUntilEndOfDirective();
858 return true;
859 }
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Chris Lattner478a18e2009-01-26 06:19:46 +0000861 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000862 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000863 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
864 return true;
865 }
866
867 // We must have 3 if there are still flags.
868 if (FlagVal != 3) {
869 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000870 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000871 return true;
872 }
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Chris Lattner478a18e2009-01-26 06:19:46 +0000874 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Chris Lattner478a18e2009-01-26 06:19:46 +0000876 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000877 if (FlagTok.is(tok::eod)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000878 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000879 return true;
880
881 // We must have 4 if there is yet another flag.
882 if (FlagVal != 4) {
883 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000884 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000885 return true;
886 }
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Chris Lattner478a18e2009-01-26 06:19:46 +0000888 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Chris Lattner478a18e2009-01-26 06:19:46 +0000890 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000891 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000892
893 // There are no more valid flags here.
894 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000895 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000896 return true;
897}
898
899/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
900/// one of the following forms:
901///
902/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000903/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000904/// # 42 "file" ('1' | '2')? '3' '4'?
905///
906void Preprocessor::HandleDigitDirective(Token &DigitTok) {
907 // Validate the number and convert it to an unsigned. GNU does not have a
908 // line # limit other than it fit in 32-bits.
909 unsigned LineNo;
910 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
911 *this))
912 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Chris Lattner478a18e2009-01-26 06:19:46 +0000914 Token StrTok;
915 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Chris Lattner478a18e2009-01-26 06:19:46 +0000917 bool IsFileEntry = false, IsFileExit = false;
918 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000919 int FilenameID = -1;
920
Peter Collingbourne84021552011-02-28 02:37:51 +0000921 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
922 // string followed by eod.
923 if (StrTok.is(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000924 ; // ok
925 else if (StrTok.isNot(tok::string_literal)) {
926 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000927 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000928 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000929 // Parse and validate the string, converting it into a unique ID.
930 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000931 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000932 if (Literal.hadError)
933 return DiscardUntilEndOfDirective();
934 if (Literal.Pascal) {
935 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
936 return DiscardUntilEndOfDirective();
937 }
Jay Foad65aa6882011-06-21 15:13:30 +0000938 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattner478a18e2009-01-26 06:19:46 +0000940 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000941 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000942 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000943 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000944 }
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chris Lattner9d79eba2009-02-04 05:21:58 +0000946 // Create a line note with this information.
947 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000948 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000949 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattner16629382009-03-27 17:13:49 +0000951 // If the preprocessor has callbacks installed, notify them of the #line
952 // change. This is used so that the line marker comes out in -E mode for
953 // example.
954 if (Callbacks) {
955 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
956 if (IsFileEntry)
957 Reason = PPCallbacks::EnterFile;
958 else if (IsFileExit)
959 Reason = PPCallbacks::ExitFile;
960 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
961 if (IsExternCHeader)
962 FileKind = SrcMgr::C_ExternCSystem;
963 else if (IsSystemHeader)
964 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Chris Lattner86d0ef72010-04-14 04:28:50 +0000966 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000967 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000968}
969
970
Chris Lattner099dd052009-01-26 05:30:54 +0000971/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
972///
Mike Stump1eb44332009-09-09 15:08:12 +0000973void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000974 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000975 // PTH doesn't emit #warning or #error directives.
976 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000977 return CurPTHLexer->DiscardToEndOfLine();
978
Chris Lattner141e71f2008-03-09 01:54:53 +0000979 // Read the rest of the line raw. We do this because we don't want macros
980 // to be expanded and we don't require that the tokens be valid preprocessing
981 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
982 // collapse multiple consequtive white space between tokens, but this isn't
983 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000984 std::string Message = CurLexer->ReadToEndOfLine();
985 if (isWarning)
986 Diag(Tok, diag::pp_hash_warning) << Message;
987 else
988 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000989}
990
991/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
992///
993void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
994 // Yes, this directive is an extension.
995 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Chris Lattner141e71f2008-03-09 01:54:53 +0000997 // Read the string argument.
998 Token StrTok;
999 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattner141e71f2008-03-09 01:54:53 +00001001 // If the token kind isn't a string, it's a malformed directive.
1002 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +00001003 StrTok.isNot(tok::wide_string_literal)) {
1004 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne84021552011-02-28 02:37:51 +00001005 if (StrTok.isNot(tok::eod))
Chris Lattner099dd052009-01-26 05:30:54 +00001006 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +00001007 return;
1008 }
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Peter Collingbourne84021552011-02-28 02:37:51 +00001010 // Verify that there is nothing after the string, other than EOD.
Chris Lattner35410d52009-04-14 05:07:49 +00001011 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +00001012
Douglas Gregor453091c2010-03-16 22:30:13 +00001013 if (Callbacks) {
1014 bool Invalid = false;
1015 std::string Str = getSpelling(StrTok, &Invalid);
1016 if (!Invalid)
1017 Callbacks->Ident(Tok.getLocation(), Str);
1018 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001019}
1020
Douglas Gregor7143aab2011-09-01 17:04:32 +00001021/// \brief Handle a #__export_macro__ directive.
1022void Preprocessor::HandleMacroExportDirective(Token &Tok) {
1023 Token MacroNameTok;
1024 ReadMacroName(MacroNameTok, 2);
1025
1026 // Error reading macro name? If so, diagnostic already issued.
1027 if (MacroNameTok.is(tok::eod))
1028 return;
1029
1030 // Check to see if this is the last token on the #__export_macro__ line.
1031 CheckEndOfDirective("__export_macro__");
1032
1033 // Okay, we finally have a valid identifier to undef.
1034 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1035
1036 // If the macro is not defined, this is an error.
1037 if (MI == 0) {
1038 Diag(MacroNameTok, diag::err_pp_export_non_macro)
1039 << MacroNameTok.getIdentifierInfo();
1040 return;
1041 }
1042
1043 // Note that this macro has now been exported.
1044 MI->setExportLocation(MacroNameTok.getLocation());
1045
1046 // If this macro definition came from a PCH file, mark it
1047 // as having changed since serialization.
1048 if (MI->isFromAST())
1049 MI->setChangedAfterLoad();
1050}
1051
Chris Lattner141e71f2008-03-09 01:54:53 +00001052//===----------------------------------------------------------------------===//
1053// Preprocessor Include Directive Handling.
1054//===----------------------------------------------------------------------===//
1055
1056/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1057/// checked and spelled filename, e.g. as an operand of #include. This returns
1058/// true if the input filename was in <>'s or false if it were in ""'s. The
1059/// caller is expected to provide a buffer that is large enough to hold the
1060/// spelling of the filename, but is also expected to handle the case when
1061/// this method decides to use a different buffer.
1062bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001063 StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001064 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +00001065 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Chris Lattner141e71f2008-03-09 01:54:53 +00001067 // Make sure the filename is <x> or "x".
1068 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +00001069 if (Buffer[0] == '<') {
1070 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001071 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001072 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001073 return true;
1074 }
1075 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +00001076 } else if (Buffer[0] == '"') {
1077 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001078 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001079 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001080 return true;
1081 }
1082 isAngled = false;
1083 } else {
1084 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001085 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001086 return true;
1087 }
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Chris Lattner141e71f2008-03-09 01:54:53 +00001089 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +00001090 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001091 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001092 Buffer = StringRef();
Chris Lattnera1394812010-01-10 01:35:12 +00001093 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001094 }
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Chris Lattner141e71f2008-03-09 01:54:53 +00001096 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001097 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001098 return isAngled;
1099}
1100
1101/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1102/// from a macro as multiple tokens, which need to be glued together. This
1103/// occurs for code like:
1104/// #define FOO <a/b.h>
1105/// #include FOO
1106/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1107///
1108/// This code concatenates and consumes tokens up to the '>' token. It returns
1109/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne84021552011-02-28 02:37:51 +00001110/// the EOD marker.
John Thompsona28cc092009-10-30 13:49:06 +00001111bool Preprocessor::ConcatenateIncludeName(
Douglas Gregorecdcb882010-10-20 22:00:55 +00001112 llvm::SmallString<128> &FilenameBuffer,
1113 SourceLocation &End) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001114 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
John Thompsona28cc092009-10-30 13:49:06 +00001116 Lex(CurTok);
Peter Collingbourne84021552011-02-28 02:37:51 +00001117 while (CurTok.isNot(tok::eod)) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001118 End = CurTok.getLocation();
1119
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001120 // FIXME: Provide code completion for #includes.
1121 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001122 setCodeCompletionReached();
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001123 Lex(CurTok);
1124 continue;
1125 }
1126
Chris Lattner141e71f2008-03-09 01:54:53 +00001127 // Append the spelling of this token to the buffer. If there was a space
1128 // before it, add it now.
1129 if (CurTok.hasLeadingSpace())
1130 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Chris Lattner141e71f2008-03-09 01:54:53 +00001132 // Get the spelling of the token, directly into FilenameBuffer if possible.
1133 unsigned PreAppendSize = FilenameBuffer.size();
1134 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Chris Lattner141e71f2008-03-09 01:54:53 +00001136 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001137 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Chris Lattner141e71f2008-03-09 01:54:53 +00001139 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1140 if (BufPtr != &FilenameBuffer[PreAppendSize])
1141 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Chris Lattner141e71f2008-03-09 01:54:53 +00001143 // Resize FilenameBuffer to the correct size.
1144 if (CurTok.getLength() != ActualLen)
1145 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Chris Lattner141e71f2008-03-09 01:54:53 +00001147 // If we found the '>' marker, return success.
1148 if (CurTok.is(tok::greater))
1149 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001150
John Thompsona28cc092009-10-30 13:49:06 +00001151 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001152 }
1153
Peter Collingbourne84021552011-02-28 02:37:51 +00001154 // If we hit the eod marker, emit an error and return true so that the caller
1155 // knows the EOD has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001156 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001157 return true;
1158}
1159
1160/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1161/// file to be included from the lexer, then include it! This is a common
1162/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001163/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001164/// specifies the file to start searching from.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001165void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1166 Token &IncludeTok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001167 const DirectoryLookup *LookupFrom,
1168 bool isImport) {
1169
1170 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001171 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Chris Lattner141e71f2008-03-09 01:54:53 +00001173 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001174 llvm::SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001175 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001176 SourceLocation End;
1177
Chris Lattner141e71f2008-03-09 01:54:53 +00001178 switch (FilenameTok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +00001179 case tok::eod:
1180 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattner141e71f2008-03-09 01:54:53 +00001181 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Chris Lattner141e71f2008-03-09 01:54:53 +00001183 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001184 case tok::string_literal:
1185 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregorecdcb882010-10-20 22:00:55 +00001186 End = FilenameTok.getLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001187 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Chris Lattner141e71f2008-03-09 01:54:53 +00001189 case tok::less:
1190 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1191 // case, glue the tokens together into FilenameBuffer and interpret those.
1192 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +00001193 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne84021552011-02-28 02:37:51 +00001194 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001195 Filename = FilenameBuffer.str();
Chris Lattner141e71f2008-03-09 01:54:53 +00001196 break;
1197 default:
1198 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1199 DiscardUntilEndOfDirective();
1200 return;
1201 }
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001203 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001204 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001205 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1206 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001207 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001208 DiscardUntilEndOfDirective();
1209 return;
1210 }
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Peter Collingbourne84021552011-02-28 02:37:51 +00001212 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001213 // we allow macros that expand to nothing after the filename, because this
1214 // falls into the category of "#include pp-tokens new-line" specified in
1215 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001216 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001217
1218 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001219 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1220 Diag(FilenameTok, diag::err_pp_include_too_deep);
1221 return;
1222 }
Mike Stump1eb44332009-09-09 15:08:12 +00001223
John McCall8dfac0b2011-09-30 05:12:12 +00001224 // Complain about attempts to #include files in an audit pragma.
1225 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1226 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1227 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1228
1229 // Immediately leave the pragma.
1230 PragmaARCCFCodeAuditedLoc = SourceLocation();
1231 }
1232
Chris Lattner141e71f2008-03-09 01:54:53 +00001233 // Search include directories.
1234 const DirectoryLookup *CurDir;
Manuel Klimek74124942011-04-26 21:50:03 +00001235 llvm::SmallString<1024> SearchPath;
1236 llvm::SmallString<1024> RelativePath;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001237 // We get the raw path only if we have 'Callbacks' to which we later pass
1238 // the path.
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001239 StringRef SuggestedModule;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001240 const FileEntry *File = LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +00001241 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001242 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
1243 AutoModuleImport? &SuggestedModule : 0);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001244
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001245 // If we are supposed to import a module rather than including the header,
1246 // do so now.
1247 if (!SuggestedModule.empty()) {
1248 TheModuleLoader.loadModule(IncludeTok.getLocation(),
1249 Identifiers.get(SuggestedModule),
1250 FilenameTok.getLocation());
1251 return;
1252 }
1253
Douglas Gregorecdcb882010-10-20 22:00:55 +00001254 // Notify the callback object that we've seen an inclusion directive.
1255 if (Callbacks)
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001256 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
Manuel Klimek74124942011-04-26 21:50:03 +00001257 End, SearchPath, RelativePath);
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001258
Peter Collingbournebb527862011-07-12 19:35:15 +00001259 if (File == 0) {
Eli Friedmanf84139a2011-08-30 23:07:51 +00001260 if (!SuppressIncludeNotFoundError)
1261 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Peter Collingbournebb527862011-07-12 19:35:15 +00001262 return;
1263 }
1264
Chris Lattner72181832008-09-26 20:12:23 +00001265 // The #included file will be considered to be a system header if either it is
1266 // in a system include directory, or if the #includer is a system include
1267 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001268 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001269 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001270 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001272 // Ask HeaderInfo if we should enter this #include file. If not, #including
1273 // this file will have no effect.
1274 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001275 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001276 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001277 return;
1278 }
1279
Chris Lattner141e71f2008-03-09 01:54:53 +00001280 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001281 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1282 FileCharacter);
Peter Collingbourned57b7ff2011-06-30 16:41:03 +00001283 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattner141e71f2008-03-09 01:54:53 +00001284
1285 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001286 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001287}
1288
1289/// HandleIncludeNextDirective - Implements #include_next.
1290///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001291void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1292 Token &IncludeNextTok) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001293 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Chris Lattner141e71f2008-03-09 01:54:53 +00001295 // #include_next is like #include, except that we start searching after
1296 // the current found directory. If we can't do this, issue a
1297 // diagnostic.
1298 const DirectoryLookup *Lookup = CurDirLookup;
1299 if (isInPrimaryFile()) {
1300 Lookup = 0;
1301 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1302 } else if (Lookup == 0) {
1303 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1304 } else {
1305 // Start looking up in the next directory.
1306 ++Lookup;
1307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Douglas Gregorecdcb882010-10-20 22:00:55 +00001309 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattner141e71f2008-03-09 01:54:53 +00001310}
1311
1312/// HandleImportDirective - Implements #import.
1313///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001314void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1315 Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001316 if (!Features.ObjC1) // #import is standard for ObjC.
1317 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Douglas Gregorecdcb882010-10-20 22:00:55 +00001319 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001320}
1321
Chris Lattnerde076652009-04-08 18:46:40 +00001322/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1323/// pseudo directive in the predefines buffer. This handles it by sucking all
1324/// tokens through the preprocessor and discarding them (only keeping the side
1325/// effects on the preprocessor).
Douglas Gregorecdcb882010-10-20 22:00:55 +00001326void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1327 Token &IncludeMacrosTok) {
Chris Lattnerde076652009-04-08 18:46:40 +00001328 // This directive should only occur in the predefines buffer. If not, emit an
1329 // error and reject it.
1330 SourceLocation Loc = IncludeMacrosTok.getLocation();
1331 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1332 Diag(IncludeMacrosTok.getLocation(),
1333 diag::pp_include_macros_out_of_predefines);
1334 DiscardUntilEndOfDirective();
1335 return;
1336 }
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Chris Lattnerfd105112009-04-08 20:53:24 +00001338 // Treat this as a normal #include for checking purposes. If this is
1339 // successful, it will push a new lexer onto the include stack.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001340 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Chris Lattnerfd105112009-04-08 20:53:24 +00001342 Token TmpTok;
1343 do {
1344 Lex(TmpTok);
1345 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1346 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001347}
1348
Chris Lattner141e71f2008-03-09 01:54:53 +00001349//===----------------------------------------------------------------------===//
1350// Preprocessor Macro Directive Handling.
1351//===----------------------------------------------------------------------===//
1352
1353/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1354/// definition has just been read. Lex the rest of the arguments and the
1355/// closing ), updating MI with what we learn. Return true if an error occurs
1356/// parsing the arg list.
1357bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001358 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Chris Lattner141e71f2008-03-09 01:54:53 +00001360 Token Tok;
1361 while (1) {
1362 LexUnexpandedToken(Tok);
1363 switch (Tok.getKind()) {
1364 case tok::r_paren:
1365 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001366 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001367 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001368 // Otherwise we have #define FOO(A,)
1369 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1370 return true;
1371 case tok::ellipsis: // #define X(... -> C99 varargs
Richard Smith661a9962011-10-15 01:18:56 +00001372 if (!Features.C99)
1373 Diag(Tok, Features.CPlusPlus0x ?
1374 diag::warn_cxx98_compat_variadic_macro :
1375 diag::ext_variadic_macro);
Chris Lattner141e71f2008-03-09 01:54:53 +00001376
1377 // Lex the token after the identifier.
1378 LexUnexpandedToken(Tok);
1379 if (Tok.isNot(tok::r_paren)) {
1380 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1381 return true;
1382 }
1383 // Add the __VA_ARGS__ identifier as an argument.
1384 Arguments.push_back(Ident__VA_ARGS__);
1385 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001386 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001387 return false;
Peter Collingbourne84021552011-02-28 02:37:51 +00001388 case tok::eod: // #define X(
Chris Lattner141e71f2008-03-09 01:54:53 +00001389 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1390 return true;
1391 default:
1392 // Handle keywords and identifiers here to accept things like
1393 // #define Foo(for) for.
1394 IdentifierInfo *II = Tok.getIdentifierInfo();
1395 if (II == 0) {
1396 // #define X(1
1397 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1398 return true;
1399 }
1400
1401 // If this is already used as an argument, it is used multiple times (e.g.
1402 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001403 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001404 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001405 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001406 return true;
1407 }
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Chris Lattner141e71f2008-03-09 01:54:53 +00001409 // Add the argument to the macro info.
1410 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Chris Lattner141e71f2008-03-09 01:54:53 +00001412 // Lex the token after the identifier.
1413 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Chris Lattner141e71f2008-03-09 01:54:53 +00001415 switch (Tok.getKind()) {
1416 default: // #define X(A B
1417 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1418 return true;
1419 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001420 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001421 return false;
1422 case tok::comma: // #define X(A,
1423 break;
1424 case tok::ellipsis: // #define X(A... -> GCC extension
1425 // Diagnose extension.
1426 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Chris Lattner141e71f2008-03-09 01:54:53 +00001428 // Lex the token after the identifier.
1429 LexUnexpandedToken(Tok);
1430 if (Tok.isNot(tok::r_paren)) {
1431 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1432 return true;
1433 }
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Chris Lattner141e71f2008-03-09 01:54:53 +00001435 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001436 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001437 return false;
1438 }
1439 }
1440 }
1441}
1442
1443/// HandleDefineDirective - Implements #define. This consumes the entire macro
1444/// line then lets the caller lex the next real token.
1445void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1446 ++NumDefined;
1447
1448 Token MacroNameTok;
1449 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Chris Lattner141e71f2008-03-09 01:54:53 +00001451 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001452 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001453 return;
1454
Chris Lattner2451b522009-04-21 04:46:33 +00001455 Token LastTok = MacroNameTok;
1456
Chris Lattner141e71f2008-03-09 01:54:53 +00001457 // If we are supposed to keep comments in #defines, reenable comment saving
1458 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001459 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Chris Lattner141e71f2008-03-09 01:54:53 +00001461 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001462 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Chris Lattner141e71f2008-03-09 01:54:53 +00001464 Token Tok;
1465 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Chris Lattner141e71f2008-03-09 01:54:53 +00001467 // If this is a function-like macro definition, parse the argument list,
1468 // marking each of the identifiers as being used as macro arguments. Also,
1469 // check other constraints on the first token of the macro body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001470 if (Tok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001471 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001472 } else if (Tok.hasLeadingSpace()) {
1473 // This is a normal token with leading space. Clear the leading space
1474 // marker on the first token to get proper expansion.
1475 Tok.clearFlag(Token::LeadingSpace);
1476 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001477 // This is a function-like macro definition. Read the argument list.
1478 MI->setIsFunctionLike();
1479 if (ReadMacroDefinitionArgList(MI)) {
1480 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001481 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001482 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001483 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001484 DiscardUntilEndOfDirective();
1485 return;
1486 }
1487
Chris Lattner8fde5972009-04-19 18:26:34 +00001488 // If this is a definition of a variadic C99 function-like macro, not using
1489 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Chris Lattner8fde5972009-04-19 18:26:34 +00001491 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1492 // This gets unpoisoned where it is allowed.
1493 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1494 if (MI->isC99Varargs())
1495 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Chris Lattner141e71f2008-03-09 01:54:53 +00001497 // Read the first token after the arg list for down below.
1498 LexUnexpandedToken(Tok);
Eli Friedman158ebfb2011-10-10 23:35:28 +00001499 } else if (Features.C99 || Features.CPlusPlus0x) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001500 // C99 requires whitespace between the macro definition and the body. Emit
1501 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001502 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001503 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001504 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1505 // first character of a replacement list is not a character required by
1506 // subclause 5.2.1, then there shall be white-space separation between the
1507 // identifier and the replacement list.". 5.2.1 lists this set:
1508 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1509 // is irrelevant here.
1510 bool isInvalid = false;
1511 if (Tok.is(tok::at)) // @ is not in the list above.
1512 isInvalid = true;
1513 else if (Tok.is(tok::unknown)) {
1514 // If we have an unknown token, it is something strange like "`". Since
1515 // all of valid characters would have lexed into a single character
1516 // token of some sort, we know this is not a valid case.
1517 isInvalid = true;
1518 }
1519 if (isInvalid)
1520 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1521 else
1522 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001523 }
Chris Lattner2451b522009-04-21 04:46:33 +00001524
Peter Collingbourne84021552011-02-28 02:37:51 +00001525 if (!Tok.is(tok::eod))
Chris Lattner2451b522009-04-21 04:46:33 +00001526 LastTok = Tok;
1527
Chris Lattner141e71f2008-03-09 01:54:53 +00001528 // Read the rest of the macro body.
1529 if (MI->isObjectLike()) {
1530 // Object-like macros are very simple, just read their body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001531 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001532 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001533 MI->AddTokenToBody(Tok);
1534 // Get the next token of the macro.
1535 LexUnexpandedToken(Tok);
1536 }
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Chris Lattner141e71f2008-03-09 01:54:53 +00001538 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001539 // Otherwise, read the body of a function-like macro. While we are at it,
1540 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1541 // parameters in function-like macro expansions.
Peter Collingbourne84021552011-02-28 02:37:51 +00001542 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001543 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001544
Chris Lattner141e71f2008-03-09 01:54:53 +00001545 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001546 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Chris Lattner141e71f2008-03-09 01:54:53 +00001548 // Get the next token of the macro.
1549 LexUnexpandedToken(Tok);
1550 continue;
1551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Chris Lattner141e71f2008-03-09 01:54:53 +00001553 // Get the next token of the macro.
1554 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Chris Lattner32404692009-05-25 17:16:10 +00001556 // Check for a valid macro arg identifier.
1557 if (Tok.getIdentifierInfo() == 0 ||
1558 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1559
1560 // If this is assembler-with-cpp mode, we accept random gibberish after
1561 // the '#' because '#' is often a comment character. However, change
1562 // the kind of the token to tok::unknown so that the preprocessor isn't
1563 // confused.
Peter Collingbourne84021552011-02-28 02:37:51 +00001564 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner32404692009-05-25 17:16:10 +00001565 LastTok.setKind(tok::unknown);
1566 } else {
1567 Diag(Tok, diag::err_pp_stringize_not_parameter);
1568 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Chris Lattner32404692009-05-25 17:16:10 +00001570 // Disable __VA_ARGS__ again.
1571 Ident__VA_ARGS__->setIsPoisoned(true);
1572 return;
1573 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001574 }
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Chris Lattner32404692009-05-25 17:16:10 +00001576 // Things look ok, add the '#' and param name tokens to the macro.
1577 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001578 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001579 LastTok = 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 }
1584 }
Mike Stump1eb44332009-09-09 15:08:12 +00001585
1586
Chris Lattner141e71f2008-03-09 01:54:53 +00001587 // Disable __VA_ARGS__ again.
1588 Ident__VA_ARGS__->setIsPoisoned(true);
1589
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001590 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattner141e71f2008-03-09 01:54:53 +00001591 // replacement list.
1592 unsigned NumTokens = MI->getNumTokens();
1593 if (NumTokens != 0) {
1594 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1595 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001596 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001597 return;
1598 }
1599 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1600 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001601 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001602 return;
1603 }
1604 }
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Chris Lattner2451b522009-04-21 04:46:33 +00001606 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Chris Lattner141e71f2008-03-09 01:54:53 +00001608 // Finally, if this identifier already had a macro defined for it, verify that
1609 // the macro bodies are identical and free the old definition.
1610 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001611 // It is very common for system headers to have tons of macro redefinitions
1612 // and for warnings to be disabled in system headers. If this is the case,
1613 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001614 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001615 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001616 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner41c3ae12009-01-16 19:50:11 +00001617 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001618
Chris Lattnerf47724b2010-08-17 15:55:45 +00001619 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001620 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001621 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001622 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001623 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1624 << MacroNameTok.getIdentifierInfo();
1625 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1626 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001627 }
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001628 if (OtherMI->isWarnIfUnused())
1629 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek0ea76722008-12-15 19:56:42 +00001630 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001631 }
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Chris Lattner141e71f2008-03-09 01:54:53 +00001633 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001635 assert(!MI->isUsed());
1636 // If we need warning for not using the macro, add its location in the
1637 // warn-because-unused-macro set. If it gets used it will be removed from set.
1638 if (isInPrimaryFile() && // don't warn for include'd macros.
1639 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikied6471f72011-09-25 23:23:43 +00001640 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001641 MI->setIsWarnIfUnused(true);
1642 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1643 }
1644
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001645 // If the callbacks want to know, tell them about the macro definition.
1646 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001647 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001648}
1649
1650/// HandleUndefDirective - Implements #undef.
1651///
1652void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1653 ++NumUndefined;
1654
1655 Token MacroNameTok;
1656 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Chris Lattner141e71f2008-03-09 01:54:53 +00001658 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001659 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001660 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Chris Lattner141e71f2008-03-09 01:54:53 +00001662 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001663 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Chris Lattner141e71f2008-03-09 01:54:53 +00001665 // Okay, we finally have a valid identifier to undef.
1666 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Chris Lattner141e71f2008-03-09 01:54:53 +00001668 // If the macro is not defined, this is a noop undef, just return.
1669 if (MI == 0) return;
1670
Argyrios Kyrtzidis1f8dcfc2011-07-11 20:39:47 +00001671 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattner141e71f2008-03-09 01:54:53 +00001672 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001673
1674 // If the callbacks want to know, tell them about the macro #undef.
1675 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001676 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001677
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001678 if (MI->isWarnIfUnused())
1679 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1680
Chris Lattner141e71f2008-03-09 01:54:53 +00001681 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001682 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001683 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1684}
1685
1686
1687//===----------------------------------------------------------------------===//
1688// Preprocessor Conditional Directive Handling.
1689//===----------------------------------------------------------------------===//
1690
1691/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1692/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1693/// if any tokens have been returned or pp-directives activated before this
1694/// #ifndef has been lexed.
1695///
1696void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1697 bool ReadAnyTokensBeforeDirective) {
1698 ++NumIf;
1699 Token DirectiveTok = Result;
1700
1701 Token MacroNameTok;
1702 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Chris Lattner141e71f2008-03-09 01:54:53 +00001704 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001705 if (MacroNameTok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001706 // Skip code until we get to #endif. This helps with recovery by not
1707 // emitting an error when the #endif is reached.
1708 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1709 /*Foundnonskip*/false, /*FoundElse*/false);
1710 return;
1711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Chris Lattner141e71f2008-03-09 01:54:53 +00001713 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001714 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001715
Chris Lattner13d283d2010-02-12 08:03:27 +00001716 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1717 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001718
Ted Kremenek60e45d42008-11-18 00:34:22 +00001719 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001720 // If the start of a top-level #ifdef and if the macro is not defined,
1721 // inform MIOpt that this might be the start of a proper include guard.
1722 // Otherwise it is some other form of unknown conditional which we can't
1723 // handle.
1724 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001725 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001726 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001727 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001728 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001729 }
1730
Chris Lattner141e71f2008-03-09 01:54:53 +00001731 // If there is a macro, process it.
1732 if (MI) // Mark it used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001733 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Chris Lattner141e71f2008-03-09 01:54:53 +00001735 // Should we include the stuff contained by this directive?
1736 if (!MI == isIfndef) {
1737 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001738 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1739 /*wasskip*/false, /*foundnonskip*/true,
1740 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001741 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001742 // No, skip the contents of this block.
Chris Lattner141e71f2008-03-09 01:54:53 +00001743 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001744 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001745 /*FoundElse*/false);
1746 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001747
1748 if (Callbacks) {
1749 if (isIfndef)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001750 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001751 else
Craig Silverstein2aa92672010-11-19 21:33:15 +00001752 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001753 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001754}
1755
1756/// HandleIfDirective - Implements the #if directive.
1757///
1758void Preprocessor::HandleIfDirective(Token &IfToken,
1759 bool ReadAnyTokensBeforeDirective) {
1760 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Craig Silverstein08985b92010-11-06 01:19:03 +00001762 // Parse and evaluate the conditional expression.
Chris Lattner141e71f2008-03-09 01:54:53 +00001763 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein08985b92010-11-06 01:19:03 +00001764 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1765 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1766 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes0049db62008-06-01 18:31:24 +00001767
1768 // If this condition is equivalent to #ifndef X, and if this is the first
1769 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001770 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001771 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001772 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001773 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001774 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001775 }
1776
Chris Lattner141e71f2008-03-09 01:54:53 +00001777 // Should we include the stuff contained by this directive?
1778 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001779 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001780 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001781 /*foundnonskip*/true, /*foundelse*/false);
1782 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001783 // No, skip the contents of this block.
Mike Stump1eb44332009-09-09 15:08:12 +00001784 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001785 /*FoundElse*/false);
1786 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001787
1788 if (Callbacks)
1789 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001790}
1791
1792/// HandleEndifDirective - Implements the #endif directive.
1793///
1794void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1795 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Chris Lattner141e71f2008-03-09 01:54:53 +00001797 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001798 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Chris Lattner141e71f2008-03-09 01:54:53 +00001800 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001801 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001802 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001803 Diag(EndifToken, diag::err_pp_endif_without_if);
1804 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001805 }
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Chris Lattner141e71f2008-03-09 01:54:53 +00001807 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001808 if (CurPPLexer->getConditionalStackDepth() == 0)
1809 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Ted Kremenek60e45d42008-11-18 00:34:22 +00001811 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001812 "This code should only be reachable in the non-skipping case!");
Craig Silverstein08985b92010-11-06 01:19:03 +00001813
1814 if (Callbacks)
1815 Callbacks->Endif();
Chris Lattner141e71f2008-03-09 01:54:53 +00001816}
1817
Craig Silverstein08985b92010-11-06 01:19:03 +00001818/// HandleElseDirective - Implements the #else directive.
1819///
Chris Lattner141e71f2008-03-09 01:54:53 +00001820void Preprocessor::HandleElseDirective(Token &Result) {
1821 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Chris Lattner141e71f2008-03-09 01:54:53 +00001823 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001824 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Chris Lattner141e71f2008-03-09 01:54:53 +00001826 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001827 if (CurPPLexer->popConditionalLevel(CI)) {
1828 Diag(Result, diag::pp_err_else_without_if);
1829 return;
1830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Chris Lattner141e71f2008-03-09 01:54:53 +00001832 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001833 if (CurPPLexer->getConditionalStackDepth() == 0)
1834 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001835
1836 // If this is a #else with a #else before it, report the error.
1837 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Craig Silverstein08985b92010-11-06 01:19:03 +00001839 // Finally, skip the rest of the contents of this block.
1840 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00001841 /*FoundElse*/true, Result.getLocation());
Craig Silverstein08985b92010-11-06 01:19:03 +00001842
1843 if (Callbacks)
1844 Callbacks->Else();
Chris Lattner141e71f2008-03-09 01:54:53 +00001845}
1846
Craig Silverstein08985b92010-11-06 01:19:03 +00001847/// HandleElifDirective - Implements the #elif directive.
1848///
Chris Lattner141e71f2008-03-09 01:54:53 +00001849void Preprocessor::HandleElifDirective(Token &ElifToken) {
1850 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Chris Lattner141e71f2008-03-09 01:54:53 +00001852 // #elif directive in a non-skipping conditional... start skipping.
1853 // We don't care what the condition is, because we will always skip it (since
1854 // the block immediately before it was included).
Craig Silverstein08985b92010-11-06 01:19:03 +00001855 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001856 DiscardUntilEndOfDirective();
Craig Silverstein08985b92010-11-06 01:19:03 +00001857 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001858
1859 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001860 if (CurPPLexer->popConditionalLevel(CI)) {
1861 Diag(ElifToken, diag::pp_err_elif_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 #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001866 if (CurPPLexer->getConditionalStackDepth() == 0)
1867 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Chris Lattner141e71f2008-03-09 01:54:53 +00001869 // If this is a #elif with a #else before it, report the error.
1870 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1871
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*/CI.FoundElse,
1875 ElifToken.getLocation());
Craig Silverstein08985b92010-11-06 01:19:03 +00001876
1877 if (Callbacks)
1878 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001879}