blob: 2dfae872e2f6cbc58c67a2429cb39492b0b1eef2 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Chris Lattner359cc442009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf44e8542010-08-24 19:08:16 +000019#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregorfba18aa2011-09-15 22:00:41 +000020#include "clang/Lex/ModuleLoader.h"
Douglas Gregor80c60f72010-09-09 22:45:38 +000021#include "clang/Lex/Pragma.h"
Chris Lattner6e290142009-11-30 04:18:44 +000022#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000023#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000024#include "llvm/ADT/APInt.h"
Douglas Gregore3a82562011-11-30 18:02:36 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000026using namespace clang;
27
28//===----------------------------------------------------------------------===//
29// Utility Methods for Preprocessor Directive Handling.
30//===----------------------------------------------------------------------===//
31
Chris Lattnerf47724b2010-08-17 15:55:45 +000032MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenek9714a232010-10-19 22:15:20 +000033 MacroInfoChain *MIChain;
Mike Stump1eb44332009-09-09 15:08:12 +000034
Ted Kremenek9714a232010-10-19 22:15:20 +000035 if (MICache) {
36 MIChain = MICache;
37 MICache = MICache->Next;
Ted Kremenekaf8fa252010-10-19 18:16:54 +000038 }
Ted Kremenek9714a232010-10-19 22:15:20 +000039 else {
40 MIChain = BP.Allocate<MacroInfoChain>();
41 }
42
43 MIChain->Next = MIChainHead;
44 MIChain->Prev = 0;
45 if (MIChainHead)
46 MIChainHead->Prev = MIChain;
47 MIChainHead = MIChain;
48
49 return &(MIChain->MI);
Chris Lattnerf47724b2010-08-17 15:55:45 +000050}
51
52MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
53 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000054 new (MI) MacroInfo(L);
55 return MI;
56}
57
Chris Lattnerf47724b2010-08-17 15:55:45 +000058MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
59 MacroInfo *MI = AllocateMacroInfo();
60 new (MI) MacroInfo(MacroToClone, BP);
61 return MI;
62}
63
Chris Lattner0301b3f2009-02-20 22:19:20 +000064/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
65/// be reused for allocating new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000066void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenek9714a232010-10-19 22:15:20 +000067 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
68 if (MacroInfoChain *Prev = MIChain->Prev) {
69 MacroInfoChain *Next = MIChain->Next;
70 Prev->Next = Next;
71 if (Next)
72 Next->Prev = Prev;
73 }
74 else {
75 assert(MIChainHead == MIChain);
76 MIChainHead = MIChain->Next;
77 MIChainHead->Prev = 0;
78 }
79 MIChain->Next = MICache;
80 MICache = MIChain;
Chris Lattner0301b3f2009-02-20 22:19:20 +000081
Ted Kremenek9714a232010-10-19 22:15:20 +000082 MI->Destroy();
83}
Chris Lattner0301b3f2009-02-20 22:19:20 +000084
Chris Lattner141e71f2008-03-09 01:54:53 +000085/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
Peter Collingbourne84021552011-02-28 02:37:51 +000086/// current line until the tok::eod token is found.
Chris Lattner141e71f2008-03-09 01:54:53 +000087void Preprocessor::DiscardUntilEndOfDirective() {
88 Token Tmp;
89 do {
90 LexUnexpandedToken(Tmp);
Peter Collingbournea5ef5842011-02-22 13:49:06 +000091 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne84021552011-02-28 02:37:51 +000092 } while (Tmp.isNot(tok::eod));
Chris Lattner141e71f2008-03-09 01:54:53 +000093}
94
Chris Lattner141e71f2008-03-09 01:54:53 +000095/// ReadMacroName - Lex and validate a macro name, which occurs after a
Peter Collingbourne84021552011-02-28 02:37:51 +000096/// #define or #undef. This sets the token kind to eod and discards the rest
Chris Lattner141e71f2008-03-09 01:54:53 +000097/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
98/// this is due to a a #define, 2 if #undef directive, 0 if it is something
99/// else (e.g. #ifdef).
100void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
101 // Read the token, don't allow macro expansion on it.
102 LexUnexpandedToken(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000104 if (MacroNameTok.is(tok::code_completion)) {
105 if (CodeComplete)
106 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000107 setCodeCompletionReached();
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000108 LexUnexpandedToken(MacroNameTok);
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000109 }
110
Chris Lattner141e71f2008-03-09 01:54:53 +0000111 // Missing macro name?
Peter Collingbourne84021552011-02-28 02:37:51 +0000112 if (MacroNameTok.is(tok::eod)) {
Chris Lattner3692b092008-11-18 07:59:24 +0000113 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
114 return;
115 }
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Chris Lattner141e71f2008-03-09 01:54:53 +0000117 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
118 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +0000119 bool Invalid = false;
120 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
121 if (Invalid)
122 return;
123
Chris Lattner9485d232008-12-13 20:12:40 +0000124 const IdentifierInfo &Info = Identifiers.get(Spelling);
125 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000126 // C++ 2.5p2: Alternative tokens behave the same as its primary token
127 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000128 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +0000129 else
130 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
131 // Fall through on error.
132 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
133 // Error if defining "defined": C99 6.10.8.4.
134 Diag(MacroNameTok, diag::err_defined_macro_name);
135 } else if (isDefineUndef && II->hasMacroDefinition() &&
136 getMacroInfo(II)->isBuiltinMacro()) {
137 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
138 if (isDefineUndef == 1)
139 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
140 else
141 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
142 } else {
143 // Okay, we got a good identifier node. Return it.
144 return;
145 }
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Chris Lattner141e71f2008-03-09 01:54:53 +0000147 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne84021552011-02-28 02:37:51 +0000148 // token kind to tok::eod.
149 MacroNameTok.setKind(tok::eod);
Chris Lattner141e71f2008-03-09 01:54:53 +0000150 return DiscardUntilEndOfDirective();
151}
152
Peter Collingbourne84021552011-02-28 02:37:51 +0000153/// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
154/// not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattnerab82f412009-04-17 23:30:53 +0000155/// true, then we consider macros that expand to zero tokens as being ok.
156void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000157 Token Tmp;
Chris Lattnerab82f412009-04-17 23:30:53 +0000158 // Lex unexpanded tokens for most directives: macros might expand to zero
159 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
160 // #line) allow empty macros.
161 if (EnableMacros)
162 Lex(Tmp);
163 else
164 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Chris Lattner141e71f2008-03-09 01:54:53 +0000166 // There should be no tokens after the directive, but we allow them as an
167 // extension.
168 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
169 LexUnexpandedToken(Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000170
Peter Collingbourne84021552011-02-28 02:37:51 +0000171 if (Tmp.isNot(tok::eod)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000172 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000173 // or if this is a macro-style preprocessing directive, because it is more
174 // trouble than it is worth to insert /**/ and check that there is no /**/
175 // in the range also.
Douglas Gregor849b2432010-03-31 17:46:05 +0000176 FixItHint Hint;
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000177 if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
178 !CurTokenLexer)
Douglas Gregor849b2432010-03-31 17:46:05 +0000179 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
180 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000181 DiscardUntilEndOfDirective();
182 }
183}
184
185
186
187/// SkipExcludedConditionalBlock - We just read a #if or related directive and
188/// decided that the subsequent tokens are in the #if'd out portion of the
189/// file. Lex the rest of the file, until we see an #endif. If
190/// FoundNonSkipPortion is true, then we have already emitted code for part of
191/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
192/// is true, then #else directives are ok, if not, then we have already seen one
193/// so a #else directive is a duplicate. When this returns, the caller can lex
194/// the first valid token.
195void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
196 bool FoundNonSkipPortion,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000197 bool FoundElse,
198 SourceLocation ElseLoc) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000199 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000200 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000201
Ted Kremenek60e45d42008-11-18 00:34:22 +0000202 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000203 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Ted Kremenek268ee702008-12-12 18:34:08 +0000205 if (CurPTHLexer) {
206 PTHSkipExcludedConditionalBlock();
207 return;
208 }
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Chris Lattner141e71f2008-03-09 01:54:53 +0000210 // Enter raw mode to disable identifier lookup (and thus macro expansion),
211 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000212 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000213 Token Tok;
214 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000215 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Douglas Gregorf44e8542010-08-24 19:08:16 +0000217 if (Tok.is(tok::code_completion)) {
218 if (CodeComplete)
219 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000220 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000221 continue;
222 }
223
Chris Lattner141e71f2008-03-09 01:54:53 +0000224 // If this is the end of the buffer, we have an error.
225 if (Tok.is(tok::eof)) {
226 // Emit errors for each unterminated conditional on the stack, including
227 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000228 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000229 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000230 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
231 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000232 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000233 }
234
Chris Lattner141e71f2008-03-09 01:54:53 +0000235 // Just return and let the caller lex after this #include.
236 break;
237 }
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattner141e71f2008-03-09 01:54:53 +0000239 // If this token is not a preprocessor directive, just skip it.
240 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
241 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chris Lattner141e71f2008-03-09 01:54:53 +0000243 // We just parsed a # character at the start of a line, so we're in
244 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne84021552011-02-28 02:37:51 +0000245 // converted into an EOD token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000246 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000247 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000248
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Chris Lattner141e71f2008-03-09 01:54:53 +0000250 // Read the next token, the directive flavor.
251 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Chris Lattner141e71f2008-03-09 01:54:53 +0000253 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
254 // something bogus), skip it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000255 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000256 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000257 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000258 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000259 continue;
260 }
261
262 // If the first letter isn't i or e, it isn't intesting to us. We know that
263 // this is safe in the face of spelling differences, because there is no way
264 // to spell an i/e in a strange way that is another letter. Skipping this
265 // allows us to avoid looking up the identifier info for #define/#undef and
266 // other common directives.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000267 const char *RawCharData = Tok.getRawIdentifierData();
268
Chris Lattner141e71f2008-03-09 01:54:53 +0000269 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000270 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000271 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000272 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000273 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000274 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000275 continue;
276 }
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattner141e71f2008-03-09 01:54:53 +0000278 // Get the identifier name without trigraphs or embedded newlines. Note
279 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
280 // when skipping.
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000281 char DirectiveBuf[20];
Chris Lattner5f9e2722011-07-23 10:55:15 +0000282 StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000283 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000284 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000285 } else {
286 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000287 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000288 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000289 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000290 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000291 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000292 continue;
293 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000294 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000295 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000296 }
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000298 if (Directive.startswith("if")) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000299 StringRef Sub = Directive.substr(2);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000300 if (Sub.empty() || // "if"
301 Sub == "def" || // "ifdef"
302 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
304 // bother parsing the condition.
305 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000306 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000307 /*foundnonskip*/false,
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000308 /*foundelse*/false);
309
310 if (Callbacks)
311 Callbacks->Endif();
Chris Lattner141e71f2008-03-09 01:54:53 +0000312 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000313 } else if (Directive[0] == 'e') {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000314 StringRef Sub = Directive.substr(1);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000315 if (Sub == "ndif") { // "endif"
Chris Lattner35410d52009-04-14 05:07:49 +0000316 CheckEndOfDirective("endif");
Chris Lattner141e71f2008-03-09 01:54:53 +0000317 PPConditionalInfo CondInfo;
318 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000319 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000320 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattner141e71f2008-03-09 01:54:53 +0000321 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattner141e71f2008-03-09 01:54:53 +0000323 // If we popped the outermost skipping block, we're done skipping!
324 if (!CondInfo.WasSkipping)
325 break;
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000326 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000327 // #else directive in a skipping conditional. If not in some other
328 // skipping conditional, and if #else hasn't already been seen, enter it
329 // as a non-skipping conditional.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000330 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattner141e71f2008-03-09 01:54:53 +0000332 // If this is a #else with a #else before it, report the error.
333 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Chris Lattner141e71f2008-03-09 01:54:53 +0000335 // Note that we've seen a #else in this conditional.
336 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000338 if (Callbacks)
339 Callbacks->Else();
340
Chris Lattner141e71f2008-03-09 01:54:53 +0000341 // If the conditional is at the top level, and the #if block wasn't
342 // entered, enter the #else block now.
343 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
344 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000345 CheckEndOfDirective("else");
Chris Lattner141e71f2008-03-09 01:54:53 +0000346 break;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000347 } else {
348 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattner141e71f2008-03-09 01:54:53 +0000349 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000350 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000351 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000352
353 bool ShouldEnter;
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000354 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +0000355 // If this is in a skipping block or if we're already handled this #if
356 // block, don't bother parsing the condition.
357 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
358 DiscardUntilEndOfDirective();
359 ShouldEnter = false;
360 } else {
361 // Restore the value of LexingRawMode so that identifiers are
362 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000363 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
364 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000365 IdentifierInfo *IfNDefMacro = 0;
366 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000367 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000368 }
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000369 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Chris Lattner141e71f2008-03-09 01:54:53 +0000371 // If this is a #elif with a #else before it, report the error.
372 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000374 if (Callbacks)
375 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
376
Chris Lattner141e71f2008-03-09 01:54:53 +0000377 // If this condition is true, enter it!
378 if (ShouldEnter) {
379 CondInfo.FoundNonSkip = true;
380 break;
381 }
382 }
383 }
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Ted Kremenek60e45d42008-11-18 00:34:22 +0000385 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000386 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000387 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000388 }
389
390 // Finally, if we are out of the conditional (saw an #endif or ran off the end
391 // of the file, just stop skipping and return to lexing whatever came after
392 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000393 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000394
395 if (Callbacks) {
396 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
397 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
398 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000399}
400
Ted Kremenek268ee702008-12-12 18:34:08 +0000401void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000402
403 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000404 assert(CurPTHLexer);
405 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Ted Kremenek268ee702008-12-12 18:34:08 +0000407 // Skip to the next '#else', '#elif', or #endif.
408 if (CurPTHLexer->SkipBlock()) {
409 // We have reached an #endif. Both the '#' and 'endif' tokens
410 // have been consumed by the PTHLexer. Just pop off the condition level.
411 PPConditionalInfo CondInfo;
412 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000413 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek268ee702008-12-12 18:34:08 +0000414 assert(!InCond && "Can't be skipping if not in a conditional!");
415 break;
416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Ted Kremenek268ee702008-12-12 18:34:08 +0000418 // We have reached a '#else' or '#elif'. Lex the next token to get
419 // the directive flavor.
420 Token Tok;
421 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Ted Kremenek268ee702008-12-12 18:34:08 +0000423 // We can actually look up the IdentifierInfo here since we aren't in
424 // raw mode.
425 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
426
427 if (K == tok::pp_else) {
428 // #else: Enter the else condition. We aren't in a nested condition
429 // since we skip those. We're always in the one matching the last
430 // blocked we skipped.
431 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
432 // Note that we've seen a #else in this conditional.
433 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Ted Kremenek268ee702008-12-12 18:34:08 +0000435 // If the #if block wasn't entered then enter the #else block now.
436 if (!CondInfo.FoundNonSkip) {
437 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Peter Collingbourne84021552011-02-28 02:37:51 +0000439 // Scan until the eod token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000440 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000441 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000442 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Ted Kremenek268ee702008-12-12 18:34:08 +0000444 break;
445 }
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Ted Kremenek268ee702008-12-12 18:34:08 +0000447 // Otherwise skip this block.
448 continue;
449 }
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Ted Kremenek268ee702008-12-12 18:34:08 +0000451 assert(K == tok::pp_elif);
452 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
453
454 // If this is a #elif with a #else before it, report the error.
455 if (CondInfo.FoundElse)
456 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Ted Kremenek268ee702008-12-12 18:34:08 +0000458 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000459 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000460 if (CondInfo.FoundNonSkip)
461 continue;
462
463 // Evaluate the condition of the #elif.
464 IdentifierInfo *IfNDefMacro = 0;
465 CurPTHLexer->ParsingPreprocessorDirective = true;
466 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
467 CurPTHLexer->ParsingPreprocessorDirective = false;
468
469 // If this condition is true, enter it!
470 if (ShouldEnter) {
471 CondInfo.FoundNonSkip = true;
472 break;
473 }
474
475 // Otherwise, skip this block and go to the next one.
476 continue;
477 }
478}
479
Chris Lattner10725092008-03-09 04:17:44 +0000480/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
481/// return null on failure. isAngled indicates whether the file reference is
482/// for system #include's or not (i.e. using <> instead of "").
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000483const FileEntry *Preprocessor::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000484 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000485 bool isAngled,
486 const DirectoryLookup *FromDir,
487 const DirectoryLookup *&CurDir,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000488 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000489 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000490 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000491 bool SkipCache) {
Chris Lattner10725092008-03-09 04:17:44 +0000492 // If the header lookup mechanism may be relative to the current file, pass in
493 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000494 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000495 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000496 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000497 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000499 // If there is no file entry associated with this file, it must be the
500 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000501 // it won't be scanned for preprocessor directives. If we have the
502 // predefines buffer, resolve #include references (which come from the
503 // -include command line argument) as if they came from the main file, this
504 // affects file lookup etc.
505 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000506 FID = SourceMgr.getMainFileID();
507 CurFileEnt = SourceMgr.getFileEntryForID(FID);
508 }
Chris Lattner10725092008-03-09 04:17:44 +0000509 }
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattner10725092008-03-09 04:17:44 +0000511 // Do a standard file entry lookup.
512 CurDir = CurDirLookup;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000513 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +0000514 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000515 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000516 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Chris Lattner10725092008-03-09 04:17:44 +0000518 // Otherwise, see if this is a subframework header. If so, this is relative
519 // to one of the headers on the #include stack. Walk the list of the current
520 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000521 // FIXME: SuggestedModule!
Ted Kremenek81d24e12008-11-20 16:19:53 +0000522 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000523 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000524 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek74124942011-04-26 21:50:03 +0000525 SearchPath, RelativePath)))
Chris Lattner10725092008-03-09 04:17:44 +0000526 return FE;
527 }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Chris Lattner10725092008-03-09 04:17:44 +0000529 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
530 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000531 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000532 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000533 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek74124942011-04-26 21:50:03 +0000534 if ((FE = HeaderInfo.LookupSubframeworkHeader(
535 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattner10725092008-03-09 04:17:44 +0000536 return FE;
537 }
538 }
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Chris Lattner10725092008-03-09 04:17:44 +0000540 // Otherwise, we really couldn't find the file.
541 return 0;
542}
543
Chris Lattner141e71f2008-03-09 01:54:53 +0000544
545//===----------------------------------------------------------------------===//
546// Preprocessor Directive Handling.
547//===----------------------------------------------------------------------===//
548
549/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000550/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000551/// lexer/preprocessor state, and advances the lexer(s) so that the next token
552/// read is the correct one.
553void Preprocessor::HandleDirective(Token &Result) {
554 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Chris Lattner141e71f2008-03-09 01:54:53 +0000556 // We just parsed a # character at the start of a line, so we're in directive
557 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne84021552011-02-28 02:37:51 +0000558 // EOD token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000559 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Chris Lattner141e71f2008-03-09 01:54:53 +0000561 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000562
Chris Lattner141e71f2008-03-09 01:54:53 +0000563 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000564 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000565 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000566 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Chris Lattner42aa16c2009-03-18 21:00:25 +0000568 // Save the '#' token in case we need to return it later.
569 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Chris Lattner141e71f2008-03-09 01:54:53 +0000571 // Read the next token, the directive flavor. This isn't expanded due to
572 // C99 6.10.3p8.
573 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Chris Lattner141e71f2008-03-09 01:54:53 +0000575 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
576 // #define A(x) #x
577 // A(abc
578 // #warning blah
579 // def)
Richard Smitha3ca4d62011-12-16 22:50:01 +0000580 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
581 // not support this for #include-like directives, since that can result in
582 // terrible diagnostics, and does not work in GCC.
583 if (InMacroArgs) {
584 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
585 switch (II->getPPKeywordID()) {
586 case tok::pp_include:
587 case tok::pp_import:
588 case tok::pp_include_next:
589 case tok::pp___include_macros:
590 Diag(Result, diag::err_embedded_include) << II->getName();
591 DiscardUntilEndOfDirective();
592 return;
593 default:
594 break;
595 }
596 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000597 Diag(Result, diag::ext_embedded_directive);
Richard Smitha3ca4d62011-12-16 22:50:01 +0000598 }
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Chris Lattner141e71f2008-03-09 01:54:53 +0000600TryAgain:
601 switch (Result.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000602 case tok::eod:
Chris Lattner141e71f2008-03-09 01:54:53 +0000603 return; // null directive.
604 case tok::comment:
605 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
606 LexUnexpandedToken(Result);
607 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000608 case tok::code_completion:
609 if (CodeComplete)
610 CodeComplete->CodeCompleteDirective(
611 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000612 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000613 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000614 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5f607c42009-03-18 20:41:10 +0000615 if (getLangOptions().AsmPreprocessor)
616 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000617 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000618 default:
619 IdentifierInfo *II = Result.getIdentifierInfo();
620 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Chris Lattner141e71f2008-03-09 01:54:53 +0000622 // Ask what the preprocessor keyword ID is.
623 switch (II->getPPKeywordID()) {
624 default: break;
625 // C99 6.10.1 - Conditional Inclusion.
626 case tok::pp_if:
627 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
628 case tok::pp_ifdef:
629 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
630 case tok::pp_ifndef:
631 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
632 case tok::pp_elif:
633 return HandleElifDirective(Result);
634 case tok::pp_else:
635 return HandleElseDirective(Result);
636 case tok::pp_endif:
637 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattner141e71f2008-03-09 01:54:53 +0000639 // C99 6.10.2 - Source File Inclusion.
640 case tok::pp_include:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000641 // Handle #include.
642 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000643 case tok::pp___include_macros:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000644 // Handle -imacros.
645 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattner141e71f2008-03-09 01:54:53 +0000647 // C99 6.10.3 - Macro Replacement.
648 case tok::pp_define:
649 return HandleDefineDirective(Result);
650 case tok::pp_undef:
651 return HandleUndefDirective(Result);
652
653 // C99 6.10.4 - Line Control.
654 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000655 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Chris Lattner141e71f2008-03-09 01:54:53 +0000657 // C99 6.10.5 - Error Directive.
658 case tok::pp_error:
659 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Chris Lattner141e71f2008-03-09 01:54:53 +0000661 // C99 6.10.6 - Pragma Directive.
662 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000663 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Chris Lattner141e71f2008-03-09 01:54:53 +0000665 // GNU Extensions.
666 case tok::pp_import:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000667 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000668 case tok::pp_include_next:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000669 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Chris Lattner141e71f2008-03-09 01:54:53 +0000671 case tok::pp_warning:
672 Diag(Result, diag::ext_pp_warning_directive);
673 return HandleUserDiagnosticDirective(Result, true);
674 case tok::pp_ident:
675 return HandleIdentSCCSDirective(Result);
676 case tok::pp_sccs:
677 return HandleIdentSCCSDirective(Result);
678 case tok::pp_assert:
679 //isExtension = true; // FIXME: implement #assert
680 break;
681 case tok::pp_unassert:
682 //isExtension = true; // FIXME: implement #unassert
683 break;
Douglas Gregor7143aab2011-09-01 17:04:32 +0000684
685 case tok::pp___export_macro__:
686 return HandleMacroExportDirective(Result);
Douglas Gregoraa93a872011-10-17 15:32:29 +0000687 case tok::pp___private_macro__:
688 return HandleMacroPrivateDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000689 }
690 break;
691 }
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Chris Lattner42aa16c2009-03-18 21:00:25 +0000693 // If this is a .S file, treat unknown # directives as non-preprocessor
694 // directives. This is important because # may be a comment or introduce
695 // various pseudo-ops. Just return the # token and push back the following
696 // token to be lexed next time.
697 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000698 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000699 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000700 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000701 Toks[1] = Result;
Chris Lattnerba3ca522011-01-06 05:01:51 +0000702
703 // If the second token is a hashhash token, then we need to translate it to
704 // unknown so the token lexer doesn't try to perform token pasting.
705 if (Result.is(tok::hashhash))
706 Toks[1].setKind(tok::unknown);
707
Chris Lattner42aa16c2009-03-18 21:00:25 +0000708 // Enter this token stream so that we re-lex the tokens. Make sure to
709 // enable macro expansion, in case the token after the # is an identifier
710 // that is expanded.
711 EnterTokenStream(Toks, 2, false, true);
712 return;
713 }
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattner141e71f2008-03-09 01:54:53 +0000715 // If we reached here, the preprocessing token is not valid!
716 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattner141e71f2008-03-09 01:54:53 +0000718 // Read the rest of the PP line.
719 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Chris Lattner141e71f2008-03-09 01:54:53 +0000721 // Okay, we're done parsing the directive.
722}
723
Chris Lattner478a18e2009-01-26 06:19:46 +0000724/// GetLineValue - Convert a numeric token into an unsigned value, emitting
725/// Diagnostic DiagID if it is invalid, and returning the value in Val.
726static bool GetLineValue(Token &DigitTok, unsigned &Val,
727 unsigned DiagID, Preprocessor &PP) {
728 if (DigitTok.isNot(tok::numeric_constant)) {
729 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Peter Collingbourne84021552011-02-28 02:37:51 +0000731 if (DigitTok.isNot(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000732 PP.DiscardUntilEndOfDirective();
733 return true;
734 }
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Chris Lattner478a18e2009-01-26 06:19:46 +0000736 llvm::SmallString<64> IntegerBuffer;
737 IntegerBuffer.resize(DigitTok.getLength());
738 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000739 bool Invalid = false;
740 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
741 if (Invalid)
742 return true;
743
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000744 // Verify that we have a simple digit-sequence, and compute the value. This
745 // is always a simple digit string computed in decimal, so we do this manually
746 // here.
747 Val = 0;
748 for (unsigned i = 0; i != ActualLength; ++i) {
749 if (!isdigit(DigitTokBegin[i])) {
750 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
751 diag::err_pp_line_digit_sequence);
752 PP.DiscardUntilEndOfDirective();
753 return true;
754 }
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000756 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
757 if (NextVal < Val) { // overflow.
758 PP.Diag(DigitTok, DiagID);
759 PP.DiscardUntilEndOfDirective();
760 return true;
761 }
762 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000763 }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
765 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner478a18e2009-01-26 06:19:46 +0000766 if (Val == 0) {
767 PP.Diag(DigitTok, DiagID);
768 PP.DiscardUntilEndOfDirective();
769 return true;
770 }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000772 if (DigitTokBegin[0] == '0')
773 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Chris Lattner478a18e2009-01-26 06:19:46 +0000775 return false;
776}
777
Mike Stump1eb44332009-09-09 15:08:12 +0000778/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner359cc442009-01-26 05:29:08 +0000779/// acceptable forms are:
780/// # line digit-sequence
781/// # line digit-sequence "s-char-sequence"
782void Preprocessor::HandleLineDirective(Token &Tok) {
783 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
784 // expanded.
785 Token DigitTok;
786 Lex(DigitTok);
787
Chris Lattner359cc442009-01-26 05:29:08 +0000788 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000789 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000790 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000791 return;
Chris Lattner359cc442009-01-26 05:29:08 +0000792
Chris Lattner478a18e2009-01-26 06:19:46 +0000793 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
794 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman158ebfb2011-10-10 23:35:28 +0000795 unsigned LineLimit = 32768U;
796 if (Features.C99 || Features.CPlusPlus0x)
797 LineLimit = 2147483648U;
Chris Lattner359cc442009-01-26 05:29:08 +0000798 if (LineNo >= LineLimit)
799 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith661a9962011-10-15 01:18:56 +0000800 else if (Features.CPlusPlus0x && LineNo >= 32768U)
801 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Chris Lattner5b9a5042009-01-26 07:57:50 +0000803 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000804 Token StrTok;
805 Lex(StrTok);
806
Peter Collingbourne84021552011-02-28 02:37:51 +0000807 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
808 // string followed by eod.
809 if (StrTok.is(tok::eod))
Chris Lattner359cc442009-01-26 05:29:08 +0000810 ; // ok
811 else if (StrTok.isNot(tok::string_literal)) {
812 Diag(StrTok, diag::err_pp_line_invalid_filename);
813 DiscardUntilEndOfDirective();
814 return;
815 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000816 // Parse and validate the string, converting it into a unique ID.
817 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000818 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000819 if (Literal.hadError)
820 return DiscardUntilEndOfDirective();
821 if (Literal.Pascal) {
822 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
823 return DiscardUntilEndOfDirective();
824 }
Jay Foad65aa6882011-06-21 15:13:30 +0000825 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Peter Collingbourne84021552011-02-28 02:37:51 +0000827 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattnerab82f412009-04-17 23:30:53 +0000828 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
829 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Chris Lattner4c4ea172009-02-03 21:52:55 +0000832 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Chris Lattner16629382009-03-27 17:13:49 +0000834 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000835 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
836 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000837 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000838}
839
Chris Lattner478a18e2009-01-26 06:19:46 +0000840/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
841/// marker directive.
842static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
843 bool &IsSystemHeader, bool &IsExternCHeader,
844 Preprocessor &PP) {
845 unsigned FlagVal;
846 Token FlagTok;
847 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000848 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000849 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
850 return true;
851
852 if (FlagVal == 1) {
853 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Chris Lattner478a18e2009-01-26 06:19:46 +0000855 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000856 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000857 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
858 return true;
859 } else if (FlagVal == 2) {
860 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000861
Chris Lattner137b6a62009-02-04 06:25:26 +0000862 SourceManager &SM = PP.getSourceManager();
863 // If we are leaving the current presumed file, check to make sure the
864 // presumed include stack isn't empty!
865 FileID CurFileID =
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000866 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner137b6a62009-02-04 06:25:26 +0000867 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000868 if (PLoc.isInvalid())
869 return true;
870
Chris Lattner137b6a62009-02-04 06:25:26 +0000871 // If there is no include loc (main file) or if the include loc is in a
872 // different physical file, then we aren't in a "1" line marker flag region.
873 SourceLocation IncLoc = PLoc.getIncludeLoc();
874 if (IncLoc.isInvalid() ||
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000875 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner137b6a62009-02-04 06:25:26 +0000876 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
877 PP.DiscardUntilEndOfDirective();
878 return true;
879 }
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Chris Lattner478a18e2009-01-26 06:19:46 +0000881 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000882 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000883 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
884 return true;
885 }
886
887 // We must have 3 if there are still flags.
888 if (FlagVal != 3) {
889 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000890 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000891 return true;
892 }
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Chris Lattner478a18e2009-01-26 06:19:46 +0000894 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner478a18e2009-01-26 06:19:46 +0000896 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000897 if (FlagTok.is(tok::eod)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000898 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000899 return true;
900
901 // We must have 4 if there is yet another flag.
902 if (FlagVal != 4) {
903 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000904 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000905 return true;
906 }
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Chris Lattner478a18e2009-01-26 06:19:46 +0000908 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Chris Lattner478a18e2009-01-26 06:19:46 +0000910 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000911 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000912
913 // There are no more valid flags here.
914 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000915 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000916 return true;
917}
918
919/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
920/// one of the following forms:
921///
922/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000923/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000924/// # 42 "file" ('1' | '2')? '3' '4'?
925///
926void Preprocessor::HandleDigitDirective(Token &DigitTok) {
927 // Validate the number and convert it to an unsigned. GNU does not have a
928 // line # limit other than it fit in 32-bits.
929 unsigned LineNo;
930 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
931 *this))
932 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Chris Lattner478a18e2009-01-26 06:19:46 +0000934 Token StrTok;
935 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Chris Lattner478a18e2009-01-26 06:19:46 +0000937 bool IsFileEntry = false, IsFileExit = false;
938 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000939 int FilenameID = -1;
940
Peter Collingbourne84021552011-02-28 02:37:51 +0000941 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
942 // string followed by eod.
943 if (StrTok.is(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000944 ; // ok
945 else if (StrTok.isNot(tok::string_literal)) {
946 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000947 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000948 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000949 // Parse and validate the string, converting it into a unique ID.
950 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000951 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000952 if (Literal.hadError)
953 return DiscardUntilEndOfDirective();
954 if (Literal.Pascal) {
955 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
956 return DiscardUntilEndOfDirective();
957 }
Jay Foad65aa6882011-06-21 15:13:30 +0000958 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattner478a18e2009-01-26 06:19:46 +0000960 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +0000961 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +0000962 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +0000963 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000964 }
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Chris Lattner9d79eba2009-02-04 05:21:58 +0000966 // Create a line note with this information.
967 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +0000968 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000969 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Chris Lattner16629382009-03-27 17:13:49 +0000971 // If the preprocessor has callbacks installed, notify them of the #line
972 // change. This is used so that the line marker comes out in -E mode for
973 // example.
974 if (Callbacks) {
975 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
976 if (IsFileEntry)
977 Reason = PPCallbacks::EnterFile;
978 else if (IsFileExit)
979 Reason = PPCallbacks::ExitFile;
980 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
981 if (IsExternCHeader)
982 FileKind = SrcMgr::C_ExternCSystem;
983 else if (IsSystemHeader)
984 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Chris Lattner86d0ef72010-04-14 04:28:50 +0000986 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +0000987 }
Chris Lattner478a18e2009-01-26 06:19:46 +0000988}
989
990
Chris Lattner099dd052009-01-26 05:30:54 +0000991/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
992///
Mike Stump1eb44332009-09-09 15:08:12 +0000993void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +0000994 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000995 // PTH doesn't emit #warning or #error directives.
996 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000997 return CurPTHLexer->DiscardToEndOfLine();
998
Chris Lattner141e71f2008-03-09 01:54:53 +0000999 // Read the rest of the line raw. We do this because we don't want macros
1000 // to be expanded and we don't require that the tokens be valid preprocessing
1001 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1002 // collapse multiple consequtive white space between tokens, but this isn't
1003 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +00001004 std::string Message = CurLexer->ReadToEndOfLine();
1005 if (isWarning)
1006 Diag(Tok, diag::pp_hash_warning) << Message;
1007 else
1008 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +00001009}
1010
1011/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1012///
1013void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1014 // Yes, this directive is an extension.
1015 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattner141e71f2008-03-09 01:54:53 +00001017 // Read the string argument.
1018 Token StrTok;
1019 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Chris Lattner141e71f2008-03-09 01:54:53 +00001021 // If the token kind isn't a string, it's a malformed directive.
1022 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +00001023 StrTok.isNot(tok::wide_string_literal)) {
1024 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne84021552011-02-28 02:37:51 +00001025 if (StrTok.isNot(tok::eod))
Chris Lattner099dd052009-01-26 05:30:54 +00001026 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +00001027 return;
1028 }
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Peter Collingbourne84021552011-02-28 02:37:51 +00001030 // Verify that there is nothing after the string, other than EOD.
Chris Lattner35410d52009-04-14 05:07:49 +00001031 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +00001032
Douglas Gregor453091c2010-03-16 22:30:13 +00001033 if (Callbacks) {
1034 bool Invalid = false;
1035 std::string Str = getSpelling(StrTok, &Invalid);
1036 if (!Invalid)
1037 Callbacks->Ident(Tok.getLocation(), Str);
1038 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001039}
1040
Douglas Gregor7143aab2011-09-01 17:04:32 +00001041/// \brief Handle a #__export_macro__ directive.
1042void Preprocessor::HandleMacroExportDirective(Token &Tok) {
1043 Token MacroNameTok;
1044 ReadMacroName(MacroNameTok, 2);
1045
1046 // Error reading macro name? If so, diagnostic already issued.
1047 if (MacroNameTok.is(tok::eod))
1048 return;
1049
1050 // Check to see if this is the last token on the #__export_macro__ line.
1051 CheckEndOfDirective("__export_macro__");
1052
1053 // Okay, we finally have a valid identifier to undef.
1054 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1055
1056 // If the macro is not defined, this is an error.
1057 if (MI == 0) {
Douglas Gregoraa93a872011-10-17 15:32:29 +00001058 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor7143aab2011-09-01 17:04:32 +00001059 << MacroNameTok.getIdentifierInfo();
1060 return;
1061 }
1062
1063 // Note that this macro has now been exported.
Douglas Gregoraa93a872011-10-17 15:32:29 +00001064 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1065
1066 // If this macro definition came from a PCH file, mark it
1067 // as having changed since serialization.
1068 if (MI->isFromAST())
1069 MI->setChangedAfterLoad();
1070}
1071
1072/// \brief Handle a #__private_macro__ directive.
1073void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1074 Token MacroNameTok;
1075 ReadMacroName(MacroNameTok, 2);
1076
1077 // Error reading macro name? If so, diagnostic already issued.
1078 if (MacroNameTok.is(tok::eod))
1079 return;
1080
1081 // Check to see if this is the last token on the #__private_macro__ line.
1082 CheckEndOfDirective("__private_macro__");
1083
1084 // Okay, we finally have a valid identifier to undef.
1085 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1086
1087 // If the macro is not defined, this is an error.
1088 if (MI == 0) {
1089 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1090 << MacroNameTok.getIdentifierInfo();
1091 return;
1092 }
1093
1094 // Note that this macro has now been marked private.
1095 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor7143aab2011-09-01 17:04:32 +00001096
1097 // If this macro definition came from a PCH file, mark it
1098 // as having changed since serialization.
1099 if (MI->isFromAST())
1100 MI->setChangedAfterLoad();
1101}
1102
Chris Lattner141e71f2008-03-09 01:54:53 +00001103//===----------------------------------------------------------------------===//
1104// Preprocessor Include Directive Handling.
1105//===----------------------------------------------------------------------===//
1106
1107/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1108/// checked and spelled filename, e.g. as an operand of #include. This returns
1109/// true if the input filename was in <>'s or false if it were in ""'s. The
1110/// caller is expected to provide a buffer that is large enough to hold the
1111/// spelling of the filename, but is also expected to handle the case when
1112/// this method decides to use a different buffer.
1113bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001114 StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001115 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +00001116 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Chris Lattner141e71f2008-03-09 01:54:53 +00001118 // Make sure the filename is <x> or "x".
1119 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +00001120 if (Buffer[0] == '<') {
1121 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001122 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001123 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001124 return true;
1125 }
1126 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +00001127 } else if (Buffer[0] == '"') {
1128 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001129 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001130 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001131 return true;
1132 }
1133 isAngled = false;
1134 } else {
1135 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001136 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001137 return true;
1138 }
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Chris Lattner141e71f2008-03-09 01:54:53 +00001140 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +00001141 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001142 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001143 Buffer = StringRef();
Chris Lattnera1394812010-01-10 01:35:12 +00001144 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001145 }
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Chris Lattner141e71f2008-03-09 01:54:53 +00001147 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001148 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001149 return isAngled;
1150}
1151
1152/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1153/// from a macro as multiple tokens, which need to be glued together. This
1154/// occurs for code like:
1155/// #define FOO <a/b.h>
1156/// #include FOO
1157/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1158///
1159/// This code concatenates and consumes tokens up to the '>' token. It returns
1160/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne84021552011-02-28 02:37:51 +00001161/// the EOD marker.
John Thompsona28cc092009-10-30 13:49:06 +00001162bool Preprocessor::ConcatenateIncludeName(
Douglas Gregorecdcb882010-10-20 22:00:55 +00001163 llvm::SmallString<128> &FilenameBuffer,
1164 SourceLocation &End) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001165 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001166
John Thompsona28cc092009-10-30 13:49:06 +00001167 Lex(CurTok);
Peter Collingbourne84021552011-02-28 02:37:51 +00001168 while (CurTok.isNot(tok::eod)) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001169 End = CurTok.getLocation();
1170
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001171 // FIXME: Provide code completion for #includes.
1172 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001173 setCodeCompletionReached();
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001174 Lex(CurTok);
1175 continue;
1176 }
1177
Chris Lattner141e71f2008-03-09 01:54:53 +00001178 // Append the spelling of this token to the buffer. If there was a space
1179 // before it, add it now.
1180 if (CurTok.hasLeadingSpace())
1181 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Chris Lattner141e71f2008-03-09 01:54:53 +00001183 // Get the spelling of the token, directly into FilenameBuffer if possible.
1184 unsigned PreAppendSize = FilenameBuffer.size();
1185 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chris Lattner141e71f2008-03-09 01:54:53 +00001187 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001188 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Chris Lattner141e71f2008-03-09 01:54:53 +00001190 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1191 if (BufPtr != &FilenameBuffer[PreAppendSize])
1192 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Chris Lattner141e71f2008-03-09 01:54:53 +00001194 // Resize FilenameBuffer to the correct size.
1195 if (CurTok.getLength() != ActualLen)
1196 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Chris Lattner141e71f2008-03-09 01:54:53 +00001198 // If we found the '>' marker, return success.
1199 if (CurTok.is(tok::greater))
1200 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001201
John Thompsona28cc092009-10-30 13:49:06 +00001202 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001203 }
1204
Peter Collingbourne84021552011-02-28 02:37:51 +00001205 // If we hit the eod marker, emit an error and return true so that the caller
1206 // knows the EOD has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001207 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001208 return true;
1209}
1210
1211/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1212/// file to be included from the lexer, then include it! This is a common
1213/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +00001214/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001215/// specifies the file to start searching from.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001216void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1217 Token &IncludeTok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001218 const DirectoryLookup *LookupFrom,
1219 bool isImport) {
1220
1221 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001222 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Chris Lattner141e71f2008-03-09 01:54:53 +00001224 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +00001225 llvm::SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001226 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001227 SourceLocation End;
Douglas Gregore3a82562011-11-30 18:02:36 +00001228 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregorecdcb882010-10-20 22:00:55 +00001229
Chris Lattner141e71f2008-03-09 01:54:53 +00001230 switch (FilenameTok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +00001231 case tok::eod:
1232 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattner141e71f2008-03-09 01:54:53 +00001233 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Chris Lattner141e71f2008-03-09 01:54:53 +00001235 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001236 case tok::string_literal:
1237 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregorecdcb882010-10-20 22:00:55 +00001238 End = FilenameTok.getLocation();
Douglas Gregore3a82562011-11-30 18:02:36 +00001239 CharEnd = End.getLocWithOffset(Filename.size());
Chris Lattner141e71f2008-03-09 01:54:53 +00001240 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Chris Lattner141e71f2008-03-09 01:54:53 +00001242 case tok::less:
1243 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1244 // case, glue the tokens together into FilenameBuffer and interpret those.
1245 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +00001246 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne84021552011-02-28 02:37:51 +00001247 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001248 Filename = FilenameBuffer.str();
Douglas Gregore3a82562011-11-30 18:02:36 +00001249 CharEnd = getLocForEndOfToken(End);
Chris Lattner141e71f2008-03-09 01:54:53 +00001250 break;
1251 default:
1252 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1253 DiscardUntilEndOfDirective();
1254 return;
1255 }
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001257 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001258 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001259 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1260 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001261 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001262 DiscardUntilEndOfDirective();
1263 return;
1264 }
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Peter Collingbourne84021552011-02-28 02:37:51 +00001266 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001267 // we allow macros that expand to nothing after the filename, because this
1268 // falls into the category of "#include pp-tokens new-line" specified in
1269 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001270 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001271
1272 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001273 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1274 Diag(FilenameTok, diag::err_pp_include_too_deep);
1275 return;
1276 }
Mike Stump1eb44332009-09-09 15:08:12 +00001277
John McCall8dfac0b2011-09-30 05:12:12 +00001278 // Complain about attempts to #include files in an audit pragma.
1279 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1280 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1281 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1282
1283 // Immediately leave the pragma.
1284 PragmaARCCFCodeAuditedLoc = SourceLocation();
1285 }
1286
Chris Lattner141e71f2008-03-09 01:54:53 +00001287 // Search include directories.
1288 const DirectoryLookup *CurDir;
Manuel Klimek74124942011-04-26 21:50:03 +00001289 llvm::SmallString<1024> SearchPath;
1290 llvm::SmallString<1024> RelativePath;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001291 // We get the raw path only if we have 'Callbacks' to which we later pass
1292 // the path.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001293 Module *SuggestedModule = 0;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001294 const FileEntry *File = LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +00001295 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001296 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
Douglas Gregor752c74d2012-01-03 17:07:34 +00001297 getLangOptions().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001298
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001299 if (Callbacks) {
1300 if (!File) {
1301 // Give the clients a chance to recover.
1302 llvm::SmallString<128> RecoveryPath;
1303 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1304 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1305 // Add the recovery path to the list of search paths.
1306 DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
1307 HeaderInfo.AddSearchPath(DL, isAngled);
1308
1309 // Try the lookup again, skipping the cache.
1310 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
Douglas Gregor752c74d2012-01-03 17:07:34 +00001311 getLangOptions().Modules? &SuggestedModule : 0,
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001312 /*SkipCache*/true);
1313 }
1314 }
1315 }
1316
1317 // Notify the callback object that we've seen an inclusion directive.
1318 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1319 End, SearchPath, RelativePath);
1320 }
1321
1322 if (File == 0) {
1323 if (!SuppressIncludeNotFoundError)
1324 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1325 return;
1326 }
1327
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001328 // If we are supposed to import a module rather than including the header,
1329 // do so now.
Douglas Gregorc69c42e2011-11-17 22:44:56 +00001330 if (SuggestedModule) {
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001331 // Compute the module access path corresponding to this module.
1332 // FIXME: Should we have a second loadModule() overload to avoid this
1333 // extra lookup step?
1334 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001335 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001336 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1337 FilenameTok.getLocation()));
1338 std::reverse(Path.begin(), Path.end());
1339
Douglas Gregore3a82562011-11-30 18:02:36 +00001340 // Warn that we're replacing the include/import with a module import.
1341 llvm::SmallString<128> PathString;
1342 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1343 if (I)
1344 PathString += '.';
1345 PathString += Path[I].first->getName();
1346 }
1347 int IncludeKind = 0;
1348
1349 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1350 case tok::pp_include:
1351 IncludeKind = 0;
1352 break;
1353
1354 case tok::pp_import:
1355 IncludeKind = 1;
1356 break;
1357
Douglas Gregoredee9692011-11-30 18:03:26 +00001358 case tok::pp_include_next:
1359 IncludeKind = 2;
1360 break;
Douglas Gregore3a82562011-11-30 18:02:36 +00001361
1362 case tok::pp___include_macros:
1363 IncludeKind = 3;
1364 break;
1365
1366 default:
1367 llvm_unreachable("unknown include directive kind");
1368 break;
1369 }
1370
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001371 // Determine whether we are actually building the module that this
1372 // include directive maps to.
1373 bool BuildingImportedModule
1374 = Path[0].first->getName() == getLangOptions().CurrentModule;
1375
1376 if (!BuildingImportedModule) {
1377 // If we're not building the imported module, warn that we're going
1378 // to automatically turn this inclusion directive into a module import.
1379 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1380 /*IsTokenRange=*/false);
1381 Diag(HashLoc, diag::warn_auto_module_import)
1382 << IncludeKind << PathString
1383 << FixItHint::CreateReplacement(ReplaceRange,
1384 "__import_module__ " + PathString.str().str() + ";");
1385 }
Douglas Gregore3a82562011-11-30 18:02:36 +00001386
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001387 // Load the module.
Douglas Gregor5e356932011-12-01 17:11:21 +00001388 // If this was an #__include_macros directive, only make macros visible.
1389 Module::NameVisibilityKind Visibility
1390 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor305dc3e2011-12-20 00:28:52 +00001391 Module *Imported
1392 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1393 /*IsIncludeDirective=*/true);
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001394
1395 // If this header isn't part of the module we're building, we're done.
Douglas Gregor305dc3e2011-12-20 00:28:52 +00001396 if (!BuildingImportedModule && Imported)
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001397 return;
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001398 }
1399
Chris Lattner72181832008-09-26 20:12:23 +00001400 // The #included file will be considered to be a system header if either it is
1401 // in a system include directory, or if the #includer is a system include
1402 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001403 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001404 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001405 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001407 // Ask HeaderInfo if we should enter this #include file. If not, #including
1408 // this file will have no effect.
1409 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001410 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001411 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001412 return;
1413 }
1414
Chris Lattner141e71f2008-03-09 01:54:53 +00001415 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +00001416 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1417 FileCharacter);
Peter Collingbourned57b7ff2011-06-30 16:41:03 +00001418 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattner141e71f2008-03-09 01:54:53 +00001419
1420 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001421 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001422}
1423
1424/// HandleIncludeNextDirective - Implements #include_next.
1425///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001426void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1427 Token &IncludeNextTok) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001428 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Chris Lattner141e71f2008-03-09 01:54:53 +00001430 // #include_next is like #include, except that we start searching after
1431 // the current found directory. If we can't do this, issue a
1432 // diagnostic.
1433 const DirectoryLookup *Lookup = CurDirLookup;
1434 if (isInPrimaryFile()) {
1435 Lookup = 0;
1436 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1437 } else if (Lookup == 0) {
1438 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1439 } else {
1440 // Start looking up in the next directory.
1441 ++Lookup;
1442 }
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Douglas Gregorecdcb882010-10-20 22:00:55 +00001444 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattner141e71f2008-03-09 01:54:53 +00001445}
1446
1447/// HandleImportDirective - Implements #import.
1448///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001449void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1450 Token &ImportTok) {
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001451 if (!Features.ObjC1) // #import is standard for ObjC.
1452 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Douglas Gregorecdcb882010-10-20 22:00:55 +00001454 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001455}
1456
Chris Lattnerde076652009-04-08 18:46:40 +00001457/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1458/// pseudo directive in the predefines buffer. This handles it by sucking all
1459/// tokens through the preprocessor and discarding them (only keeping the side
1460/// effects on the preprocessor).
Douglas Gregorecdcb882010-10-20 22:00:55 +00001461void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1462 Token &IncludeMacrosTok) {
Chris Lattnerde076652009-04-08 18:46:40 +00001463 // This directive should only occur in the predefines buffer. If not, emit an
1464 // error and reject it.
1465 SourceLocation Loc = IncludeMacrosTok.getLocation();
1466 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1467 Diag(IncludeMacrosTok.getLocation(),
1468 diag::pp_include_macros_out_of_predefines);
1469 DiscardUntilEndOfDirective();
1470 return;
1471 }
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Chris Lattnerfd105112009-04-08 20:53:24 +00001473 // Treat this as a normal #include for checking purposes. If this is
1474 // successful, it will push a new lexer onto the include stack.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001475 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Chris Lattnerfd105112009-04-08 20:53:24 +00001477 Token TmpTok;
1478 do {
1479 Lex(TmpTok);
1480 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1481 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001482}
1483
Chris Lattner141e71f2008-03-09 01:54:53 +00001484//===----------------------------------------------------------------------===//
1485// Preprocessor Macro Directive Handling.
1486//===----------------------------------------------------------------------===//
1487
1488/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1489/// definition has just been read. Lex the rest of the arguments and the
1490/// closing ), updating MI with what we learn. Return true if an error occurs
1491/// parsing the arg list.
1492bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001493 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Chris Lattner141e71f2008-03-09 01:54:53 +00001495 Token Tok;
1496 while (1) {
1497 LexUnexpandedToken(Tok);
1498 switch (Tok.getKind()) {
1499 case tok::r_paren:
1500 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001501 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001502 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001503 // Otherwise we have #define FOO(A,)
1504 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1505 return true;
1506 case tok::ellipsis: // #define X(... -> C99 varargs
Richard Smith661a9962011-10-15 01:18:56 +00001507 if (!Features.C99)
1508 Diag(Tok, Features.CPlusPlus0x ?
1509 diag::warn_cxx98_compat_variadic_macro :
1510 diag::ext_variadic_macro);
Chris Lattner141e71f2008-03-09 01:54:53 +00001511
1512 // Lex the token after the identifier.
1513 LexUnexpandedToken(Tok);
1514 if (Tok.isNot(tok::r_paren)) {
1515 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1516 return true;
1517 }
1518 // Add the __VA_ARGS__ identifier as an argument.
1519 Arguments.push_back(Ident__VA_ARGS__);
1520 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001521 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001522 return false;
Peter Collingbourne84021552011-02-28 02:37:51 +00001523 case tok::eod: // #define X(
Chris Lattner141e71f2008-03-09 01:54:53 +00001524 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1525 return true;
1526 default:
1527 // Handle keywords and identifiers here to accept things like
1528 // #define Foo(for) for.
1529 IdentifierInfo *II = Tok.getIdentifierInfo();
1530 if (II == 0) {
1531 // #define X(1
1532 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1533 return true;
1534 }
1535
1536 // If this is already used as an argument, it is used multiple times (e.g.
1537 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001538 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001539 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001540 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001541 return true;
1542 }
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Chris Lattner141e71f2008-03-09 01:54:53 +00001544 // Add the argument to the macro info.
1545 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Chris Lattner141e71f2008-03-09 01:54:53 +00001547 // Lex the token after the identifier.
1548 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Chris Lattner141e71f2008-03-09 01:54:53 +00001550 switch (Tok.getKind()) {
1551 default: // #define X(A B
1552 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1553 return true;
1554 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001555 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001556 return false;
1557 case tok::comma: // #define X(A,
1558 break;
1559 case tok::ellipsis: // #define X(A... -> GCC extension
1560 // Diagnose extension.
1561 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Chris Lattner141e71f2008-03-09 01:54:53 +00001563 // Lex the token after the identifier.
1564 LexUnexpandedToken(Tok);
1565 if (Tok.isNot(tok::r_paren)) {
1566 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1567 return true;
1568 }
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Chris Lattner141e71f2008-03-09 01:54:53 +00001570 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001571 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001572 return false;
1573 }
1574 }
1575 }
1576}
1577
1578/// HandleDefineDirective - Implements #define. This consumes the entire macro
1579/// line then lets the caller lex the next real token.
1580void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1581 ++NumDefined;
1582
1583 Token MacroNameTok;
1584 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Chris Lattner141e71f2008-03-09 01:54:53 +00001586 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001587 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001588 return;
1589
Chris Lattner2451b522009-04-21 04:46:33 +00001590 Token LastTok = MacroNameTok;
1591
Chris Lattner141e71f2008-03-09 01:54:53 +00001592 // If we are supposed to keep comments in #defines, reenable comment saving
1593 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001594 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Chris Lattner141e71f2008-03-09 01:54:53 +00001596 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001597 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Chris Lattner141e71f2008-03-09 01:54:53 +00001599 Token Tok;
1600 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Chris Lattner141e71f2008-03-09 01:54:53 +00001602 // If this is a function-like macro definition, parse the argument list,
1603 // marking each of the identifiers as being used as macro arguments. Also,
1604 // check other constraints on the first token of the macro body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001605 if (Tok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001606 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001607 } else if (Tok.hasLeadingSpace()) {
1608 // This is a normal token with leading space. Clear the leading space
1609 // marker on the first token to get proper expansion.
1610 Tok.clearFlag(Token::LeadingSpace);
1611 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001612 // This is a function-like macro definition. Read the argument list.
1613 MI->setIsFunctionLike();
1614 if (ReadMacroDefinitionArgList(MI)) {
1615 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001616 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001617 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001618 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001619 DiscardUntilEndOfDirective();
1620 return;
1621 }
1622
Chris Lattner8fde5972009-04-19 18:26:34 +00001623 // If this is a definition of a variadic C99 function-like macro, not using
1624 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Chris Lattner8fde5972009-04-19 18:26:34 +00001626 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1627 // This gets unpoisoned where it is allowed.
1628 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1629 if (MI->isC99Varargs())
1630 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Chris Lattner141e71f2008-03-09 01:54:53 +00001632 // Read the first token after the arg list for down below.
1633 LexUnexpandedToken(Tok);
Eli Friedman158ebfb2011-10-10 23:35:28 +00001634 } else if (Features.C99 || Features.CPlusPlus0x) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001635 // C99 requires whitespace between the macro definition and the body. Emit
1636 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001637 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001638 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001639 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1640 // first character of a replacement list is not a character required by
1641 // subclause 5.2.1, then there shall be white-space separation between the
1642 // identifier and the replacement list.". 5.2.1 lists this set:
1643 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1644 // is irrelevant here.
1645 bool isInvalid = false;
1646 if (Tok.is(tok::at)) // @ is not in the list above.
1647 isInvalid = true;
1648 else if (Tok.is(tok::unknown)) {
1649 // If we have an unknown token, it is something strange like "`". Since
1650 // all of valid characters would have lexed into a single character
1651 // token of some sort, we know this is not a valid case.
1652 isInvalid = true;
1653 }
1654 if (isInvalid)
1655 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1656 else
1657 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001658 }
Chris Lattner2451b522009-04-21 04:46:33 +00001659
Peter Collingbourne84021552011-02-28 02:37:51 +00001660 if (!Tok.is(tok::eod))
Chris Lattner2451b522009-04-21 04:46:33 +00001661 LastTok = Tok;
1662
Chris Lattner141e71f2008-03-09 01:54:53 +00001663 // Read the rest of the macro body.
1664 if (MI->isObjectLike()) {
1665 // Object-like macros are very simple, just read their body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001666 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001667 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001668 MI->AddTokenToBody(Tok);
1669 // Get the next token of the macro.
1670 LexUnexpandedToken(Tok);
1671 }
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Chris Lattner141e71f2008-03-09 01:54:53 +00001673 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001674 // Otherwise, read the body of a function-like macro. While we are at it,
1675 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1676 // parameters in function-like macro expansions.
Peter Collingbourne84021552011-02-28 02:37:51 +00001677 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001678 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001679
Chris Lattner141e71f2008-03-09 01:54:53 +00001680 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001681 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Chris Lattner141e71f2008-03-09 01:54:53 +00001683 // Get the next token of the macro.
1684 LexUnexpandedToken(Tok);
1685 continue;
1686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Chris Lattner141e71f2008-03-09 01:54:53 +00001688 // Get the next token of the macro.
1689 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Chris Lattner32404692009-05-25 17:16:10 +00001691 // Check for a valid macro arg identifier.
1692 if (Tok.getIdentifierInfo() == 0 ||
1693 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1694
1695 // If this is assembler-with-cpp mode, we accept random gibberish after
1696 // the '#' because '#' is often a comment character. However, change
1697 // the kind of the token to tok::unknown so that the preprocessor isn't
1698 // confused.
Peter Collingbourne84021552011-02-28 02:37:51 +00001699 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner32404692009-05-25 17:16:10 +00001700 LastTok.setKind(tok::unknown);
1701 } else {
1702 Diag(Tok, diag::err_pp_stringize_not_parameter);
1703 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Chris Lattner32404692009-05-25 17:16:10 +00001705 // Disable __VA_ARGS__ again.
1706 Ident__VA_ARGS__->setIsPoisoned(true);
1707 return;
1708 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001709 }
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Chris Lattner32404692009-05-25 17:16:10 +00001711 // Things look ok, add the '#' and param name tokens to the macro.
1712 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001713 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001714 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Chris Lattner141e71f2008-03-09 01:54:53 +00001716 // Get the next token of the macro.
1717 LexUnexpandedToken(Tok);
1718 }
1719 }
Mike Stump1eb44332009-09-09 15:08:12 +00001720
1721
Chris Lattner141e71f2008-03-09 01:54:53 +00001722 // Disable __VA_ARGS__ again.
1723 Ident__VA_ARGS__->setIsPoisoned(true);
1724
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001725 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattner141e71f2008-03-09 01:54:53 +00001726 // replacement list.
1727 unsigned NumTokens = MI->getNumTokens();
1728 if (NumTokens != 0) {
1729 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1730 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001731 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001732 return;
1733 }
1734 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1735 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001736 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001737 return;
1738 }
1739 }
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Chris Lattner2451b522009-04-21 04:46:33 +00001741 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Chris Lattner141e71f2008-03-09 01:54:53 +00001743 // Finally, if this identifier already had a macro defined for it, verify that
1744 // the macro bodies are identical and free the old definition.
1745 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001746 // It is very common for system headers to have tons of macro redefinitions
1747 // and for warnings to be disabled in system headers. If this is the case,
1748 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001749 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001750 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001751 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner41c3ae12009-01-16 19:50:11 +00001752 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001753
Chris Lattnerf47724b2010-08-17 15:55:45 +00001754 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001755 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001756 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001757 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001758 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1759 << MacroNameTok.getIdentifierInfo();
1760 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1761 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001762 }
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001763 if (OtherMI->isWarnIfUnused())
1764 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek0ea76722008-12-15 19:56:42 +00001765 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001766 }
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Chris Lattner141e71f2008-03-09 01:54:53 +00001768 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001770 assert(!MI->isUsed());
1771 // If we need warning for not using the macro, add its location in the
1772 // warn-because-unused-macro set. If it gets used it will be removed from set.
1773 if (isInPrimaryFile() && // don't warn for include'd macros.
1774 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikied6471f72011-09-25 23:23:43 +00001775 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001776 MI->setIsWarnIfUnused(true);
1777 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1778 }
1779
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001780 // If the callbacks want to know, tell them about the macro definition.
1781 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001782 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001783}
1784
1785/// HandleUndefDirective - Implements #undef.
1786///
1787void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1788 ++NumUndefined;
1789
1790 Token MacroNameTok;
1791 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Chris Lattner141e71f2008-03-09 01:54:53 +00001793 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001794 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001795 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Chris Lattner141e71f2008-03-09 01:54:53 +00001797 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001798 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Chris Lattner141e71f2008-03-09 01:54:53 +00001800 // Okay, we finally have a valid identifier to undef.
1801 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Chris Lattner141e71f2008-03-09 01:54:53 +00001803 // If the macro is not defined, this is a noop undef, just return.
1804 if (MI == 0) return;
1805
Argyrios Kyrtzidis1f8dcfc2011-07-11 20:39:47 +00001806 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattner141e71f2008-03-09 01:54:53 +00001807 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001808
1809 // If the callbacks want to know, tell them about the macro #undef.
1810 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001811 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001812
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001813 if (MI->isWarnIfUnused())
1814 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1815
Chris Lattner141e71f2008-03-09 01:54:53 +00001816 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001817 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001818 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1819}
1820
1821
1822//===----------------------------------------------------------------------===//
1823// Preprocessor Conditional Directive Handling.
1824//===----------------------------------------------------------------------===//
1825
1826/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1827/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1828/// if any tokens have been returned or pp-directives activated before this
1829/// #ifndef has been lexed.
1830///
1831void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1832 bool ReadAnyTokensBeforeDirective) {
1833 ++NumIf;
1834 Token DirectiveTok = Result;
1835
1836 Token MacroNameTok;
1837 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Chris Lattner141e71f2008-03-09 01:54:53 +00001839 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001840 if (MacroNameTok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001841 // Skip code until we get to #endif. This helps with recovery by not
1842 // emitting an error when the #endif is reached.
1843 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1844 /*Foundnonskip*/false, /*FoundElse*/false);
1845 return;
1846 }
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Chris Lattner141e71f2008-03-09 01:54:53 +00001848 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001849 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001850
Chris Lattner13d283d2010-02-12 08:03:27 +00001851 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1852 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001853
Ted Kremenek60e45d42008-11-18 00:34:22 +00001854 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001855 // If the start of a top-level #ifdef and if the macro is not defined,
1856 // inform MIOpt that this might be the start of a proper include guard.
1857 // Otherwise it is some other form of unknown conditional which we can't
1858 // handle.
1859 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001860 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001861 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001862 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001863 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001864 }
1865
Chris Lattner141e71f2008-03-09 01:54:53 +00001866 // If there is a macro, process it.
1867 if (MI) // Mark it used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001868 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Chris Lattner141e71f2008-03-09 01:54:53 +00001870 // Should we include the stuff contained by this directive?
1871 if (!MI == isIfndef) {
1872 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001873 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1874 /*wasskip*/false, /*foundnonskip*/true,
1875 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001876 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001877 // No, skip the contents of this block.
Chris Lattner141e71f2008-03-09 01:54:53 +00001878 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001879 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001880 /*FoundElse*/false);
1881 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001882
1883 if (Callbacks) {
1884 if (isIfndef)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001885 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001886 else
Craig Silverstein2aa92672010-11-19 21:33:15 +00001887 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein08985b92010-11-06 01:19:03 +00001888 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001889}
1890
1891/// HandleIfDirective - Implements the #if directive.
1892///
1893void Preprocessor::HandleIfDirective(Token &IfToken,
1894 bool ReadAnyTokensBeforeDirective) {
1895 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Craig Silverstein08985b92010-11-06 01:19:03 +00001897 // Parse and evaluate the conditional expression.
Chris Lattner141e71f2008-03-09 01:54:53 +00001898 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein08985b92010-11-06 01:19:03 +00001899 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1900 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1901 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes0049db62008-06-01 18:31:24 +00001902
1903 // If this condition is equivalent to #ifndef X, and if this is the first
1904 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001905 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001906 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001907 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001908 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001909 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001910 }
1911
Chris Lattner141e71f2008-03-09 01:54:53 +00001912 // Should we include the stuff contained by this directive?
1913 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001914 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001915 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001916 /*foundnonskip*/true, /*foundelse*/false);
1917 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001918 // No, skip the contents of this block.
Mike Stump1eb44332009-09-09 15:08:12 +00001919 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001920 /*FoundElse*/false);
1921 }
Craig Silverstein08985b92010-11-06 01:19:03 +00001922
1923 if (Callbacks)
1924 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00001925}
1926
1927/// HandleEndifDirective - Implements the #endif directive.
1928///
1929void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1930 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Chris Lattner141e71f2008-03-09 01:54:53 +00001932 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00001933 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Chris Lattner141e71f2008-03-09 01:54:53 +00001935 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001936 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001937 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001938 Diag(EndifToken, diag::err_pp_endif_without_if);
1939 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001940 }
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Chris Lattner141e71f2008-03-09 01:54:53 +00001942 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001943 if (CurPPLexer->getConditionalStackDepth() == 0)
1944 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Ted Kremenek60e45d42008-11-18 00:34:22 +00001946 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001947 "This code should only be reachable in the non-skipping case!");
Craig Silverstein08985b92010-11-06 01:19:03 +00001948
1949 if (Callbacks)
1950 Callbacks->Endif();
Chris Lattner141e71f2008-03-09 01:54:53 +00001951}
1952
Craig Silverstein08985b92010-11-06 01:19:03 +00001953/// HandleElseDirective - Implements the #else directive.
1954///
Chris Lattner141e71f2008-03-09 01:54:53 +00001955void Preprocessor::HandleElseDirective(Token &Result) {
1956 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Chris Lattner141e71f2008-03-09 01:54:53 +00001958 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00001959 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Chris Lattner141e71f2008-03-09 01:54:53 +00001961 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001962 if (CurPPLexer->popConditionalLevel(CI)) {
1963 Diag(Result, diag::pp_err_else_without_if);
1964 return;
1965 }
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Chris Lattner141e71f2008-03-09 01:54:53 +00001967 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001968 if (CurPPLexer->getConditionalStackDepth() == 0)
1969 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001970
1971 // If this is a #else with a #else before it, report the error.
1972 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Craig Silverstein08985b92010-11-06 01:19:03 +00001974 // Finally, skip the rest of the contents of this block.
1975 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00001976 /*FoundElse*/true, Result.getLocation());
Craig Silverstein08985b92010-11-06 01:19:03 +00001977
1978 if (Callbacks)
1979 Callbacks->Else();
Chris Lattner141e71f2008-03-09 01:54:53 +00001980}
1981
Craig Silverstein08985b92010-11-06 01:19:03 +00001982/// HandleElifDirective - Implements the #elif directive.
1983///
Chris Lattner141e71f2008-03-09 01:54:53 +00001984void Preprocessor::HandleElifDirective(Token &ElifToken) {
1985 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Chris Lattner141e71f2008-03-09 01:54:53 +00001987 // #elif directive in a non-skipping conditional... start skipping.
1988 // We don't care what the condition is, because we will always skip it (since
1989 // the block immediately before it was included).
Craig Silverstein08985b92010-11-06 01:19:03 +00001990 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001991 DiscardUntilEndOfDirective();
Craig Silverstein08985b92010-11-06 01:19:03 +00001992 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00001993
1994 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001995 if (CurPPLexer->popConditionalLevel(CI)) {
1996 Diag(ElifToken, diag::pp_err_elif_without_if);
1997 return;
1998 }
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Chris Lattner141e71f2008-03-09 01:54:53 +00002000 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002001 if (CurPPLexer->getConditionalStackDepth() == 0)
2002 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Chris Lattner141e71f2008-03-09 01:54:53 +00002004 // If this is a #elif with a #else before it, report the error.
2005 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2006
Craig Silverstein08985b92010-11-06 01:19:03 +00002007 // Finally, skip the rest of the contents of this block.
2008 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00002009 /*FoundElse*/CI.FoundElse,
2010 ElifToken.getLocation());
Craig Silverstein08985b92010-11-06 01:19:03 +00002011
2012 if (Callbacks)
2013 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattner141e71f2008-03-09 01:54:53 +00002014}