blob: 1f54ef52c3ebade32a32c1421df07347bf27aca8 [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor3a7ad252010-08-24 19:08:16 +000019#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor97eec242011-09-15 22:00:41 +000020#include "clang/Lex/ModuleLoader.h"
Douglas Gregorc7d65762010-09-09 22:45:38 +000021#include "clang/Lex/Pragma.h"
Chris Lattner710bb872009-11-30 04:18:44 +000022#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000023#include "clang/Basic/SourceManager.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000024#include "llvm/ADT/APInt.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000025using namespace clang;
26
27//===----------------------------------------------------------------------===//
28// Utility Methods for Preprocessor Directive Handling.
29//===----------------------------------------------------------------------===//
30
Chris Lattnerc0a585d2010-08-17 15:55:45 +000031MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000032 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000033
Ted Kremenekc8456f82010-10-19 22:15:20 +000034 if (MICache) {
35 MIChain = MICache;
36 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000037 }
Ted Kremenekc8456f82010-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 Lattnerc0a585d2010-08-17 15:55:45 +000049}
50
51MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
52 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000053 new (MI) MacroInfo(L);
54 return MI;
55}
56
Chris Lattnerc0a585d2010-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 Lattner666f7a42009-02-20 22:19:20 +000063/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
64/// be reused for allocating new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +000065void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-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 Lattner666f7a42009-02-20 22:19:20 +000080
Ted Kremenekc8456f82010-10-19 22:15:20 +000081 MI->Destroy();
82}
Chris Lattner666f7a42009-02-20 22:19:20 +000083
Chris Lattnerf64b3522008-03-09 01:54:53 +000084/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000085/// current line until the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000086void Preprocessor::DiscardUntilEndOfDirective() {
87 Token Tmp;
88 do {
89 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000090 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000091 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000092}
93
Chris Lattnerf64b3522008-03-09 01:54:53 +000094/// ReadMacroName - Lex and validate a macro name, which occurs after a
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000095/// #define or #undef. This sets the token kind to eod and discards the rest
Chris Lattnerf64b3522008-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 Stump11289f42009-09-09 15:08:12 +0000102
Douglas Gregor12785102010-08-24 20:21:13 +0000103 if (MacroNameTok.is(tok::code_completion)) {
104 if (CodeComplete)
105 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000106 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000107 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000108 }
109
Chris Lattnerf64b3522008-03-09 01:54:53 +0000110 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000111 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000112 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
113 return;
114 }
Mike Stump11289f42009-09-09 15:08:12 +0000115
Chris Lattnerf64b3522008-03-09 01:54:53 +0000116 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
117 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000118 bool Invalid = false;
119 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
120 if (Invalid)
121 return;
122
Chris Lattner77c76ae2008-12-13 20:12:40 +0000123 const IdentifierInfo &Info = Identifiers.get(Spelling);
124 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000125 // C++ 2.5p2: Alternative tokens behave the same as its primary token
126 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000127 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-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 Stump11289f42009-09-09 15:08:12 +0000145
Chris Lattnerf64b3522008-03-09 01:54:53 +0000146 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000147 // token kind to tok::eod.
148 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000149 return DiscardUntilEndOfDirective();
150}
151
Peter Collingbourne2f1e36b2011-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 Lattner0003c272009-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 Lattnerf64b3522008-03-09 01:54:53 +0000156 Token Tmp;
Chris Lattner0003c272009-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 Stump11289f42009-09-09 15:08:12 +0000164
Chris Lattnerf64b3522008-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 Stump11289f42009-09-09 15:08:12 +0000169
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000170 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000171 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-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 Gregora771f462010-03-31 17:46:05 +0000175 FixItHint Hint;
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000176 if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
177 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000178 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
179 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-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,
196 bool FoundElse) {
197 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000198 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000199
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000200 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000201 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000202
Ted Kremenek56572ab2008-12-12 18:34:08 +0000203 if (CurPTHLexer) {
204 PTHSkipExcludedConditionalBlock();
205 return;
206 }
Mike Stump11289f42009-09-09 15:08:12 +0000207
Chris Lattnerf64b3522008-03-09 01:54:53 +0000208 // Enter raw mode to disable identifier lookup (and thus macro expansion),
209 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000210 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000211 Token Tok;
212 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000213 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000214
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000215 if (Tok.is(tok::code_completion)) {
216 if (CodeComplete)
217 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000218 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000219 continue;
220 }
221
Chris Lattnerf64b3522008-03-09 01:54:53 +0000222 // If this is the end of the buffer, we have an error.
223 if (Tok.is(tok::eof)) {
224 // Emit errors for each unterminated conditional on the stack, including
225 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000226 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000227 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000228 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
229 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000230 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000231 }
232
Chris Lattnerf64b3522008-03-09 01:54:53 +0000233 // Just return and let the caller lex after this #include.
234 break;
235 }
Mike Stump11289f42009-09-09 15:08:12 +0000236
Chris Lattnerf64b3522008-03-09 01:54:53 +0000237 // If this token is not a preprocessor directive, just skip it.
238 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
239 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000240
Chris Lattnerf64b3522008-03-09 01:54:53 +0000241 // We just parsed a # character at the start of a line, so we're in
242 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000243 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000244 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000245 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000246
Mike Stump11289f42009-09-09 15:08:12 +0000247
Chris Lattnerf64b3522008-03-09 01:54:53 +0000248 // Read the next token, the directive flavor.
249 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000250
Chris Lattnerf64b3522008-03-09 01:54:53 +0000251 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
252 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000253 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000254 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000255 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000256 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000257 continue;
258 }
259
260 // If the first letter isn't i or e, it isn't intesting to us. We know that
261 // this is safe in the face of spelling differences, because there is no way
262 // to spell an i/e in a strange way that is another letter. Skipping this
263 // allows us to avoid looking up the identifier info for #define/#undef and
264 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000265 const char *RawCharData = Tok.getRawIdentifierData();
266
Chris Lattnerf64b3522008-03-09 01:54:53 +0000267 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000268 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000269 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000270 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000271 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000272 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000273 continue;
274 }
Mike Stump11289f42009-09-09 15:08:12 +0000275
Chris Lattnerf64b3522008-03-09 01:54:53 +0000276 // Get the identifier name without trigraphs or embedded newlines. Note
277 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
278 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000279 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000280 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000281 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000282 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000283 } else {
284 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000285 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000286 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000287 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000288 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000289 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000290 continue;
291 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000292 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000293 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000294 }
Mike Stump11289f42009-09-09 15:08:12 +0000295
Benjamin Kramer144884642009-12-31 13:32:38 +0000296 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000297 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000298 if (Sub.empty() || // "if"
299 Sub == "def" || // "ifdef"
300 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000301 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
302 // bother parsing the condition.
303 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000304 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000305 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000306 /*foundelse*/false);
307
308 if (Callbacks)
309 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000310 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000311 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000312 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000313 if (Sub == "ndif") { // "endif"
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000314 CheckEndOfDirective("endif");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000315 PPConditionalInfo CondInfo;
316 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000317 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000318 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000319 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000320
Chris Lattnerf64b3522008-03-09 01:54:53 +0000321 // If we popped the outermost skipping block, we're done skipping!
322 if (!CondInfo.WasSkipping)
323 break;
Benjamin Kramer144884642009-12-31 13:32:38 +0000324 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000325 // #else directive in a skipping conditional. If not in some other
326 // skipping conditional, and if #else hasn't already been seen, enter it
327 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000328 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattnerf64b3522008-03-09 01:54:53 +0000330 // If this is a #else with a #else before it, report the error.
331 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000332
Chris Lattnerf64b3522008-03-09 01:54:53 +0000333 // Note that we've seen a #else in this conditional.
334 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000335
Chandler Carruth540960f2011-01-03 17:40:17 +0000336 if (Callbacks)
337 Callbacks->Else();
338
Chris Lattnerf64b3522008-03-09 01:54:53 +0000339 // If the conditional is at the top level, and the #if block wasn't
340 // entered, enter the #else block now.
341 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
342 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000343 CheckEndOfDirective("else");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000344 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000345 } else {
346 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000347 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000348 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000349 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000350
351 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000352 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000353 // If this is in a skipping block or if we're already handled this #if
354 // block, don't bother parsing the condition.
355 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
356 DiscardUntilEndOfDirective();
357 ShouldEnter = false;
358 } else {
359 // Restore the value of LexingRawMode so that identifiers are
360 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000361 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
362 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000363 IdentifierInfo *IfNDefMacro = 0;
364 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000365 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000366 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000367 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000368
Chris Lattnerf64b3522008-03-09 01:54:53 +0000369 // If this is a #elif with a #else before it, report the error.
370 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000371
Chandler Carruth540960f2011-01-03 17:40:17 +0000372 if (Callbacks)
373 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
374
Chris Lattnerf64b3522008-03-09 01:54:53 +0000375 // If this condition is true, enter it!
376 if (ShouldEnter) {
377 CondInfo.FoundNonSkip = true;
378 break;
379 }
380 }
381 }
Mike Stump11289f42009-09-09 15:08:12 +0000382
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000383 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000384 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000385 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 }
387
388 // Finally, if we are out of the conditional (saw an #endif or ran off the end
389 // of the file, just stop skipping and return to lexing whatever came after
390 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000391 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000392}
393
Ted Kremenek56572ab2008-12-12 18:34:08 +0000394void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000395
396 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000397 assert(CurPTHLexer);
398 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000399
Ted Kremenek56572ab2008-12-12 18:34:08 +0000400 // Skip to the next '#else', '#elif', or #endif.
401 if (CurPTHLexer->SkipBlock()) {
402 // We have reached an #endif. Both the '#' and 'endif' tokens
403 // have been consumed by the PTHLexer. Just pop off the condition level.
404 PPConditionalInfo CondInfo;
405 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000406 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000407 assert(!InCond && "Can't be skipping if not in a conditional!");
408 break;
409 }
Mike Stump11289f42009-09-09 15:08:12 +0000410
Ted Kremenek56572ab2008-12-12 18:34:08 +0000411 // We have reached a '#else' or '#elif'. Lex the next token to get
412 // the directive flavor.
413 Token Tok;
414 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000415
Ted Kremenek56572ab2008-12-12 18:34:08 +0000416 // We can actually look up the IdentifierInfo here since we aren't in
417 // raw mode.
418 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
419
420 if (K == tok::pp_else) {
421 // #else: Enter the else condition. We aren't in a nested condition
422 // since we skip those. We're always in the one matching the last
423 // blocked we skipped.
424 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
425 // Note that we've seen a #else in this conditional.
426 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000427
Ted Kremenek56572ab2008-12-12 18:34:08 +0000428 // If the #if block wasn't entered then enter the #else block now.
429 if (!CondInfo.FoundNonSkip) {
430 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000431
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000432 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000433 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000434 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000435 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000436
Ted Kremenek56572ab2008-12-12 18:34:08 +0000437 break;
438 }
Mike Stump11289f42009-09-09 15:08:12 +0000439
Ted Kremenek56572ab2008-12-12 18:34:08 +0000440 // Otherwise skip this block.
441 continue;
442 }
Mike Stump11289f42009-09-09 15:08:12 +0000443
Ted Kremenek56572ab2008-12-12 18:34:08 +0000444 assert(K == tok::pp_elif);
445 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
446
447 // If this is a #elif with a #else before it, report the error.
448 if (CondInfo.FoundElse)
449 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000450
Ted Kremenek56572ab2008-12-12 18:34:08 +0000451 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000452 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000453 if (CondInfo.FoundNonSkip)
454 continue;
455
456 // Evaluate the condition of the #elif.
457 IdentifierInfo *IfNDefMacro = 0;
458 CurPTHLexer->ParsingPreprocessorDirective = true;
459 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
460 CurPTHLexer->ParsingPreprocessorDirective = false;
461
462 // If this condition is true, enter it!
463 if (ShouldEnter) {
464 CondInfo.FoundNonSkip = true;
465 break;
466 }
467
468 // Otherwise, skip this block and go to the next one.
469 continue;
470 }
471}
472
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000473/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
474/// return null on failure. isAngled indicates whether the file reference is
475/// for system #include's or not (i.e. using <> instead of "").
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000476const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000477 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000478 bool isAngled,
479 const DirectoryLookup *FromDir,
480 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000481 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000482 SmallVectorImpl<char> *RelativePath,
483 StringRef *SuggestedModule) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000484 // If the header lookup mechanism may be relative to the current file, pass in
485 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000486 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000487 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000488 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000489 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000490
Chris Lattner022923a2009-02-04 19:45:07 +0000491 // If there is no file entry associated with this file, it must be the
492 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000493 // it won't be scanned for preprocessor directives. If we have the
494 // predefines buffer, resolve #include references (which come from the
495 // -include command line argument) as if they came from the main file, this
496 // affects file lookup etc.
497 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000498 FID = SourceMgr.getMainFileID();
499 CurFileEnt = SourceMgr.getFileEntryForID(FID);
500 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000501 }
Mike Stump11289f42009-09-09 15:08:12 +0000502
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000503 // Do a standard file entry lookup.
504 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000505 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000506 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor97eec242011-09-15 22:00:41 +0000507 SearchPath, RelativePath, SuggestedModule);
Chris Lattnerfde85352010-01-22 00:14:44 +0000508 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000509
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000510 // Otherwise, see if this is a subframework header. If so, this is relative
511 // to one of the headers on the #include stack. Walk the list of the current
512 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregor97eec242011-09-15 22:00:41 +0000513 // FIXME: SuggestedModule!
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000514 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000515 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000516 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000517 SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000518 return FE;
519 }
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000521 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
522 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000523 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000524 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000525 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000526 if ((FE = HeaderInfo.LookupSubframeworkHeader(
527 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000528 return FE;
529 }
530 }
Mike Stump11289f42009-09-09 15:08:12 +0000531
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000532 // Otherwise, we really couldn't find the file.
533 return 0;
534}
535
Chris Lattnerf64b3522008-03-09 01:54:53 +0000536
537//===----------------------------------------------------------------------===//
538// Preprocessor Directive Handling.
539//===----------------------------------------------------------------------===//
540
541/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000542/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000543/// lexer/preprocessor state, and advances the lexer(s) so that the next token
544/// read is the correct one.
545void Preprocessor::HandleDirective(Token &Result) {
546 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000547
Chris Lattnerf64b3522008-03-09 01:54:53 +0000548 // We just parsed a # character at the start of a line, so we're in directive
549 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000550 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000551 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000552
Chris Lattnerf64b3522008-03-09 01:54:53 +0000553 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000554
Chris Lattnerf64b3522008-03-09 01:54:53 +0000555 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000556 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000557 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000558 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000559
Chris Lattner2d17ab72009-03-18 21:00:25 +0000560 // Save the '#' token in case we need to return it later.
561 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000562
Chris Lattnerf64b3522008-03-09 01:54:53 +0000563 // Read the next token, the directive flavor. This isn't expanded due to
564 // C99 6.10.3p8.
565 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000566
Chris Lattnerf64b3522008-03-09 01:54:53 +0000567 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
568 // #define A(x) #x
569 // A(abc
570 // #warning blah
571 // def)
572 // If so, the user is relying on non-portable behavior, emit a diagnostic.
573 if (InMacroArgs)
574 Diag(Result, diag::ext_embedded_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000575
Chris Lattnerf64b3522008-03-09 01:54:53 +0000576TryAgain:
577 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000578 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000579 return; // null directive.
580 case tok::comment:
581 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
582 LexUnexpandedToken(Result);
583 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000584 case tok::code_completion:
585 if (CodeComplete)
586 CodeComplete->CodeCompleteDirective(
587 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000588 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000589 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000590 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000591 if (getLangOptions().AsmPreprocessor)
592 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000593 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000594 default:
595 IdentifierInfo *II = Result.getIdentifierInfo();
596 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000597
Chris Lattnerf64b3522008-03-09 01:54:53 +0000598 // Ask what the preprocessor keyword ID is.
599 switch (II->getPPKeywordID()) {
600 default: break;
601 // C99 6.10.1 - Conditional Inclusion.
602 case tok::pp_if:
603 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
604 case tok::pp_ifdef:
605 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
606 case tok::pp_ifndef:
607 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
608 case tok::pp_elif:
609 return HandleElifDirective(Result);
610 case tok::pp_else:
611 return HandleElseDirective(Result);
612 case tok::pp_endif:
613 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000614
Chris Lattnerf64b3522008-03-09 01:54:53 +0000615 // C99 6.10.2 - Source File Inclusion.
616 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000617 // Handle #include.
618 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000619 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000620 // Handle -imacros.
621 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000622
Chris Lattnerf64b3522008-03-09 01:54:53 +0000623 // C99 6.10.3 - Macro Replacement.
624 case tok::pp_define:
625 return HandleDefineDirective(Result);
626 case tok::pp_undef:
627 return HandleUndefDirective(Result);
628
629 // C99 6.10.4 - Line Control.
630 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000631 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000632
Chris Lattnerf64b3522008-03-09 01:54:53 +0000633 // C99 6.10.5 - Error Directive.
634 case tok::pp_error:
635 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000636
Chris Lattnerf64b3522008-03-09 01:54:53 +0000637 // C99 6.10.6 - Pragma Directive.
638 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000639 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000640
Chris Lattnerf64b3522008-03-09 01:54:53 +0000641 // GNU Extensions.
642 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000643 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000644 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000645 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattnerf64b3522008-03-09 01:54:53 +0000647 case tok::pp_warning:
648 Diag(Result, diag::ext_pp_warning_directive);
649 return HandleUserDiagnosticDirective(Result, true);
650 case tok::pp_ident:
651 return HandleIdentSCCSDirective(Result);
652 case tok::pp_sccs:
653 return HandleIdentSCCSDirective(Result);
654 case tok::pp_assert:
655 //isExtension = true; // FIXME: implement #assert
656 break;
657 case tok::pp_unassert:
658 //isExtension = true; // FIXME: implement #unassert
659 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000660
661 case tok::pp___export_macro__:
662 return HandleMacroExportDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000663 }
664 break;
665 }
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattner2d17ab72009-03-18 21:00:25 +0000667 // If this is a .S file, treat unknown # directives as non-preprocessor
668 // directives. This is important because # may be a comment or introduce
669 // various pseudo-ops. Just return the # token and push back the following
670 // token to be lexed next time.
671 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000672 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000673 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000674 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000675 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000676
677 // If the second token is a hashhash token, then we need to translate it to
678 // unknown so the token lexer doesn't try to perform token pasting.
679 if (Result.is(tok::hashhash))
680 Toks[1].setKind(tok::unknown);
681
Chris Lattner2d17ab72009-03-18 21:00:25 +0000682 // Enter this token stream so that we re-lex the tokens. Make sure to
683 // enable macro expansion, in case the token after the # is an identifier
684 // that is expanded.
685 EnterTokenStream(Toks, 2, false, true);
686 return;
687 }
Mike Stump11289f42009-09-09 15:08:12 +0000688
Chris Lattnerf64b3522008-03-09 01:54:53 +0000689 // If we reached here, the preprocessing token is not valid!
690 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattnerf64b3522008-03-09 01:54:53 +0000692 // Read the rest of the PP line.
693 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattnerf64b3522008-03-09 01:54:53 +0000695 // Okay, we're done parsing the directive.
696}
697
Chris Lattner76e68962009-01-26 06:19:46 +0000698/// GetLineValue - Convert a numeric token into an unsigned value, emitting
699/// Diagnostic DiagID if it is invalid, and returning the value in Val.
700static bool GetLineValue(Token &DigitTok, unsigned &Val,
701 unsigned DiagID, Preprocessor &PP) {
702 if (DigitTok.isNot(tok::numeric_constant)) {
703 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000704
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000705 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000706 PP.DiscardUntilEndOfDirective();
707 return true;
708 }
Mike Stump11289f42009-09-09 15:08:12 +0000709
Chris Lattner76e68962009-01-26 06:19:46 +0000710 llvm::SmallString<64> IntegerBuffer;
711 IntegerBuffer.resize(DigitTok.getLength());
712 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000713 bool Invalid = false;
714 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
715 if (Invalid)
716 return true;
717
Chris Lattnerd66f1722009-04-18 18:35:15 +0000718 // Verify that we have a simple digit-sequence, and compute the value. This
719 // is always a simple digit string computed in decimal, so we do this manually
720 // here.
721 Val = 0;
722 for (unsigned i = 0; i != ActualLength; ++i) {
723 if (!isdigit(DigitTokBegin[i])) {
724 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
725 diag::err_pp_line_digit_sequence);
726 PP.DiscardUntilEndOfDirective();
727 return true;
728 }
Mike Stump11289f42009-09-09 15:08:12 +0000729
Chris Lattnerd66f1722009-04-18 18:35:15 +0000730 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
731 if (NextVal < Val) { // overflow.
732 PP.Diag(DigitTok, DiagID);
733 PP.DiscardUntilEndOfDirective();
734 return true;
735 }
736 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000737 }
Mike Stump11289f42009-09-09 15:08:12 +0000738
739 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000740 if (Val == 0) {
741 PP.Diag(DigitTok, DiagID);
742 PP.DiscardUntilEndOfDirective();
743 return true;
744 }
Mike Stump11289f42009-09-09 15:08:12 +0000745
Chris Lattnerd66f1722009-04-18 18:35:15 +0000746 if (DigitTokBegin[0] == '0')
747 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000748
Chris Lattner76e68962009-01-26 06:19:46 +0000749 return false;
750}
751
Mike Stump11289f42009-09-09 15:08:12 +0000752/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner100c65e2009-01-26 05:29:08 +0000753/// acceptable forms are:
754/// # line digit-sequence
755/// # line digit-sequence "s-char-sequence"
756void Preprocessor::HandleLineDirective(Token &Tok) {
757 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
758 // expanded.
759 Token DigitTok;
760 Lex(DigitTok);
761
Chris Lattner100c65e2009-01-26 05:29:08 +0000762 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000763 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000764 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000765 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000766
Chris Lattner76e68962009-01-26 06:19:46 +0000767 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
768 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner100c65e2009-01-26 05:29:08 +0000769 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
770 if (LineNo >= LineLimit)
771 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump11289f42009-09-09 15:08:12 +0000772
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000773 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000774 Token StrTok;
775 Lex(StrTok);
776
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000777 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
778 // string followed by eod.
779 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000780 ; // ok
781 else if (StrTok.isNot(tok::string_literal)) {
782 Diag(StrTok, diag::err_pp_line_invalid_filename);
783 DiscardUntilEndOfDirective();
784 return;
785 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000786 // Parse and validate the string, converting it into a unique ID.
787 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000788 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000789 if (Literal.hadError)
790 return DiscardUntilEndOfDirective();
791 if (Literal.Pascal) {
792 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
793 return DiscardUntilEndOfDirective();
794 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000795 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000796
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000797 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000798 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
799 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000800 }
Mike Stump11289f42009-09-09 15:08:12 +0000801
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000802 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000803
Chris Lattner839150e2009-03-27 17:13:49 +0000804 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000805 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
806 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000807 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000808}
809
Chris Lattner76e68962009-01-26 06:19:46 +0000810/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
811/// marker directive.
812static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
813 bool &IsSystemHeader, bool &IsExternCHeader,
814 Preprocessor &PP) {
815 unsigned FlagVal;
816 Token FlagTok;
817 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000818 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000819 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
820 return true;
821
822 if (FlagVal == 1) {
823 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000824
Chris Lattner76e68962009-01-26 06:19:46 +0000825 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000826 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000827 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
828 return true;
829 } else if (FlagVal == 2) {
830 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000831
Chris Lattner1c967782009-02-04 06:25:26 +0000832 SourceManager &SM = PP.getSourceManager();
833 // If we are leaving the current presumed file, check to make sure the
834 // presumed include stack isn't empty!
835 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000836 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000837 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000838 if (PLoc.isInvalid())
839 return true;
840
Chris Lattner1c967782009-02-04 06:25:26 +0000841 // If there is no include loc (main file) or if the include loc is in a
842 // different physical file, then we aren't in a "1" line marker flag region.
843 SourceLocation IncLoc = PLoc.getIncludeLoc();
844 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000845 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000846 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
847 PP.DiscardUntilEndOfDirective();
848 return true;
849 }
Mike Stump11289f42009-09-09 15:08:12 +0000850
Chris Lattner76e68962009-01-26 06:19:46 +0000851 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000852 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000853 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
854 return true;
855 }
856
857 // We must have 3 if there are still flags.
858 if (FlagVal != 3) {
859 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000860 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000861 return true;
862 }
Mike Stump11289f42009-09-09 15:08:12 +0000863
Chris Lattner76e68962009-01-26 06:19:46 +0000864 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000865
Chris Lattner76e68962009-01-26 06:19:46 +0000866 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000867 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000868 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000869 return true;
870
871 // We must have 4 if there is yet another flag.
872 if (FlagVal != 4) {
873 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000874 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000875 return true;
876 }
Mike Stump11289f42009-09-09 15:08:12 +0000877
Chris Lattner76e68962009-01-26 06:19:46 +0000878 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattner76e68962009-01-26 06:19:46 +0000880 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000881 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000882
883 // There are no more valid flags here.
884 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000885 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000886 return true;
887}
888
889/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
890/// one of the following forms:
891///
892/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000893/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000894/// # 42 "file" ('1' | '2')? '3' '4'?
895///
896void Preprocessor::HandleDigitDirective(Token &DigitTok) {
897 // Validate the number and convert it to an unsigned. GNU does not have a
898 // line # limit other than it fit in 32-bits.
899 unsigned LineNo;
900 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
901 *this))
902 return;
Mike Stump11289f42009-09-09 15:08:12 +0000903
Chris Lattner76e68962009-01-26 06:19:46 +0000904 Token StrTok;
905 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000906
Chris Lattner76e68962009-01-26 06:19:46 +0000907 bool IsFileEntry = false, IsFileExit = false;
908 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000909 int FilenameID = -1;
910
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000911 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
912 // string followed by eod.
913 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000914 ; // ok
915 else if (StrTok.isNot(tok::string_literal)) {
916 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000917 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000918 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000919 // Parse and validate the string, converting it into a unique ID.
920 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000921 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000922 if (Literal.hadError)
923 return DiscardUntilEndOfDirective();
924 if (Literal.Pascal) {
925 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
926 return DiscardUntilEndOfDirective();
927 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000928 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000929
Chris Lattner76e68962009-01-26 06:19:46 +0000930 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +0000931 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000932 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +0000933 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000934 }
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000936 // Create a line note with this information.
937 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +0000938 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000939 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattner839150e2009-03-27 17:13:49 +0000941 // If the preprocessor has callbacks installed, notify them of the #line
942 // change. This is used so that the line marker comes out in -E mode for
943 // example.
944 if (Callbacks) {
945 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
946 if (IsFileEntry)
947 Reason = PPCallbacks::EnterFile;
948 else if (IsFileExit)
949 Reason = PPCallbacks::ExitFile;
950 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
951 if (IsExternCHeader)
952 FileKind = SrcMgr::C_ExternCSystem;
953 else if (IsSystemHeader)
954 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +0000955
Chris Lattnerc745cec2010-04-14 04:28:50 +0000956 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +0000957 }
Chris Lattner76e68962009-01-26 06:19:46 +0000958}
959
960
Chris Lattner38d7fd22009-01-26 05:30:54 +0000961/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
962///
Mike Stump11289f42009-09-09 15:08:12 +0000963void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000964 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +0000965 // PTH doesn't emit #warning or #error directives.
966 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +0000967 return CurPTHLexer->DiscardToEndOfLine();
968
Chris Lattnerf64b3522008-03-09 01:54:53 +0000969 // Read the rest of the line raw. We do this because we don't want macros
970 // to be expanded and we don't require that the tokens be valid preprocessing
971 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
972 // collapse multiple consequtive white space between tokens, but this isn't
973 // specified by the standard.
Chris Lattner100c65e2009-01-26 05:29:08 +0000974 std::string Message = CurLexer->ReadToEndOfLine();
975 if (isWarning)
976 Diag(Tok, diag::pp_hash_warning) << Message;
977 else
978 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000979}
980
981/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
982///
983void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
984 // Yes, this directive is an extension.
985 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000986
Chris Lattnerf64b3522008-03-09 01:54:53 +0000987 // Read the string argument.
988 Token StrTok;
989 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000990
Chris Lattnerf64b3522008-03-09 01:54:53 +0000991 // If the token kind isn't a string, it's a malformed directive.
992 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +0000993 StrTok.isNot(tok::wide_string_literal)) {
994 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000995 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +0000996 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000997 return;
998 }
Mike Stump11289f42009-09-09 15:08:12 +0000999
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001000 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001001 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001002
Douglas Gregordc970f02010-03-16 22:30:13 +00001003 if (Callbacks) {
1004 bool Invalid = false;
1005 std::string Str = getSpelling(StrTok, &Invalid);
1006 if (!Invalid)
1007 Callbacks->Ident(Tok.getLocation(), Str);
1008 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001009}
1010
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001011/// \brief Handle a #__export_macro__ directive.
1012void Preprocessor::HandleMacroExportDirective(Token &Tok) {
1013 Token MacroNameTok;
1014 ReadMacroName(MacroNameTok, 2);
1015
1016 // Error reading macro name? If so, diagnostic already issued.
1017 if (MacroNameTok.is(tok::eod))
1018 return;
1019
1020 // Check to see if this is the last token on the #__export_macro__ line.
1021 CheckEndOfDirective("__export_macro__");
1022
1023 // Okay, we finally have a valid identifier to undef.
1024 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1025
1026 // If the macro is not defined, this is an error.
1027 if (MI == 0) {
1028 Diag(MacroNameTok, diag::err_pp_export_non_macro)
1029 << MacroNameTok.getIdentifierInfo();
1030 return;
1031 }
1032
1033 // Note that this macro has now been exported.
1034 MI->setExportLocation(MacroNameTok.getLocation());
1035
1036 // If this macro definition came from a PCH file, mark it
1037 // as having changed since serialization.
1038 if (MI->isFromAST())
1039 MI->setChangedAfterLoad();
1040}
1041
Chris Lattnerf64b3522008-03-09 01:54:53 +00001042//===----------------------------------------------------------------------===//
1043// Preprocessor Include Directive Handling.
1044//===----------------------------------------------------------------------===//
1045
1046/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1047/// checked and spelled filename, e.g. as an operand of #include. This returns
1048/// true if the input filename was in <>'s or false if it were in ""'s. The
1049/// caller is expected to provide a buffer that is large enough to hold the
1050/// spelling of the filename, but is also expected to handle the case when
1051/// this method decides to use a different buffer.
1052bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001053 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001054 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001055 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001056
Chris Lattnerf64b3522008-03-09 01:54:53 +00001057 // Make sure the filename is <x> or "x".
1058 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001059 if (Buffer[0] == '<') {
1060 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001061 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001062 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001063 return true;
1064 }
1065 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001066 } else if (Buffer[0] == '"') {
1067 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001068 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001069 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001070 return true;
1071 }
1072 isAngled = false;
1073 } else {
1074 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001075 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001076 return true;
1077 }
Mike Stump11289f42009-09-09 15:08:12 +00001078
Chris Lattnerf64b3522008-03-09 01:54:53 +00001079 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001080 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001081 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001082 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001083 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
Chris Lattnerf64b3522008-03-09 01:54:53 +00001086 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001087 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001088 return isAngled;
1089}
1090
1091/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1092/// from a macro as multiple tokens, which need to be glued together. This
1093/// occurs for code like:
1094/// #define FOO <a/b.h>
1095/// #include FOO
1096/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1097///
1098/// This code concatenates and consumes tokens up to the '>' token. It returns
1099/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001100/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001101bool Preprocessor::ConcatenateIncludeName(
Douglas Gregor796d76a2010-10-20 22:00:55 +00001102 llvm::SmallString<128> &FilenameBuffer,
1103 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001104 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001105
John Thompsonb5353522009-10-30 13:49:06 +00001106 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001107 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001108 End = CurTok.getLocation();
1109
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001110 // FIXME: Provide code completion for #includes.
1111 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001112 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001113 Lex(CurTok);
1114 continue;
1115 }
1116
Chris Lattnerf64b3522008-03-09 01:54:53 +00001117 // Append the spelling of this token to the buffer. If there was a space
1118 // before it, add it now.
1119 if (CurTok.hasLeadingSpace())
1120 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001121
Chris Lattnerf64b3522008-03-09 01:54:53 +00001122 // Get the spelling of the token, directly into FilenameBuffer if possible.
1123 unsigned PreAppendSize = FilenameBuffer.size();
1124 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001125
Chris Lattnerf64b3522008-03-09 01:54:53 +00001126 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001127 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001128
Chris Lattnerf64b3522008-03-09 01:54:53 +00001129 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1130 if (BufPtr != &FilenameBuffer[PreAppendSize])
1131 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001132
Chris Lattnerf64b3522008-03-09 01:54:53 +00001133 // Resize FilenameBuffer to the correct size.
1134 if (CurTok.getLength() != ActualLen)
1135 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001136
Chris Lattnerf64b3522008-03-09 01:54:53 +00001137 // If we found the '>' marker, return success.
1138 if (CurTok.is(tok::greater))
1139 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001140
John Thompsonb5353522009-10-30 13:49:06 +00001141 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001142 }
1143
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001144 // If we hit the eod marker, emit an error and return true so that the caller
1145 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001146 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001147 return true;
1148}
1149
1150/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1151/// file to be included from the lexer, then include it! This is a common
1152/// routine with functionality shared between #include, #include_next and
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001153/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001154/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001155void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1156 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001157 const DirectoryLookup *LookupFrom,
1158 bool isImport) {
1159
1160 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001161 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001162
Chris Lattnerf64b3522008-03-09 01:54:53 +00001163 // Reserve a buffer to get the spelling.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001164 llvm::SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001165 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001166 SourceLocation End;
1167
Chris Lattnerf64b3522008-03-09 01:54:53 +00001168 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001169 case tok::eod:
1170 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001171 return;
Mike Stump11289f42009-09-09 15:08:12 +00001172
Chris Lattnerf64b3522008-03-09 01:54:53 +00001173 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001174 case tok::string_literal:
1175 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001176 End = FilenameTok.getLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001177 break;
Mike Stump11289f42009-09-09 15:08:12 +00001178
Chris Lattnerf64b3522008-03-09 01:54:53 +00001179 case tok::less:
1180 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1181 // case, glue the tokens together into FilenameBuffer and interpret those.
1182 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001183 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001184 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001185 Filename = FilenameBuffer.str();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001186 break;
1187 default:
1188 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1189 DiscardUntilEndOfDirective();
1190 return;
1191 }
Mike Stump11289f42009-09-09 15:08:12 +00001192
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001193 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001194 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001195 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1196 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001197 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001198 DiscardUntilEndOfDirective();
1199 return;
1200 }
Mike Stump11289f42009-09-09 15:08:12 +00001201
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001202 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001203 // we allow macros that expand to nothing after the filename, because this
1204 // falls into the category of "#include pp-tokens new-line" specified in
1205 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001206 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001207
1208 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001209 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1210 Diag(FilenameTok, diag::err_pp_include_too_deep);
1211 return;
1212 }
Mike Stump11289f42009-09-09 15:08:12 +00001213
Chris Lattnerf64b3522008-03-09 01:54:53 +00001214 // Search include directories.
1215 const DirectoryLookup *CurDir;
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001216 llvm::SmallString<1024> SearchPath;
1217 llvm::SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001218 // We get the raw path only if we have 'Callbacks' to which we later pass
1219 // the path.
Douglas Gregor97eec242011-09-15 22:00:41 +00001220 StringRef SuggestedModule;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001221 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001222 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001223 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
1224 AutoModuleImport? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001225
Douglas Gregor97eec242011-09-15 22:00:41 +00001226 // If we are supposed to import a module rather than including the header,
1227 // do so now.
1228 if (!SuggestedModule.empty()) {
1229 TheModuleLoader.loadModule(IncludeTok.getLocation(),
1230 Identifiers.get(SuggestedModule),
1231 FilenameTok.getLocation());
1232 return;
1233 }
1234
Douglas Gregor796d76a2010-10-20 22:00:55 +00001235 // Notify the callback object that we've seen an inclusion directive.
1236 if (Callbacks)
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001237 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001238 End, SearchPath, RelativePath);
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001239
Peter Collingbourne77b0e7f22011-07-12 19:35:15 +00001240 if (File == 0) {
Eli Friedman3781a362011-08-30 23:07:51 +00001241 if (!SuppressIncludeNotFoundError)
1242 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Peter Collingbourne77b0e7f22011-07-12 19:35:15 +00001243 return;
1244 }
1245
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001246 // The #included file will be considered to be a system header if either it is
1247 // in a system include directory, or if the #includer is a system include
1248 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001249 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001250 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001251 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001252
Chris Lattner72286d62010-04-19 20:44:31 +00001253 // Ask HeaderInfo if we should enter this #include file. If not, #including
1254 // this file will have no effect.
1255 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001256 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001257 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001258 return;
1259 }
1260
Chris Lattnerf64b3522008-03-09 01:54:53 +00001261 // Look up the file, create a File ID for it.
Chris Lattnerd32480d2009-01-17 06:22:33 +00001262 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1263 FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001264 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001265
1266 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001267 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001268}
1269
1270/// HandleIncludeNextDirective - Implements #include_next.
1271///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001272void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1273 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001274 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001275
Chris Lattnerf64b3522008-03-09 01:54:53 +00001276 // #include_next is like #include, except that we start searching after
1277 // the current found directory. If we can't do this, issue a
1278 // diagnostic.
1279 const DirectoryLookup *Lookup = CurDirLookup;
1280 if (isInPrimaryFile()) {
1281 Lookup = 0;
1282 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1283 } else if (Lookup == 0) {
1284 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1285 } else {
1286 // Start looking up in the next directory.
1287 ++Lookup;
1288 }
Mike Stump11289f42009-09-09 15:08:12 +00001289
Douglas Gregor796d76a2010-10-20 22:00:55 +00001290 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001291}
1292
1293/// HandleImportDirective - Implements #import.
1294///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001295void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1296 Token &ImportTok) {
Chris Lattnerd4a96732009-03-06 04:28:03 +00001297 if (!Features.ObjC1) // #import is standard for ObjC.
1298 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001299
Douglas Gregor796d76a2010-10-20 22:00:55 +00001300 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001301}
1302
Chris Lattner58a1eb02009-04-08 18:46:40 +00001303/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1304/// pseudo directive in the predefines buffer. This handles it by sucking all
1305/// tokens through the preprocessor and discarding them (only keeping the side
1306/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001307void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1308 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001309 // This directive should only occur in the predefines buffer. If not, emit an
1310 // error and reject it.
1311 SourceLocation Loc = IncludeMacrosTok.getLocation();
1312 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1313 Diag(IncludeMacrosTok.getLocation(),
1314 diag::pp_include_macros_out_of_predefines);
1315 DiscardUntilEndOfDirective();
1316 return;
1317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
Chris Lattnere01d82b2009-04-08 20:53:24 +00001319 // Treat this as a normal #include for checking purposes. If this is
1320 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001321 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattnere01d82b2009-04-08 20:53:24 +00001323 Token TmpTok;
1324 do {
1325 Lex(TmpTok);
1326 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1327 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001328}
1329
Chris Lattnerf64b3522008-03-09 01:54:53 +00001330//===----------------------------------------------------------------------===//
1331// Preprocessor Macro Directive Handling.
1332//===----------------------------------------------------------------------===//
1333
1334/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1335/// definition has just been read. Lex the rest of the arguments and the
1336/// closing ), updating MI with what we learn. Return true if an error occurs
1337/// parsing the arg list.
1338bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001339 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattnerf64b3522008-03-09 01:54:53 +00001341 Token Tok;
1342 while (1) {
1343 LexUnexpandedToken(Tok);
1344 switch (Tok.getKind()) {
1345 case tok::r_paren:
1346 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001347 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001348 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001349 // Otherwise we have #define FOO(A,)
1350 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1351 return true;
1352 case tok::ellipsis: // #define X(... -> C99 varargs
Eli Friedman4acfbcd2011-08-22 18:48:28 +00001353 if (!Features.C99 && !Features.CPlusPlus0x)
1354 Diag(Tok, diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001355
1356 // Lex the token after the identifier.
1357 LexUnexpandedToken(Tok);
1358 if (Tok.isNot(tok::r_paren)) {
1359 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1360 return true;
1361 }
1362 // Add the __VA_ARGS__ identifier as an argument.
1363 Arguments.push_back(Ident__VA_ARGS__);
1364 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001365 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001366 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001367 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001368 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1369 return true;
1370 default:
1371 // Handle keywords and identifiers here to accept things like
1372 // #define Foo(for) for.
1373 IdentifierInfo *II = Tok.getIdentifierInfo();
1374 if (II == 0) {
1375 // #define X(1
1376 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1377 return true;
1378 }
1379
1380 // If this is already used as an argument, it is used multiple times (e.g.
1381 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001382 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001383 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001384 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001385 return true;
1386 }
Mike Stump11289f42009-09-09 15:08:12 +00001387
Chris Lattnerf64b3522008-03-09 01:54:53 +00001388 // Add the argument to the macro info.
1389 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001390
Chris Lattnerf64b3522008-03-09 01:54:53 +00001391 // Lex the token after the identifier.
1392 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001393
Chris Lattnerf64b3522008-03-09 01:54:53 +00001394 switch (Tok.getKind()) {
1395 default: // #define X(A B
1396 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1397 return true;
1398 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001399 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001400 return false;
1401 case tok::comma: // #define X(A,
1402 break;
1403 case tok::ellipsis: // #define X(A... -> GCC extension
1404 // Diagnose extension.
1405 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001406
Chris Lattnerf64b3522008-03-09 01:54:53 +00001407 // Lex the token after the identifier.
1408 LexUnexpandedToken(Tok);
1409 if (Tok.isNot(tok::r_paren)) {
1410 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1411 return true;
1412 }
Mike Stump11289f42009-09-09 15:08:12 +00001413
Chris Lattnerf64b3522008-03-09 01:54:53 +00001414 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001415 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001416 return false;
1417 }
1418 }
1419 }
1420}
1421
1422/// HandleDefineDirective - Implements #define. This consumes the entire macro
1423/// line then lets the caller lex the next real token.
1424void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1425 ++NumDefined;
1426
1427 Token MacroNameTok;
1428 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001429
Chris Lattnerf64b3522008-03-09 01:54:53 +00001430 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001431 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001432 return;
1433
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001434 Token LastTok = MacroNameTok;
1435
Chris Lattnerf64b3522008-03-09 01:54:53 +00001436 // If we are supposed to keep comments in #defines, reenable comment saving
1437 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001438 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001439
Chris Lattnerf64b3522008-03-09 01:54:53 +00001440 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001441 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001442
Chris Lattnerf64b3522008-03-09 01:54:53 +00001443 Token Tok;
1444 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001445
Chris Lattnerf64b3522008-03-09 01:54:53 +00001446 // If this is a function-like macro definition, parse the argument list,
1447 // marking each of the identifiers as being used as macro arguments. Also,
1448 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001449 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001450 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001451 } else if (Tok.hasLeadingSpace()) {
1452 // This is a normal token with leading space. Clear the leading space
1453 // marker on the first token to get proper expansion.
1454 Tok.clearFlag(Token::LeadingSpace);
1455 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001456 // This is a function-like macro definition. Read the argument list.
1457 MI->setIsFunctionLike();
1458 if (ReadMacroDefinitionArgList(MI)) {
1459 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001460 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001461 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001462 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001463 DiscardUntilEndOfDirective();
1464 return;
1465 }
1466
Chris Lattner249c38b2009-04-19 18:26:34 +00001467 // If this is a definition of a variadic C99 function-like macro, not using
1468 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001469
Chris Lattner249c38b2009-04-19 18:26:34 +00001470 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1471 // This gets unpoisoned where it is allowed.
1472 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1473 if (MI->isC99Varargs())
1474 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001475
Chris Lattnerf64b3522008-03-09 01:54:53 +00001476 // Read the first token after the arg list for down below.
1477 LexUnexpandedToken(Tok);
Chris Lattner2425bcb2009-04-18 02:23:25 +00001478 } else if (Features.C99) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001479 // C99 requires whitespace between the macro definition and the body. Emit
1480 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001481 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001482 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001483 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1484 // first character of a replacement list is not a character required by
1485 // subclause 5.2.1, then there shall be white-space separation between the
1486 // identifier and the replacement list.". 5.2.1 lists this set:
1487 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1488 // is irrelevant here.
1489 bool isInvalid = false;
1490 if (Tok.is(tok::at)) // @ is not in the list above.
1491 isInvalid = true;
1492 else if (Tok.is(tok::unknown)) {
1493 // If we have an unknown token, it is something strange like "`". Since
1494 // all of valid characters would have lexed into a single character
1495 // token of some sort, we know this is not a valid case.
1496 isInvalid = true;
1497 }
1498 if (isInvalid)
1499 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1500 else
1501 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001502 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001503
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001504 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001505 LastTok = Tok;
1506
Chris Lattnerf64b3522008-03-09 01:54:53 +00001507 // Read the rest of the macro body.
1508 if (MI->isObjectLike()) {
1509 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001510 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001511 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001512 MI->AddTokenToBody(Tok);
1513 // Get the next token of the macro.
1514 LexUnexpandedToken(Tok);
1515 }
Mike Stump11289f42009-09-09 15:08:12 +00001516
Chris Lattnerf64b3522008-03-09 01:54:53 +00001517 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001518 // Otherwise, read the body of a function-like macro. While we are at it,
1519 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1520 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001521 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001522 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001523
Chris Lattnerf64b3522008-03-09 01:54:53 +00001524 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001525 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattnerf64b3522008-03-09 01:54:53 +00001527 // Get the next token of the macro.
1528 LexUnexpandedToken(Tok);
1529 continue;
1530 }
Mike Stump11289f42009-09-09 15:08:12 +00001531
Chris Lattnerf64b3522008-03-09 01:54:53 +00001532 // Get the next token of the macro.
1533 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001534
Chris Lattner83bd8282009-05-25 17:16:10 +00001535 // Check for a valid macro arg identifier.
1536 if (Tok.getIdentifierInfo() == 0 ||
1537 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1538
1539 // If this is assembler-with-cpp mode, we accept random gibberish after
1540 // the '#' because '#' is often a comment character. However, change
1541 // the kind of the token to tok::unknown so that the preprocessor isn't
1542 // confused.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001543 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001544 LastTok.setKind(tok::unknown);
1545 } else {
1546 Diag(Tok, diag::err_pp_stringize_not_parameter);
1547 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001548
Chris Lattner83bd8282009-05-25 17:16:10 +00001549 // Disable __VA_ARGS__ again.
1550 Ident__VA_ARGS__->setIsPoisoned(true);
1551 return;
1552 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001553 }
Mike Stump11289f42009-09-09 15:08:12 +00001554
Chris Lattner83bd8282009-05-25 17:16:10 +00001555 // Things look ok, add the '#' and param name tokens to the macro.
1556 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001557 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001558 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001559
Chris Lattnerf64b3522008-03-09 01:54:53 +00001560 // Get the next token of the macro.
1561 LexUnexpandedToken(Tok);
1562 }
1563 }
Mike Stump11289f42009-09-09 15:08:12 +00001564
1565
Chris Lattnerf64b3522008-03-09 01:54:53 +00001566 // Disable __VA_ARGS__ again.
1567 Ident__VA_ARGS__->setIsPoisoned(true);
1568
Chris Lattner57540c52011-04-15 05:22:18 +00001569 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001570 // replacement list.
1571 unsigned NumTokens = MI->getNumTokens();
1572 if (NumTokens != 0) {
1573 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1574 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001575 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001576 return;
1577 }
1578 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1579 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001580 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001581 return;
1582 }
1583 }
Mike Stump11289f42009-09-09 15:08:12 +00001584
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001585 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001586
Chris Lattnerf64b3522008-03-09 01:54:53 +00001587 // Finally, if this identifier already had a macro defined for it, verify that
1588 // the macro bodies are identical and free the old definition.
1589 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001590 // It is very common for system headers to have tons of macro redefinitions
1591 // and for warnings to be disabled in system headers. If this is the case,
1592 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001593 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001594 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001595 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001596 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001597
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001598 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001599 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001600 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001601 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001602 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1603 << MacroNameTok.getIdentifierInfo();
1604 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1605 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001606 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001607 if (OtherMI->isWarnIfUnused())
1608 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001609 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001610 }
Mike Stump11289f42009-09-09 15:08:12 +00001611
Chris Lattnerf64b3522008-03-09 01:54:53 +00001612 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001613
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001614 assert(!MI->isUsed());
1615 // If we need warning for not using the macro, add its location in the
1616 // warn-because-unused-macro set. If it gets used it will be removed from set.
1617 if (isInPrimaryFile() && // don't warn for include'd macros.
1618 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1619 MI->getDefinitionLoc()) != Diagnostic::Ignored) {
1620 MI->setIsWarnIfUnused(true);
1621 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1622 }
1623
Chris Lattner928e9092009-04-12 01:39:54 +00001624 // If the callbacks want to know, tell them about the macro definition.
1625 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001626 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001627}
1628
1629/// HandleUndefDirective - Implements #undef.
1630///
1631void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1632 ++NumUndefined;
1633
1634 Token MacroNameTok;
1635 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001636
Chris Lattnerf64b3522008-03-09 01:54:53 +00001637 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001638 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001639 return;
Mike Stump11289f42009-09-09 15:08:12 +00001640
Chris Lattnerf64b3522008-03-09 01:54:53 +00001641 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001642 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001643
Chris Lattnerf64b3522008-03-09 01:54:53 +00001644 // Okay, we finally have a valid identifier to undef.
1645 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001646
Chris Lattnerf64b3522008-03-09 01:54:53 +00001647 // If the macro is not defined, this is a noop undef, just return.
1648 if (MI == 0) return;
1649
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00001650 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00001651 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001652
1653 // If the callbacks want to know, tell them about the macro #undef.
1654 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001655 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001656
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001657 if (MI->isWarnIfUnused())
1658 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1659
Chris Lattnerf64b3522008-03-09 01:54:53 +00001660 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001661 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001662 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1663}
1664
1665
1666//===----------------------------------------------------------------------===//
1667// Preprocessor Conditional Directive Handling.
1668//===----------------------------------------------------------------------===//
1669
1670/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1671/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1672/// if any tokens have been returned or pp-directives activated before this
1673/// #ifndef has been lexed.
1674///
1675void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1676 bool ReadAnyTokensBeforeDirective) {
1677 ++NumIf;
1678 Token DirectiveTok = Result;
1679
1680 Token MacroNameTok;
1681 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001682
Chris Lattnerf64b3522008-03-09 01:54:53 +00001683 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001684 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001685 // Skip code until we get to #endif. This helps with recovery by not
1686 // emitting an error when the #endif is reached.
1687 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1688 /*Foundnonskip*/false, /*FoundElse*/false);
1689 return;
1690 }
Mike Stump11289f42009-09-09 15:08:12 +00001691
Chris Lattnerf64b3522008-03-09 01:54:53 +00001692 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001693 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001694
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001695 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1696 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001697
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001698 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001699 // If the start of a top-level #ifdef and if the macro is not defined,
1700 // inform MIOpt that this might be the start of a proper include guard.
1701 // Otherwise it is some other form of unknown conditional which we can't
1702 // handle.
1703 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001704 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001705 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001706 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001707 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001708 }
1709
Chris Lattnerf64b3522008-03-09 01:54:53 +00001710 // If there is a macro, process it.
1711 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001712 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001713
Chris Lattnerf64b3522008-03-09 01:54:53 +00001714 // Should we include the stuff contained by this directive?
1715 if (!MI == isIfndef) {
1716 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001717 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1718 /*wasskip*/false, /*foundnonskip*/true,
1719 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001720 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001721 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001722 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001723 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001724 /*FoundElse*/false);
1725 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001726
1727 if (Callbacks) {
1728 if (isIfndef)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001729 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001730 else
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001731 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001732 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001733}
1734
1735/// HandleIfDirective - Implements the #if directive.
1736///
1737void Preprocessor::HandleIfDirective(Token &IfToken,
1738 bool ReadAnyTokensBeforeDirective) {
1739 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001740
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001741 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001742 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001743 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1744 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1745 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001746
1747 // If this condition is equivalent to #ifndef X, and if this is the first
1748 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001749 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001750 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001751 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001752 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001753 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001754 }
1755
Chris Lattnerf64b3522008-03-09 01:54:53 +00001756 // Should we include the stuff contained by this directive?
1757 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001758 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001759 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001760 /*foundnonskip*/true, /*foundelse*/false);
1761 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001762 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00001763 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001764 /*FoundElse*/false);
1765 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001766
1767 if (Callbacks)
1768 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001769}
1770
1771/// HandleEndifDirective - Implements the #endif directive.
1772///
1773void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1774 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00001775
Chris Lattnerf64b3522008-03-09 01:54:53 +00001776 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001777 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00001778
Chris Lattnerf64b3522008-03-09 01:54:53 +00001779 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001780 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001781 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00001782 Diag(EndifToken, diag::err_pp_endif_without_if);
1783 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001784 }
Mike Stump11289f42009-09-09 15:08:12 +00001785
Chris Lattnerf64b3522008-03-09 01:54:53 +00001786 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001787 if (CurPPLexer->getConditionalStackDepth() == 0)
1788 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001789
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001790 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00001791 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001792
1793 if (Callbacks)
1794 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001795}
1796
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001797/// HandleElseDirective - Implements the #else directive.
1798///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001799void Preprocessor::HandleElseDirective(Token &Result) {
1800 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001801
Chris Lattnerf64b3522008-03-09 01:54:53 +00001802 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001803 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00001804
Chris Lattnerf64b3522008-03-09 01:54:53 +00001805 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001806 if (CurPPLexer->popConditionalLevel(CI)) {
1807 Diag(Result, diag::pp_err_else_without_if);
1808 return;
1809 }
Mike Stump11289f42009-09-09 15:08:12 +00001810
Chris Lattnerf64b3522008-03-09 01:54:53 +00001811 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001812 if (CurPPLexer->getConditionalStackDepth() == 0)
1813 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001814
1815 // If this is a #else with a #else before it, report the error.
1816 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00001817
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001818 // Finally, skip the rest of the contents of this block.
1819 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1820 /*FoundElse*/true);
1821
1822 if (Callbacks)
1823 Callbacks->Else();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001824}
1825
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001826/// HandleElifDirective - Implements the #elif directive.
1827///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001828void Preprocessor::HandleElifDirective(Token &ElifToken) {
1829 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001830
Chris Lattnerf64b3522008-03-09 01:54:53 +00001831 // #elif directive in a non-skipping conditional... start skipping.
1832 // We don't care what the condition is, because we will always skip it (since
1833 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001834 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001835 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001836 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001837
1838 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001839 if (CurPPLexer->popConditionalLevel(CI)) {
1840 Diag(ElifToken, diag::pp_err_elif_without_if);
1841 return;
1842 }
Mike Stump11289f42009-09-09 15:08:12 +00001843
Chris Lattnerf64b3522008-03-09 01:54:53 +00001844 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001845 if (CurPPLexer->getConditionalStackDepth() == 0)
1846 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001847
Chris Lattnerf64b3522008-03-09 01:54:53 +00001848 // If this is a #elif with a #else before it, report the error.
1849 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1850
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001851 // Finally, skip the rest of the contents of this block.
1852 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1853 /*FoundElse*/CI.FoundElse);
1854
1855 if (Callbacks)
1856 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001857}