blob: 140f793234af1e109b338c0f1f91fb1ed21d223c [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,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000196 bool FoundElse,
197 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000198 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000199 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000200
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000201 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000202 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000203
Ted Kremenek56572ab2008-12-12 18:34:08 +0000204 if (CurPTHLexer) {
205 PTHSkipExcludedConditionalBlock();
206 return;
207 }
Mike Stump11289f42009-09-09 15:08:12 +0000208
Chris Lattnerf64b3522008-03-09 01:54:53 +0000209 // Enter raw mode to disable identifier lookup (and thus macro expansion),
210 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000211 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000212 Token Tok;
213 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000214 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000215
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000216 if (Tok.is(tok::code_completion)) {
217 if (CodeComplete)
218 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000219 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000220 continue;
221 }
222
Chris Lattnerf64b3522008-03-09 01:54:53 +0000223 // If this is the end of the buffer, we have an error.
224 if (Tok.is(tok::eof)) {
225 // Emit errors for each unterminated conditional on the stack, including
226 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000227 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000228 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000229 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
230 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000231 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000232 }
233
Chris Lattnerf64b3522008-03-09 01:54:53 +0000234 // Just return and let the caller lex after this #include.
235 break;
236 }
Mike Stump11289f42009-09-09 15:08:12 +0000237
Chris Lattnerf64b3522008-03-09 01:54:53 +0000238 // If this token is not a preprocessor directive, just skip it.
239 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
240 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattnerf64b3522008-03-09 01:54:53 +0000242 // We just parsed a # character at the start of a line, so we're in
243 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000244 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000245 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000246 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000247
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattnerf64b3522008-03-09 01:54:53 +0000249 // Read the next token, the directive flavor.
250 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000251
Chris Lattnerf64b3522008-03-09 01:54:53 +0000252 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
253 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000254 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000255 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000256 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000257 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000258 continue;
259 }
260
261 // If the first letter isn't i or e, it isn't intesting to us. We know that
262 // this is safe in the face of spelling differences, because there is no way
263 // to spell an i/e in a strange way that is another letter. Skipping this
264 // allows us to avoid looking up the identifier info for #define/#undef and
265 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000266 const char *RawCharData = Tok.getRawIdentifierData();
267
Chris Lattnerf64b3522008-03-09 01:54:53 +0000268 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000269 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000270 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000271 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000272 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000273 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000274 continue;
275 }
Mike Stump11289f42009-09-09 15:08:12 +0000276
Chris Lattnerf64b3522008-03-09 01:54:53 +0000277 // Get the identifier name without trigraphs or embedded newlines. Note
278 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
279 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000280 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000281 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000282 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000283 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000284 } else {
285 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000286 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000287 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000288 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000289 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000290 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000291 continue;
292 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000293 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000294 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000295 }
Mike Stump11289f42009-09-09 15:08:12 +0000296
Benjamin Kramer144884642009-12-31 13:32:38 +0000297 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000298 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000299 if (Sub.empty() || // "if"
300 Sub == "def" || // "ifdef"
301 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000302 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
303 // bother parsing the condition.
304 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000305 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000306 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000307 /*foundelse*/false);
308
309 if (Callbacks)
310 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000311 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000312 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000313 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000314 if (Sub == "ndif") { // "endif"
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000315 CheckEndOfDirective("endif");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000316 PPConditionalInfo CondInfo;
317 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000318 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000319 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000320 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chris Lattnerf64b3522008-03-09 01:54:53 +0000322 // If we popped the outermost skipping block, we're done skipping!
323 if (!CondInfo.WasSkipping)
324 break;
Benjamin Kramer144884642009-12-31 13:32:38 +0000325 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000326 // #else directive in a skipping conditional. If not in some other
327 // skipping conditional, and if #else hasn't already been seen, enter it
328 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000329 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000330
Chris Lattnerf64b3522008-03-09 01:54:53 +0000331 // If this is a #else with a #else before it, report the error.
332 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000333
Chris Lattnerf64b3522008-03-09 01:54:53 +0000334 // Note that we've seen a #else in this conditional.
335 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000336
Chandler Carruth540960f2011-01-03 17:40:17 +0000337 if (Callbacks)
338 Callbacks->Else();
339
Chris Lattnerf64b3522008-03-09 01:54:53 +0000340 // If the conditional is at the top level, and the #if block wasn't
341 // entered, enter the #else block now.
342 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
343 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000344 CheckEndOfDirective("else");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000345 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000346 } else {
347 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000348 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000349 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000350 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000351
352 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000353 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000354 // If this is in a skipping block or if we're already handled this #if
355 // block, don't bother parsing the condition.
356 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
357 DiscardUntilEndOfDirective();
358 ShouldEnter = false;
359 } else {
360 // Restore the value of LexingRawMode so that identifiers are
361 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000362 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
363 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000364 IdentifierInfo *IfNDefMacro = 0;
365 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000366 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000367 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000368 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000369
Chris Lattnerf64b3522008-03-09 01:54:53 +0000370 // If this is a #elif with a #else before it, report the error.
371 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000372
Chandler Carruth540960f2011-01-03 17:40:17 +0000373 if (Callbacks)
374 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
375
Chris Lattnerf64b3522008-03-09 01:54:53 +0000376 // If this condition is true, enter it!
377 if (ShouldEnter) {
378 CondInfo.FoundNonSkip = true;
379 break;
380 }
381 }
382 }
Mike Stump11289f42009-09-09 15:08:12 +0000383
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000384 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000386 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000387 }
388
389 // Finally, if we are out of the conditional (saw an #endif or ran off the end
390 // of the file, just stop skipping and return to lexing whatever came after
391 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000392 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000393
394 if (Callbacks) {
395 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
396 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
397 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000398}
399
Ted Kremenek56572ab2008-12-12 18:34:08 +0000400void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000401
402 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000403 assert(CurPTHLexer);
404 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000405
Ted Kremenek56572ab2008-12-12 18:34:08 +0000406 // Skip to the next '#else', '#elif', or #endif.
407 if (CurPTHLexer->SkipBlock()) {
408 // We have reached an #endif. Both the '#' and 'endif' tokens
409 // have been consumed by the PTHLexer. Just pop off the condition level.
410 PPConditionalInfo CondInfo;
411 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000412 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000413 assert(!InCond && "Can't be skipping if not in a conditional!");
414 break;
415 }
Mike Stump11289f42009-09-09 15:08:12 +0000416
Ted Kremenek56572ab2008-12-12 18:34:08 +0000417 // We have reached a '#else' or '#elif'. Lex the next token to get
418 // the directive flavor.
419 Token Tok;
420 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000421
Ted Kremenek56572ab2008-12-12 18:34:08 +0000422 // We can actually look up the IdentifierInfo here since we aren't in
423 // raw mode.
424 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
425
426 if (K == tok::pp_else) {
427 // #else: Enter the else condition. We aren't in a nested condition
428 // since we skip those. We're always in the one matching the last
429 // blocked we skipped.
430 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
431 // Note that we've seen a #else in this conditional.
432 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000433
Ted Kremenek56572ab2008-12-12 18:34:08 +0000434 // If the #if block wasn't entered then enter the #else block now.
435 if (!CondInfo.FoundNonSkip) {
436 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000437
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000438 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000439 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000440 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000441 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000442
Ted Kremenek56572ab2008-12-12 18:34:08 +0000443 break;
444 }
Mike Stump11289f42009-09-09 15:08:12 +0000445
Ted Kremenek56572ab2008-12-12 18:34:08 +0000446 // Otherwise skip this block.
447 continue;
448 }
Mike Stump11289f42009-09-09 15:08:12 +0000449
Ted Kremenek56572ab2008-12-12 18:34:08 +0000450 assert(K == tok::pp_elif);
451 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
452
453 // If this is a #elif with a #else before it, report the error.
454 if (CondInfo.FoundElse)
455 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000456
Ted Kremenek56572ab2008-12-12 18:34:08 +0000457 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000458 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000459 if (CondInfo.FoundNonSkip)
460 continue;
461
462 // Evaluate the condition of the #elif.
463 IdentifierInfo *IfNDefMacro = 0;
464 CurPTHLexer->ParsingPreprocessorDirective = true;
465 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
466 CurPTHLexer->ParsingPreprocessorDirective = false;
467
468 // If this condition is true, enter it!
469 if (ShouldEnter) {
470 CondInfo.FoundNonSkip = true;
471 break;
472 }
473
474 // Otherwise, skip this block and go to the next one.
475 continue;
476 }
477}
478
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000479/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
480/// return null on failure. isAngled indicates whether the file reference is
481/// for system #include's or not (i.e. using <> instead of "").
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000482const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000483 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000484 bool isAngled,
485 const DirectoryLookup *FromDir,
486 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000487 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000488 SmallVectorImpl<char> *RelativePath,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000489 ModuleMap::Module **SuggestedModule,
490 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000491 // If the header lookup mechanism may be relative to the current file, pass in
492 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000493 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000494 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000495 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000496 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000497
Chris Lattner022923a2009-02-04 19:45:07 +0000498 // If there is no file entry associated with this file, it must be the
499 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000500 // it won't be scanned for preprocessor directives. If we have the
501 // predefines buffer, resolve #include references (which come from the
502 // -include command line argument) as if they came from the main file, this
503 // affects file lookup etc.
504 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000505 FID = SourceMgr.getMainFileID();
506 CurFileEnt = SourceMgr.getFileEntryForID(FID);
507 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000510 // Do a standard file entry lookup.
511 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000512 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000513 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000514 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerfde85352010-01-22 00:14:44 +0000515 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000517 // Otherwise, see if this is a subframework header. If so, this is relative
518 // to one of the headers on the #include stack. Walk the list of the current
519 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregor97eec242011-09-15 22:00:41 +0000520 // FIXME: SuggestedModule!
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000521 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000522 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000523 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000524 SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000525 return FE;
526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000528 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
529 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000530 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000531 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000532 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000533 if ((FE = HeaderInfo.LookupSubframeworkHeader(
534 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000535 return FE;
536 }
537 }
Mike Stump11289f42009-09-09 15:08:12 +0000538
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000539 // Otherwise, we really couldn't find the file.
540 return 0;
541}
542
Chris Lattnerf64b3522008-03-09 01:54:53 +0000543
544//===----------------------------------------------------------------------===//
545// Preprocessor Directive Handling.
546//===----------------------------------------------------------------------===//
547
548/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000549/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000550/// lexer/preprocessor state, and advances the lexer(s) so that the next token
551/// read is the correct one.
552void Preprocessor::HandleDirective(Token &Result) {
553 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattnerf64b3522008-03-09 01:54:53 +0000555 // We just parsed a # character at the start of a line, so we're in directive
556 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000557 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000558 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000559
Chris Lattnerf64b3522008-03-09 01:54:53 +0000560 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000561
Chris Lattnerf64b3522008-03-09 01:54:53 +0000562 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000563 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000564 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000565 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000566
Chris Lattner2d17ab72009-03-18 21:00:25 +0000567 // Save the '#' token in case we need to return it later.
568 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000569
Chris Lattnerf64b3522008-03-09 01:54:53 +0000570 // Read the next token, the directive flavor. This isn't expanded due to
571 // C99 6.10.3p8.
572 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000573
Chris Lattnerf64b3522008-03-09 01:54:53 +0000574 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
575 // #define A(x) #x
576 // A(abc
577 // #warning blah
578 // def)
579 // If so, the user is relying on non-portable behavior, emit a diagnostic.
580 if (InMacroArgs)
581 Diag(Result, diag::ext_embedded_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000582
Chris Lattnerf64b3522008-03-09 01:54:53 +0000583TryAgain:
584 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000585 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000586 return; // null directive.
587 case tok::comment:
588 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
589 LexUnexpandedToken(Result);
590 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000591 case tok::code_completion:
592 if (CodeComplete)
593 CodeComplete->CodeCompleteDirective(
594 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000595 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000596 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000597 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000598 if (getLangOptions().AsmPreprocessor)
599 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000600 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000601 default:
602 IdentifierInfo *II = Result.getIdentifierInfo();
603 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000604
Chris Lattnerf64b3522008-03-09 01:54:53 +0000605 // Ask what the preprocessor keyword ID is.
606 switch (II->getPPKeywordID()) {
607 default: break;
608 // C99 6.10.1 - Conditional Inclusion.
609 case tok::pp_if:
610 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
611 case tok::pp_ifdef:
612 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
613 case tok::pp_ifndef:
614 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
615 case tok::pp_elif:
616 return HandleElifDirective(Result);
617 case tok::pp_else:
618 return HandleElseDirective(Result);
619 case tok::pp_endif:
620 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000621
Chris Lattnerf64b3522008-03-09 01:54:53 +0000622 // C99 6.10.2 - Source File Inclusion.
623 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000624 // Handle #include.
625 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000626 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000627 // Handle -imacros.
628 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000629
Chris Lattnerf64b3522008-03-09 01:54:53 +0000630 // C99 6.10.3 - Macro Replacement.
631 case tok::pp_define:
632 return HandleDefineDirective(Result);
633 case tok::pp_undef:
634 return HandleUndefDirective(Result);
635
636 // C99 6.10.4 - Line Control.
637 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000638 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000639
Chris Lattnerf64b3522008-03-09 01:54:53 +0000640 // C99 6.10.5 - Error Directive.
641 case tok::pp_error:
642 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000643
Chris Lattnerf64b3522008-03-09 01:54:53 +0000644 // C99 6.10.6 - Pragma Directive.
645 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000646 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000647
Chris Lattnerf64b3522008-03-09 01:54:53 +0000648 // GNU Extensions.
649 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000650 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000651 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000652 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000653
Chris Lattnerf64b3522008-03-09 01:54:53 +0000654 case tok::pp_warning:
655 Diag(Result, diag::ext_pp_warning_directive);
656 return HandleUserDiagnosticDirective(Result, true);
657 case tok::pp_ident:
658 return HandleIdentSCCSDirective(Result);
659 case tok::pp_sccs:
660 return HandleIdentSCCSDirective(Result);
661 case tok::pp_assert:
662 //isExtension = true; // FIXME: implement #assert
663 break;
664 case tok::pp_unassert:
665 //isExtension = true; // FIXME: implement #unassert
666 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000667
668 case tok::pp___export_macro__:
669 return HandleMacroExportDirective(Result);
Douglas Gregorebf00492011-10-17 15:32:29 +0000670 case tok::pp___private_macro__:
671 return HandleMacroPrivateDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000672 }
673 break;
674 }
Mike Stump11289f42009-09-09 15:08:12 +0000675
Chris Lattner2d17ab72009-03-18 21:00:25 +0000676 // If this is a .S file, treat unknown # directives as non-preprocessor
677 // directives. This is important because # may be a comment or introduce
678 // various pseudo-ops. Just return the # token and push back the following
679 // token to be lexed next time.
680 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000681 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000682 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000683 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000684 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000685
686 // If the second token is a hashhash token, then we need to translate it to
687 // unknown so the token lexer doesn't try to perform token pasting.
688 if (Result.is(tok::hashhash))
689 Toks[1].setKind(tok::unknown);
690
Chris Lattner2d17ab72009-03-18 21:00:25 +0000691 // Enter this token stream so that we re-lex the tokens. Make sure to
692 // enable macro expansion, in case the token after the # is an identifier
693 // that is expanded.
694 EnterTokenStream(Toks, 2, false, true);
695 return;
696 }
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattnerf64b3522008-03-09 01:54:53 +0000698 // If we reached here, the preprocessing token is not valid!
699 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000700
Chris Lattnerf64b3522008-03-09 01:54:53 +0000701 // Read the rest of the PP line.
702 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000703
Chris Lattnerf64b3522008-03-09 01:54:53 +0000704 // Okay, we're done parsing the directive.
705}
706
Chris Lattner76e68962009-01-26 06:19:46 +0000707/// GetLineValue - Convert a numeric token into an unsigned value, emitting
708/// Diagnostic DiagID if it is invalid, and returning the value in Val.
709static bool GetLineValue(Token &DigitTok, unsigned &Val,
710 unsigned DiagID, Preprocessor &PP) {
711 if (DigitTok.isNot(tok::numeric_constant)) {
712 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000713
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000714 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000715 PP.DiscardUntilEndOfDirective();
716 return true;
717 }
Mike Stump11289f42009-09-09 15:08:12 +0000718
Chris Lattner76e68962009-01-26 06:19:46 +0000719 llvm::SmallString<64> IntegerBuffer;
720 IntegerBuffer.resize(DigitTok.getLength());
721 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000722 bool Invalid = false;
723 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
724 if (Invalid)
725 return true;
726
Chris Lattnerd66f1722009-04-18 18:35:15 +0000727 // Verify that we have a simple digit-sequence, and compute the value. This
728 // is always a simple digit string computed in decimal, so we do this manually
729 // here.
730 Val = 0;
731 for (unsigned i = 0; i != ActualLength; ++i) {
732 if (!isdigit(DigitTokBegin[i])) {
733 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
734 diag::err_pp_line_digit_sequence);
735 PP.DiscardUntilEndOfDirective();
736 return true;
737 }
Mike Stump11289f42009-09-09 15:08:12 +0000738
Chris Lattnerd66f1722009-04-18 18:35:15 +0000739 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
740 if (NextVal < Val) { // overflow.
741 PP.Diag(DigitTok, DiagID);
742 PP.DiscardUntilEndOfDirective();
743 return true;
744 }
745 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000746 }
Mike Stump11289f42009-09-09 15:08:12 +0000747
748 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000749 if (Val == 0) {
750 PP.Diag(DigitTok, DiagID);
751 PP.DiscardUntilEndOfDirective();
752 return true;
753 }
Mike Stump11289f42009-09-09 15:08:12 +0000754
Chris Lattnerd66f1722009-04-18 18:35:15 +0000755 if (DigitTokBegin[0] == '0')
756 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000757
Chris Lattner76e68962009-01-26 06:19:46 +0000758 return false;
759}
760
Mike Stump11289f42009-09-09 15:08:12 +0000761/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner100c65e2009-01-26 05:29:08 +0000762/// acceptable forms are:
763/// # line digit-sequence
764/// # line digit-sequence "s-char-sequence"
765void Preprocessor::HandleLineDirective(Token &Tok) {
766 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
767 // expanded.
768 Token DigitTok;
769 Lex(DigitTok);
770
Chris Lattner100c65e2009-01-26 05:29:08 +0000771 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000772 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000773 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000774 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000775
Chris Lattner76e68962009-01-26 06:19:46 +0000776 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
777 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000778 unsigned LineLimit = 32768U;
779 if (Features.C99 || Features.CPlusPlus0x)
780 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000781 if (LineNo >= LineLimit)
782 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smithacd4d3d2011-10-15 01:18:56 +0000783 else if (Features.CPlusPlus0x && LineNo >= 32768U)
784 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000785
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000786 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000787 Token StrTok;
788 Lex(StrTok);
789
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000790 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
791 // string followed by eod.
792 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000793 ; // ok
794 else if (StrTok.isNot(tok::string_literal)) {
795 Diag(StrTok, diag::err_pp_line_invalid_filename);
796 DiscardUntilEndOfDirective();
797 return;
798 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000799 // Parse and validate the string, converting it into a unique ID.
800 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000801 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000802 if (Literal.hadError)
803 return DiscardUntilEndOfDirective();
804 if (Literal.Pascal) {
805 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
806 return DiscardUntilEndOfDirective();
807 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000808 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000809
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000810 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000811 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
812 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000813 }
Mike Stump11289f42009-09-09 15:08:12 +0000814
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000815 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000816
Chris Lattner839150e2009-03-27 17:13:49 +0000817 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000818 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
819 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000820 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000821}
822
Chris Lattner76e68962009-01-26 06:19:46 +0000823/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
824/// marker directive.
825static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
826 bool &IsSystemHeader, bool &IsExternCHeader,
827 Preprocessor &PP) {
828 unsigned FlagVal;
829 Token FlagTok;
830 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000831 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000832 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
833 return true;
834
835 if (FlagVal == 1) {
836 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000837
Chris Lattner76e68962009-01-26 06:19:46 +0000838 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000839 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000840 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
841 return true;
842 } else if (FlagVal == 2) {
843 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000844
Chris Lattner1c967782009-02-04 06:25:26 +0000845 SourceManager &SM = PP.getSourceManager();
846 // If we are leaving the current presumed file, check to make sure the
847 // presumed include stack isn't empty!
848 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000849 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000850 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000851 if (PLoc.isInvalid())
852 return true;
853
Chris Lattner1c967782009-02-04 06:25:26 +0000854 // If there is no include loc (main file) or if the include loc is in a
855 // different physical file, then we aren't in a "1" line marker flag region.
856 SourceLocation IncLoc = PLoc.getIncludeLoc();
857 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000858 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000859 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
860 PP.DiscardUntilEndOfDirective();
861 return true;
862 }
Mike Stump11289f42009-09-09 15:08:12 +0000863
Chris Lattner76e68962009-01-26 06:19:46 +0000864 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000865 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000866 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
867 return true;
868 }
869
870 // We must have 3 if there are still flags.
871 if (FlagVal != 3) {
872 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000873 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000874 return true;
875 }
Mike Stump11289f42009-09-09 15:08:12 +0000876
Chris Lattner76e68962009-01-26 06:19:46 +0000877 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000878
Chris Lattner76e68962009-01-26 06:19:46 +0000879 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000880 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000881 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000882 return true;
883
884 // We must have 4 if there is yet another flag.
885 if (FlagVal != 4) {
886 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000887 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000888 return true;
889 }
Mike Stump11289f42009-09-09 15:08:12 +0000890
Chris Lattner76e68962009-01-26 06:19:46 +0000891 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000892
Chris Lattner76e68962009-01-26 06:19:46 +0000893 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000894 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000895
896 // There are no more valid flags here.
897 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000898 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000899 return true;
900}
901
902/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
903/// one of the following forms:
904///
905/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000906/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000907/// # 42 "file" ('1' | '2')? '3' '4'?
908///
909void Preprocessor::HandleDigitDirective(Token &DigitTok) {
910 // Validate the number and convert it to an unsigned. GNU does not have a
911 // line # limit other than it fit in 32-bits.
912 unsigned LineNo;
913 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
914 *this))
915 return;
Mike Stump11289f42009-09-09 15:08:12 +0000916
Chris Lattner76e68962009-01-26 06:19:46 +0000917 Token StrTok;
918 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000919
Chris Lattner76e68962009-01-26 06:19:46 +0000920 bool IsFileEntry = false, IsFileExit = false;
921 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000922 int FilenameID = -1;
923
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000924 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
925 // string followed by eod.
926 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000927 ; // ok
928 else if (StrTok.isNot(tok::string_literal)) {
929 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000930 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000931 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000932 // Parse and validate the string, converting it into a unique ID.
933 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000934 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000935 if (Literal.hadError)
936 return DiscardUntilEndOfDirective();
937 if (Literal.Pascal) {
938 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
939 return DiscardUntilEndOfDirective();
940 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000941 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattner76e68962009-01-26 06:19:46 +0000943 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +0000944 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000945 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +0000946 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000947 }
Mike Stump11289f42009-09-09 15:08:12 +0000948
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000949 // Create a line note with this information.
950 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +0000951 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000952 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +0000953
Chris Lattner839150e2009-03-27 17:13:49 +0000954 // If the preprocessor has callbacks installed, notify them of the #line
955 // change. This is used so that the line marker comes out in -E mode for
956 // example.
957 if (Callbacks) {
958 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
959 if (IsFileEntry)
960 Reason = PPCallbacks::EnterFile;
961 else if (IsFileExit)
962 Reason = PPCallbacks::ExitFile;
963 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
964 if (IsExternCHeader)
965 FileKind = SrcMgr::C_ExternCSystem;
966 else if (IsSystemHeader)
967 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattnerc745cec2010-04-14 04:28:50 +0000969 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +0000970 }
Chris Lattner76e68962009-01-26 06:19:46 +0000971}
972
973
Chris Lattner38d7fd22009-01-26 05:30:54 +0000974/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
975///
Mike Stump11289f42009-09-09 15:08:12 +0000976void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000977 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +0000978 // PTH doesn't emit #warning or #error directives.
979 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +0000980 return CurPTHLexer->DiscardToEndOfLine();
981
Chris Lattnerf64b3522008-03-09 01:54:53 +0000982 // Read the rest of the line raw. We do this because we don't want macros
983 // to be expanded and we don't require that the tokens be valid preprocessing
984 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
985 // collapse multiple consequtive white space between tokens, but this isn't
986 // specified by the standard.
Chris Lattner100c65e2009-01-26 05:29:08 +0000987 std::string Message = CurLexer->ReadToEndOfLine();
988 if (isWarning)
989 Diag(Tok, diag::pp_hash_warning) << Message;
990 else
991 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000992}
993
994/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
995///
996void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
997 // Yes, this directive is an extension.
998 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000999
Chris Lattnerf64b3522008-03-09 01:54:53 +00001000 // Read the string argument.
1001 Token StrTok;
1002 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001003
Chris Lattnerf64b3522008-03-09 01:54:53 +00001004 // If the token kind isn't a string, it's a malformed directive.
1005 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001006 StrTok.isNot(tok::wide_string_literal)) {
1007 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001008 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001009 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001010 return;
1011 }
Mike Stump11289f42009-09-09 15:08:12 +00001012
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001013 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001014 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001015
Douglas Gregordc970f02010-03-16 22:30:13 +00001016 if (Callbacks) {
1017 bool Invalid = false;
1018 std::string Str = getSpelling(StrTok, &Invalid);
1019 if (!Invalid)
1020 Callbacks->Ident(Tok.getLocation(), Str);
1021 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001022}
1023
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001024/// \brief Handle a #__export_macro__ directive.
1025void Preprocessor::HandleMacroExportDirective(Token &Tok) {
1026 Token MacroNameTok;
1027 ReadMacroName(MacroNameTok, 2);
1028
1029 // Error reading macro name? If so, diagnostic already issued.
1030 if (MacroNameTok.is(tok::eod))
1031 return;
1032
1033 // Check to see if this is the last token on the #__export_macro__ line.
1034 CheckEndOfDirective("__export_macro__");
1035
1036 // Okay, we finally have a valid identifier to undef.
1037 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1038
1039 // If the macro is not defined, this is an error.
1040 if (MI == 0) {
Douglas Gregorebf00492011-10-17 15:32:29 +00001041 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001042 << MacroNameTok.getIdentifierInfo();
1043 return;
1044 }
1045
1046 // Note that this macro has now been exported.
Douglas Gregorebf00492011-10-17 15:32:29 +00001047 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1048
1049 // If this macro definition came from a PCH file, mark it
1050 // as having changed since serialization.
1051 if (MI->isFromAST())
1052 MI->setChangedAfterLoad();
1053}
1054
1055/// \brief Handle a #__private_macro__ directive.
1056void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1057 Token MacroNameTok;
1058 ReadMacroName(MacroNameTok, 2);
1059
1060 // Error reading macro name? If so, diagnostic already issued.
1061 if (MacroNameTok.is(tok::eod))
1062 return;
1063
1064 // Check to see if this is the last token on the #__private_macro__ line.
1065 CheckEndOfDirective("__private_macro__");
1066
1067 // Okay, we finally have a valid identifier to undef.
1068 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1069
1070 // If the macro is not defined, this is an error.
1071 if (MI == 0) {
1072 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1073 << MacroNameTok.getIdentifierInfo();
1074 return;
1075 }
1076
1077 // Note that this macro has now been marked private.
1078 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001079
1080 // If this macro definition came from a PCH file, mark it
1081 // as having changed since serialization.
1082 if (MI->isFromAST())
1083 MI->setChangedAfterLoad();
1084}
1085
Chris Lattnerf64b3522008-03-09 01:54:53 +00001086//===----------------------------------------------------------------------===//
1087// Preprocessor Include Directive Handling.
1088//===----------------------------------------------------------------------===//
1089
1090/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1091/// checked and spelled filename, e.g. as an operand of #include. This returns
1092/// true if the input filename was in <>'s or false if it were in ""'s. The
1093/// caller is expected to provide a buffer that is large enough to hold the
1094/// spelling of the filename, but is also expected to handle the case when
1095/// this method decides to use a different buffer.
1096bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001097 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001098 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001099 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001100
Chris Lattnerf64b3522008-03-09 01:54:53 +00001101 // Make sure the filename is <x> or "x".
1102 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001103 if (Buffer[0] == '<') {
1104 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001105 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001106 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001107 return true;
1108 }
1109 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001110 } else if (Buffer[0] == '"') {
1111 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001112 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001113 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001114 return true;
1115 }
1116 isAngled = false;
1117 } else {
1118 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001119 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001120 return true;
1121 }
Mike Stump11289f42009-09-09 15:08:12 +00001122
Chris Lattnerf64b3522008-03-09 01:54:53 +00001123 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001124 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001125 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001126 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001127 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001128 }
Mike Stump11289f42009-09-09 15:08:12 +00001129
Chris Lattnerf64b3522008-03-09 01:54:53 +00001130 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001131 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001132 return isAngled;
1133}
1134
1135/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1136/// from a macro as multiple tokens, which need to be glued together. This
1137/// occurs for code like:
1138/// #define FOO <a/b.h>
1139/// #include FOO
1140/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1141///
1142/// This code concatenates and consumes tokens up to the '>' token. It returns
1143/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001144/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001145bool Preprocessor::ConcatenateIncludeName(
Douglas Gregor796d76a2010-10-20 22:00:55 +00001146 llvm::SmallString<128> &FilenameBuffer,
1147 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001148 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001149
John Thompsonb5353522009-10-30 13:49:06 +00001150 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001151 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001152 End = CurTok.getLocation();
1153
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001154 // FIXME: Provide code completion for #includes.
1155 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001156 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001157 Lex(CurTok);
1158 continue;
1159 }
1160
Chris Lattnerf64b3522008-03-09 01:54:53 +00001161 // Append the spelling of this token to the buffer. If there was a space
1162 // before it, add it now.
1163 if (CurTok.hasLeadingSpace())
1164 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001165
Chris Lattnerf64b3522008-03-09 01:54:53 +00001166 // Get the spelling of the token, directly into FilenameBuffer if possible.
1167 unsigned PreAppendSize = FilenameBuffer.size();
1168 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001169
Chris Lattnerf64b3522008-03-09 01:54:53 +00001170 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001171 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001172
Chris Lattnerf64b3522008-03-09 01:54:53 +00001173 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1174 if (BufPtr != &FilenameBuffer[PreAppendSize])
1175 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001176
Chris Lattnerf64b3522008-03-09 01:54:53 +00001177 // Resize FilenameBuffer to the correct size.
1178 if (CurTok.getLength() != ActualLen)
1179 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001180
Chris Lattnerf64b3522008-03-09 01:54:53 +00001181 // If we found the '>' marker, return success.
1182 if (CurTok.is(tok::greater))
1183 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001184
John Thompsonb5353522009-10-30 13:49:06 +00001185 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001186 }
1187
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001188 // If we hit the eod marker, emit an error and return true so that the caller
1189 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001190 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001191 return true;
1192}
1193
1194/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1195/// file to be included from the lexer, then include it! This is a common
1196/// routine with functionality shared between #include, #include_next and
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001197/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001198/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001199void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1200 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001201 const DirectoryLookup *LookupFrom,
1202 bool isImport) {
1203
1204 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001205 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001206
Chris Lattnerf64b3522008-03-09 01:54:53 +00001207 // Reserve a buffer to get the spelling.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001208 llvm::SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001209 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001210 SourceLocation End;
1211
Chris Lattnerf64b3522008-03-09 01:54:53 +00001212 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001213 case tok::eod:
1214 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001215 return;
Mike Stump11289f42009-09-09 15:08:12 +00001216
Chris Lattnerf64b3522008-03-09 01:54:53 +00001217 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001218 case tok::string_literal:
1219 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001220 End = FilenameTok.getLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001221 break;
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattnerf64b3522008-03-09 01:54:53 +00001223 case tok::less:
1224 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1225 // case, glue the tokens together into FilenameBuffer and interpret those.
1226 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001227 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001228 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001229 Filename = FilenameBuffer.str();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001230 break;
1231 default:
1232 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1233 DiscardUntilEndOfDirective();
1234 return;
1235 }
Mike Stump11289f42009-09-09 15:08:12 +00001236
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001237 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001238 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001239 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1240 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001241 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001242 DiscardUntilEndOfDirective();
1243 return;
1244 }
Mike Stump11289f42009-09-09 15:08:12 +00001245
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001246 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001247 // we allow macros that expand to nothing after the filename, because this
1248 // falls into the category of "#include pp-tokens new-line" specified in
1249 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001250 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001251
1252 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001253 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1254 Diag(FilenameTok, diag::err_pp_include_too_deep);
1255 return;
1256 }
Mike Stump11289f42009-09-09 15:08:12 +00001257
John McCall32f5fe12011-09-30 05:12:12 +00001258 // Complain about attempts to #include files in an audit pragma.
1259 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1260 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1261 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1262
1263 // Immediately leave the pragma.
1264 PragmaARCCFCodeAuditedLoc = SourceLocation();
1265 }
1266
Chris Lattnerf64b3522008-03-09 01:54:53 +00001267 // Search include directories.
1268 const DirectoryLookup *CurDir;
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001269 llvm::SmallString<1024> SearchPath;
1270 llvm::SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001271 // We get the raw path only if we have 'Callbacks' to which we later pass
1272 // the path.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001273 ModuleMap::Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001274 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001275 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001276 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
1277 AutoModuleImport? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001278
Douglas Gregor97eec242011-09-15 22:00:41 +00001279 // If we are supposed to import a module rather than including the header,
1280 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001281 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001282 // Compute the module access path corresponding to this module.
1283 // FIXME: Should we have a second loadModule() overload to avoid this
1284 // extra lookup step?
1285 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1286 for (ModuleMap::Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
1287 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1288 FilenameTok.getLocation()));
1289 std::reverse(Path.begin(), Path.end());
1290
1291 // Load the module.
1292 TheModuleLoader.loadModule(IncludeTok.getLocation(), Path);
Douglas Gregor97eec242011-09-15 22:00:41 +00001293 return;
1294 }
1295
Douglas Gregor8ad31c22011-11-20 17:46:46 +00001296 if (Callbacks) {
1297 if (!File) {
1298 // Give the clients a chance to recover.
1299 llvm::SmallString<128> RecoveryPath;
1300 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1301 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1302 // Add the recovery path to the list of search paths.
1303 DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
1304 HeaderInfo.AddSearchPath(DL, isAngled);
1305
1306 // Try the lookup again, skipping the cache.
1307 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
1308 AutoModuleImport ? &SuggestedModule : 0,
1309 /*SkipCache*/true);
1310 }
1311 }
1312 }
1313
1314 // Notify the callback object that we've seen an inclusion directive.
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001315 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001316 End, SearchPath, RelativePath);
Douglas Gregor8ad31c22011-11-20 17:46:46 +00001317 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001318
Peter Collingbourne77b0e7f22011-07-12 19:35:15 +00001319 if (File == 0) {
Eli Friedman3781a362011-08-30 23:07:51 +00001320 if (!SuppressIncludeNotFoundError)
1321 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Peter Collingbourne77b0e7f22011-07-12 19:35:15 +00001322 return;
1323 }
1324
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001325 // The #included file will be considered to be a system header if either it is
1326 // in a system include directory, or if the #includer is a system include
1327 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001328 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001329 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001330 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001331
Chris Lattner72286d62010-04-19 20:44:31 +00001332 // Ask HeaderInfo if we should enter this #include file. If not, #including
1333 // this file will have no effect.
1334 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001335 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001336 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001337 return;
1338 }
1339
Chris Lattnerf64b3522008-03-09 01:54:53 +00001340 // Look up the file, create a File ID for it.
Chris Lattnerd32480d2009-01-17 06:22:33 +00001341 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1342 FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001343 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001344
1345 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001346 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001347}
1348
1349/// HandleIncludeNextDirective - Implements #include_next.
1350///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001351void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1352 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001353 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001354
Chris Lattnerf64b3522008-03-09 01:54:53 +00001355 // #include_next is like #include, except that we start searching after
1356 // the current found directory. If we can't do this, issue a
1357 // diagnostic.
1358 const DirectoryLookup *Lookup = CurDirLookup;
1359 if (isInPrimaryFile()) {
1360 Lookup = 0;
1361 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1362 } else if (Lookup == 0) {
1363 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1364 } else {
1365 // Start looking up in the next directory.
1366 ++Lookup;
1367 }
Mike Stump11289f42009-09-09 15:08:12 +00001368
Douglas Gregor796d76a2010-10-20 22:00:55 +00001369 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001370}
1371
1372/// HandleImportDirective - Implements #import.
1373///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001374void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1375 Token &ImportTok) {
Chris Lattnerd4a96732009-03-06 04:28:03 +00001376 if (!Features.ObjC1) // #import is standard for ObjC.
1377 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001378
Douglas Gregor796d76a2010-10-20 22:00:55 +00001379 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001380}
1381
Chris Lattner58a1eb02009-04-08 18:46:40 +00001382/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1383/// pseudo directive in the predefines buffer. This handles it by sucking all
1384/// tokens through the preprocessor and discarding them (only keeping the side
1385/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001386void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1387 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001388 // This directive should only occur in the predefines buffer. If not, emit an
1389 // error and reject it.
1390 SourceLocation Loc = IncludeMacrosTok.getLocation();
1391 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1392 Diag(IncludeMacrosTok.getLocation(),
1393 diag::pp_include_macros_out_of_predefines);
1394 DiscardUntilEndOfDirective();
1395 return;
1396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Chris Lattnere01d82b2009-04-08 20:53:24 +00001398 // Treat this as a normal #include for checking purposes. If this is
1399 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001400 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001401
Chris Lattnere01d82b2009-04-08 20:53:24 +00001402 Token TmpTok;
1403 do {
1404 Lex(TmpTok);
1405 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1406 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001407}
1408
Chris Lattnerf64b3522008-03-09 01:54:53 +00001409//===----------------------------------------------------------------------===//
1410// Preprocessor Macro Directive Handling.
1411//===----------------------------------------------------------------------===//
1412
1413/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1414/// definition has just been read. Lex the rest of the arguments and the
1415/// closing ), updating MI with what we learn. Return true if an error occurs
1416/// parsing the arg list.
1417bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001418 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001419
Chris Lattnerf64b3522008-03-09 01:54:53 +00001420 Token Tok;
1421 while (1) {
1422 LexUnexpandedToken(Tok);
1423 switch (Tok.getKind()) {
1424 case tok::r_paren:
1425 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001426 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001427 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001428 // Otherwise we have #define FOO(A,)
1429 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1430 return true;
1431 case tok::ellipsis: // #define X(... -> C99 varargs
Richard Smithacd4d3d2011-10-15 01:18:56 +00001432 if (!Features.C99)
1433 Diag(Tok, Features.CPlusPlus0x ?
1434 diag::warn_cxx98_compat_variadic_macro :
1435 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001436
1437 // Lex the token after the identifier.
1438 LexUnexpandedToken(Tok);
1439 if (Tok.isNot(tok::r_paren)) {
1440 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1441 return true;
1442 }
1443 // Add the __VA_ARGS__ identifier as an argument.
1444 Arguments.push_back(Ident__VA_ARGS__);
1445 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001446 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001447 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001448 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001449 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1450 return true;
1451 default:
1452 // Handle keywords and identifiers here to accept things like
1453 // #define Foo(for) for.
1454 IdentifierInfo *II = Tok.getIdentifierInfo();
1455 if (II == 0) {
1456 // #define X(1
1457 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1458 return true;
1459 }
1460
1461 // If this is already used as an argument, it is used multiple times (e.g.
1462 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001463 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001464 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001465 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001466 return true;
1467 }
Mike Stump11289f42009-09-09 15:08:12 +00001468
Chris Lattnerf64b3522008-03-09 01:54:53 +00001469 // Add the argument to the macro info.
1470 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001471
Chris Lattnerf64b3522008-03-09 01:54:53 +00001472 // Lex the token after the identifier.
1473 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001474
Chris Lattnerf64b3522008-03-09 01:54:53 +00001475 switch (Tok.getKind()) {
1476 default: // #define X(A B
1477 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1478 return true;
1479 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001480 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001481 return false;
1482 case tok::comma: // #define X(A,
1483 break;
1484 case tok::ellipsis: // #define X(A... -> GCC extension
1485 // Diagnose extension.
1486 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001487
Chris Lattnerf64b3522008-03-09 01:54:53 +00001488 // Lex the token after the identifier.
1489 LexUnexpandedToken(Tok);
1490 if (Tok.isNot(tok::r_paren)) {
1491 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1492 return true;
1493 }
Mike Stump11289f42009-09-09 15:08:12 +00001494
Chris Lattnerf64b3522008-03-09 01:54:53 +00001495 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001496 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001497 return false;
1498 }
1499 }
1500 }
1501}
1502
1503/// HandleDefineDirective - Implements #define. This consumes the entire macro
1504/// line then lets the caller lex the next real token.
1505void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1506 ++NumDefined;
1507
1508 Token MacroNameTok;
1509 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001510
Chris Lattnerf64b3522008-03-09 01:54:53 +00001511 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001512 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001513 return;
1514
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001515 Token LastTok = MacroNameTok;
1516
Chris Lattnerf64b3522008-03-09 01:54:53 +00001517 // If we are supposed to keep comments in #defines, reenable comment saving
1518 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001519 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001520
Chris Lattnerf64b3522008-03-09 01:54:53 +00001521 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001522 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001523
Chris Lattnerf64b3522008-03-09 01:54:53 +00001524 Token Tok;
1525 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattnerf64b3522008-03-09 01:54:53 +00001527 // If this is a function-like macro definition, parse the argument list,
1528 // marking each of the identifiers as being used as macro arguments. Also,
1529 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001530 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001531 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001532 } else if (Tok.hasLeadingSpace()) {
1533 // This is a normal token with leading space. Clear the leading space
1534 // marker on the first token to get proper expansion.
1535 Tok.clearFlag(Token::LeadingSpace);
1536 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001537 // This is a function-like macro definition. Read the argument list.
1538 MI->setIsFunctionLike();
1539 if (ReadMacroDefinitionArgList(MI)) {
1540 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001541 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001542 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001543 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001544 DiscardUntilEndOfDirective();
1545 return;
1546 }
1547
Chris Lattner249c38b2009-04-19 18:26:34 +00001548 // If this is a definition of a variadic C99 function-like macro, not using
1549 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001550
Chris Lattner249c38b2009-04-19 18:26:34 +00001551 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1552 // This gets unpoisoned where it is allowed.
1553 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1554 if (MI->isC99Varargs())
1555 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001556
Chris Lattnerf64b3522008-03-09 01:54:53 +00001557 // Read the first token after the arg list for down below.
1558 LexUnexpandedToken(Tok);
Eli Friedman192e0342011-10-10 23:35:28 +00001559 } else if (Features.C99 || Features.CPlusPlus0x) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001560 // C99 requires whitespace between the macro definition and the body. Emit
1561 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001562 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001563 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001564 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1565 // first character of a replacement list is not a character required by
1566 // subclause 5.2.1, then there shall be white-space separation between the
1567 // identifier and the replacement list.". 5.2.1 lists this set:
1568 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1569 // is irrelevant here.
1570 bool isInvalid = false;
1571 if (Tok.is(tok::at)) // @ is not in the list above.
1572 isInvalid = true;
1573 else if (Tok.is(tok::unknown)) {
1574 // If we have an unknown token, it is something strange like "`". Since
1575 // all of valid characters would have lexed into a single character
1576 // token of some sort, we know this is not a valid case.
1577 isInvalid = true;
1578 }
1579 if (isInvalid)
1580 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1581 else
1582 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001583 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001584
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001585 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001586 LastTok = Tok;
1587
Chris Lattnerf64b3522008-03-09 01:54:53 +00001588 // Read the rest of the macro body.
1589 if (MI->isObjectLike()) {
1590 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001591 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001592 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001593 MI->AddTokenToBody(Tok);
1594 // Get the next token of the macro.
1595 LexUnexpandedToken(Tok);
1596 }
Mike Stump11289f42009-09-09 15:08:12 +00001597
Chris Lattnerf64b3522008-03-09 01:54:53 +00001598 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001599 // Otherwise, read the body of a function-like macro. While we are at it,
1600 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1601 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001602 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001603 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001604
Chris Lattnerf64b3522008-03-09 01:54:53 +00001605 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001606 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001607
Chris Lattnerf64b3522008-03-09 01:54:53 +00001608 // Get the next token of the macro.
1609 LexUnexpandedToken(Tok);
1610 continue;
1611 }
Mike Stump11289f42009-09-09 15:08:12 +00001612
Chris Lattnerf64b3522008-03-09 01:54:53 +00001613 // Get the next token of the macro.
1614 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001615
Chris Lattner83bd8282009-05-25 17:16:10 +00001616 // Check for a valid macro arg identifier.
1617 if (Tok.getIdentifierInfo() == 0 ||
1618 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1619
1620 // If this is assembler-with-cpp mode, we accept random gibberish after
1621 // the '#' because '#' is often a comment character. However, change
1622 // the kind of the token to tok::unknown so that the preprocessor isn't
1623 // confused.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001624 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001625 LastTok.setKind(tok::unknown);
1626 } else {
1627 Diag(Tok, diag::err_pp_stringize_not_parameter);
1628 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001629
Chris Lattner83bd8282009-05-25 17:16:10 +00001630 // Disable __VA_ARGS__ again.
1631 Ident__VA_ARGS__->setIsPoisoned(true);
1632 return;
1633 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001634 }
Mike Stump11289f42009-09-09 15:08:12 +00001635
Chris Lattner83bd8282009-05-25 17:16:10 +00001636 // Things look ok, add the '#' and param name tokens to the macro.
1637 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001638 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001639 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001640
Chris Lattnerf64b3522008-03-09 01:54:53 +00001641 // Get the next token of the macro.
1642 LexUnexpandedToken(Tok);
1643 }
1644 }
Mike Stump11289f42009-09-09 15:08:12 +00001645
1646
Chris Lattnerf64b3522008-03-09 01:54:53 +00001647 // Disable __VA_ARGS__ again.
1648 Ident__VA_ARGS__->setIsPoisoned(true);
1649
Chris Lattner57540c52011-04-15 05:22:18 +00001650 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001651 // replacement list.
1652 unsigned NumTokens = MI->getNumTokens();
1653 if (NumTokens != 0) {
1654 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1655 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001656 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001657 return;
1658 }
1659 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1660 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001661 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001662 return;
1663 }
1664 }
Mike Stump11289f42009-09-09 15:08:12 +00001665
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001666 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001667
Chris Lattnerf64b3522008-03-09 01:54:53 +00001668 // Finally, if this identifier already had a macro defined for it, verify that
1669 // the macro bodies are identical and free the old definition.
1670 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001671 // It is very common for system headers to have tons of macro redefinitions
1672 // and for warnings to be disabled in system headers. If this is the case,
1673 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001674 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001675 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001676 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001677 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001678
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001679 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001680 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001681 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001682 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001683 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1684 << MacroNameTok.getIdentifierInfo();
1685 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1686 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001687 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001688 if (OtherMI->isWarnIfUnused())
1689 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001690 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001691 }
Mike Stump11289f42009-09-09 15:08:12 +00001692
Chris Lattnerf64b3522008-03-09 01:54:53 +00001693 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001694
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001695 assert(!MI->isUsed());
1696 // If we need warning for not using the macro, add its location in the
1697 // warn-because-unused-macro set. If it gets used it will be removed from set.
1698 if (isInPrimaryFile() && // don't warn for include'd macros.
1699 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00001700 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001701 MI->setIsWarnIfUnused(true);
1702 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1703 }
1704
Chris Lattner928e9092009-04-12 01:39:54 +00001705 // If the callbacks want to know, tell them about the macro definition.
1706 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001707 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001708}
1709
1710/// HandleUndefDirective - Implements #undef.
1711///
1712void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1713 ++NumUndefined;
1714
1715 Token MacroNameTok;
1716 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001717
Chris Lattnerf64b3522008-03-09 01:54:53 +00001718 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001719 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001720 return;
Mike Stump11289f42009-09-09 15:08:12 +00001721
Chris Lattnerf64b3522008-03-09 01:54:53 +00001722 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001723 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001724
Chris Lattnerf64b3522008-03-09 01:54:53 +00001725 // Okay, we finally have a valid identifier to undef.
1726 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001727
Chris Lattnerf64b3522008-03-09 01:54:53 +00001728 // If the macro is not defined, this is a noop undef, just return.
1729 if (MI == 0) return;
1730
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00001731 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00001732 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001733
1734 // If the callbacks want to know, tell them about the macro #undef.
1735 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001736 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001737
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001738 if (MI->isWarnIfUnused())
1739 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1740
Chris Lattnerf64b3522008-03-09 01:54:53 +00001741 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001742 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001743 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1744}
1745
1746
1747//===----------------------------------------------------------------------===//
1748// Preprocessor Conditional Directive Handling.
1749//===----------------------------------------------------------------------===//
1750
1751/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1752/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1753/// if any tokens have been returned or pp-directives activated before this
1754/// #ifndef has been lexed.
1755///
1756void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1757 bool ReadAnyTokensBeforeDirective) {
1758 ++NumIf;
1759 Token DirectiveTok = Result;
1760
1761 Token MacroNameTok;
1762 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001763
Chris Lattnerf64b3522008-03-09 01:54:53 +00001764 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001765 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001766 // Skip code until we get to #endif. This helps with recovery by not
1767 // emitting an error when the #endif is reached.
1768 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1769 /*Foundnonskip*/false, /*FoundElse*/false);
1770 return;
1771 }
Mike Stump11289f42009-09-09 15:08:12 +00001772
Chris Lattnerf64b3522008-03-09 01:54:53 +00001773 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001774 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001775
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001776 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1777 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001778
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001779 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001780 // If the start of a top-level #ifdef and if the macro is not defined,
1781 // inform MIOpt that this might be the start of a proper include guard.
1782 // Otherwise it is some other form of unknown conditional which we can't
1783 // handle.
1784 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001785 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001786 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001787 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001788 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001789 }
1790
Chris Lattnerf64b3522008-03-09 01:54:53 +00001791 // If there is a macro, process it.
1792 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001793 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001794
Chris Lattnerf64b3522008-03-09 01:54:53 +00001795 // Should we include the stuff contained by this directive?
1796 if (!MI == isIfndef) {
1797 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001798 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1799 /*wasskip*/false, /*foundnonskip*/true,
1800 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001801 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001802 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001803 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001804 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001805 /*FoundElse*/false);
1806 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001807
1808 if (Callbacks) {
1809 if (isIfndef)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001810 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001811 else
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001812 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001813 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001814}
1815
1816/// HandleIfDirective - Implements the #if directive.
1817///
1818void Preprocessor::HandleIfDirective(Token &IfToken,
1819 bool ReadAnyTokensBeforeDirective) {
1820 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001821
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001822 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001823 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001824 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1825 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1826 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001827
1828 // If this condition is equivalent to #ifndef X, and if this is the first
1829 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001830 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001831 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001832 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001833 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001834 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001835 }
1836
Chris Lattnerf64b3522008-03-09 01:54:53 +00001837 // Should we include the stuff contained by this directive?
1838 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001839 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001840 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001841 /*foundnonskip*/true, /*foundelse*/false);
1842 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001843 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00001844 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001845 /*FoundElse*/false);
1846 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001847
1848 if (Callbacks)
1849 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001850}
1851
1852/// HandleEndifDirective - Implements the #endif directive.
1853///
1854void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1855 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00001856
Chris Lattnerf64b3522008-03-09 01:54:53 +00001857 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001858 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00001859
Chris Lattnerf64b3522008-03-09 01:54:53 +00001860 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001861 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001862 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00001863 Diag(EndifToken, diag::err_pp_endif_without_if);
1864 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001865 }
Mike Stump11289f42009-09-09 15:08:12 +00001866
Chris Lattnerf64b3522008-03-09 01:54:53 +00001867 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001868 if (CurPPLexer->getConditionalStackDepth() == 0)
1869 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001870
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001871 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00001872 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001873
1874 if (Callbacks)
1875 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001876}
1877
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001878/// HandleElseDirective - Implements the #else directive.
1879///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001880void Preprocessor::HandleElseDirective(Token &Result) {
1881 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001882
Chris Lattnerf64b3522008-03-09 01:54:53 +00001883 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001884 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00001885
Chris Lattnerf64b3522008-03-09 01:54:53 +00001886 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001887 if (CurPPLexer->popConditionalLevel(CI)) {
1888 Diag(Result, diag::pp_err_else_without_if);
1889 return;
1890 }
Mike Stump11289f42009-09-09 15:08:12 +00001891
Chris Lattnerf64b3522008-03-09 01:54:53 +00001892 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001893 if (CurPPLexer->getConditionalStackDepth() == 0)
1894 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001895
1896 // If this is a #else with a #else before it, report the error.
1897 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00001898
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001899 // Finally, skip the rest of the contents of this block.
1900 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00001901 /*FoundElse*/true, Result.getLocation());
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001902
1903 if (Callbacks)
1904 Callbacks->Else();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001905}
1906
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001907/// HandleElifDirective - Implements the #elif directive.
1908///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001909void Preprocessor::HandleElifDirective(Token &ElifToken) {
1910 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001911
Chris Lattnerf64b3522008-03-09 01:54:53 +00001912 // #elif directive in a non-skipping conditional... start skipping.
1913 // We don't care what the condition is, because we will always skip it (since
1914 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001915 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001916 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001917 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001918
1919 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001920 if (CurPPLexer->popConditionalLevel(CI)) {
1921 Diag(ElifToken, diag::pp_err_elif_without_if);
1922 return;
1923 }
Mike Stump11289f42009-09-09 15:08:12 +00001924
Chris Lattnerf64b3522008-03-09 01:54:53 +00001925 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001926 if (CurPPLexer->getConditionalStackDepth() == 0)
1927 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001928
Chris Lattnerf64b3522008-03-09 01:54:53 +00001929 // If this is a #elif with a #else before it, report the error.
1930 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1931
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001932 // Finally, skip the rest of the contents of this block.
1933 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00001934 /*FoundElse*/CI.FoundElse,
1935 ElifToken.getLocation());
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001936
1937 if (Callbacks)
1938 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001939}