blob: 815c47494b48600b1435cab1322369a468c69ada [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattnerf64b3522008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000016#include "clang/Lex/LiteralSupport.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000017#include "clang/Lex/HeaderSearch.h"
18#include "clang/Lex/MacroInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000019#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor3a7ad252010-08-24 19:08:16 +000020#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor97eec242011-09-15 22:00:41 +000021#include "clang/Lex/ModuleLoader.h"
Douglas Gregorc7d65762010-09-09 22:45:38 +000022#include "clang/Lex/Pragma.h"
Chris Lattner710bb872009-11-30 04:18:44 +000023#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000025#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000027using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// Utility Methods for Preprocessor Directive Handling.
31//===----------------------------------------------------------------------===//
32
Chris Lattnerc0a585d2010-08-17 15:55:45 +000033MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000034 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000035
Ted Kremenekc8456f82010-10-19 22:15:20 +000036 if (MICache) {
37 MIChain = MICache;
38 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000039 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000040 else {
41 MIChain = BP.Allocate<MacroInfoChain>();
42 }
43
44 MIChain->Next = MIChainHead;
45 MIChain->Prev = 0;
46 if (MIChainHead)
47 MIChainHead->Prev = MIChain;
48 MIChainHead = MIChain;
49
50 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000051}
52
53MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
54 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000055 new (MI) MacroInfo(L);
56 return MI;
57}
58
Chris Lattnerc0a585d2010-08-17 15:55:45 +000059MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
60 MacroInfo *MI = AllocateMacroInfo();
61 new (MI) MacroInfo(MacroToClone, BP);
62 return MI;
63}
64
James Dennettf6333ac2012-06-22 05:46:07 +000065/// \brief Release the specified MacroInfo to be reused for allocating
66/// new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +000067void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +000068 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
69 if (MacroInfoChain *Prev = MIChain->Prev) {
70 MacroInfoChain *Next = MIChain->Next;
71 Prev->Next = Next;
72 if (Next)
73 Next->Prev = Prev;
74 }
75 else {
76 assert(MIChainHead == MIChain);
77 MIChainHead = MIChain->Next;
78 MIChainHead->Prev = 0;
79 }
80 MIChain->Next = MICache;
81 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +000082
Ted Kremenekc8456f82010-10-19 22:15:20 +000083 MI->Destroy();
84}
Chris Lattner666f7a42009-02-20 22:19:20 +000085
James Dennettf6333ac2012-06-22 05:46:07 +000086/// \brief Read and discard all tokens remaining on the current line until
87/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000088void Preprocessor::DiscardUntilEndOfDirective() {
89 Token Tmp;
90 do {
91 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000092 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000093 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000094}
95
James Dennettf6333ac2012-06-22 05:46:07 +000096/// \brief Lex and validate a macro name, which occurs after a
97/// \#define or \#undef.
98///
99/// This sets the token kind to eod and discards the rest
100/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
101/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
102/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000103void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
104 // Read the token, don't allow macro expansion on it.
105 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000106
Douglas Gregor12785102010-08-24 20:21:13 +0000107 if (MacroNameTok.is(tok::code_completion)) {
108 if (CodeComplete)
109 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000110 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000111 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000112 }
113
Chris Lattnerf64b3522008-03-09 01:54:53 +0000114 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000115 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000116 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
117 return;
118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Chris Lattnerf64b3522008-03-09 01:54:53 +0000120 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
121 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000122 bool Invalid = false;
123 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
124 if (Invalid)
125 return;
Nico Weber2e686202012-02-29 22:54:43 +0000126
Chris Lattner77c76ae2008-12-13 20:12:40 +0000127 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000128
129 // Allow #defining |and| and friends in microsoft mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000130 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weber2e686202012-02-29 22:54:43 +0000131 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
132 return;
133 }
134
Chris Lattner77c76ae2008-12-13 20:12:40 +0000135 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000136 // C++ 2.5p2: Alternative tokens behave the same as its primary token
137 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000138 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000139 else
140 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
141 // Fall through on error.
142 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
143 // Error if defining "defined": C99 6.10.8.4.
144 Diag(MacroNameTok, diag::err_defined_macro_name);
145 } else if (isDefineUndef && II->hasMacroDefinition() &&
146 getMacroInfo(II)->isBuiltinMacro()) {
147 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
148 if (isDefineUndef == 1)
149 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
150 else
151 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
152 } else {
153 // Okay, we got a good identifier node. Return it.
154 return;
155 }
Mike Stump11289f42009-09-09 15:08:12 +0000156
Chris Lattnerf64b3522008-03-09 01:54:53 +0000157 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000158 // token kind to tok::eod.
159 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000160 return DiscardUntilEndOfDirective();
161}
162
James Dennettf6333ac2012-06-22 05:46:07 +0000163/// \brief Ensure that the next token is a tok::eod token.
164///
165/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000166/// true, then we consider macros that expand to zero tokens as being ok.
167void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000168 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000169 // Lex unexpanded tokens for most directives: macros might expand to zero
170 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
171 // #line) allow empty macros.
172 if (EnableMacros)
173 Lex(Tmp);
174 else
175 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000176
Chris Lattnerf64b3522008-03-09 01:54:53 +0000177 // There should be no tokens after the directive, but we allow them as an
178 // extension.
179 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
180 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000181
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000182 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000183 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000184 // or if this is a macro-style preprocessing directive, because it is more
185 // trouble than it is worth to insert /**/ and check that there is no /**/
186 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000187 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000188 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000189 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000190 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
191 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000192 DiscardUntilEndOfDirective();
193 }
194}
195
196
197
James Dennettf6333ac2012-06-22 05:46:07 +0000198/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
199/// decided that the subsequent tokens are in the \#if'd out portion of the
200/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000201/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000202/// this \#if directive, so \#else/\#elif blocks should never be entered.
203/// If ElseOk is true, then \#else directives are ok, if not, then we have
204/// already seen one so a \#else directive is a duplicate. When this returns,
205/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000206void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
207 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000208 bool FoundElse,
209 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000210 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000211 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000212
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000213 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000214 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000215
Ted Kremenek56572ab2008-12-12 18:34:08 +0000216 if (CurPTHLexer) {
217 PTHSkipExcludedConditionalBlock();
218 return;
219 }
Mike Stump11289f42009-09-09 15:08:12 +0000220
Chris Lattnerf64b3522008-03-09 01:54:53 +0000221 // Enter raw mode to disable identifier lookup (and thus macro expansion),
222 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000223 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000224 Token Tok;
225 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000226 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000227
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000228 if (Tok.is(tok::code_completion)) {
229 if (CodeComplete)
230 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000231 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000232 continue;
233 }
234
Chris Lattnerf64b3522008-03-09 01:54:53 +0000235 // If this is the end of the buffer, we have an error.
236 if (Tok.is(tok::eof)) {
237 // Emit errors for each unterminated conditional on the stack, including
238 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000239 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000240 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000241 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
242 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000243 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000244 }
245
Chris Lattnerf64b3522008-03-09 01:54:53 +0000246 // Just return and let the caller lex after this #include.
247 break;
248 }
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattnerf64b3522008-03-09 01:54:53 +0000250 // If this token is not a preprocessor directive, just skip it.
251 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
252 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000253
Chris Lattnerf64b3522008-03-09 01:54:53 +0000254 // We just parsed a # character at the start of a line, so we're in
255 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000256 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000257 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000258 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000259
Mike Stump11289f42009-09-09 15:08:12 +0000260
Chris Lattnerf64b3522008-03-09 01:54:53 +0000261 // Read the next token, the directive flavor.
262 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000263
Chris Lattnerf64b3522008-03-09 01:54:53 +0000264 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
265 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000266 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000267 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000268 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000269 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000270 continue;
271 }
272
273 // If the first letter isn't i or e, it isn't intesting to us. We know that
274 // this is safe in the face of spelling differences, because there is no way
275 // to spell an i/e in a strange way that is another letter. Skipping this
276 // allows us to avoid looking up the identifier info for #define/#undef and
277 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000278 const char *RawCharData = Tok.getRawIdentifierData();
279
Chris Lattnerf64b3522008-03-09 01:54:53 +0000280 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000281 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000282 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000283 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000284 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000285 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000286 continue;
287 }
Mike Stump11289f42009-09-09 15:08:12 +0000288
Chris Lattnerf64b3522008-03-09 01:54:53 +0000289 // Get the identifier name without trigraphs or embedded newlines. Note
290 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
291 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000292 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000293 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000294 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000295 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000296 } else {
297 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000298 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000299 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000300 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000301 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000302 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000303 continue;
304 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000305 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000306 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000307 }
Mike Stump11289f42009-09-09 15:08:12 +0000308
Benjamin Kramer144884642009-12-31 13:32:38 +0000309 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000310 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000311 if (Sub.empty() || // "if"
312 Sub == "def" || // "ifdef"
313 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
315 // bother parsing the condition.
316 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000317 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000318 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000319 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000320 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000321 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000322 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000323 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000324 PPConditionalInfo CondInfo;
325 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000326 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000327 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000328 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattnerf64b3522008-03-09 01:54:53 +0000330 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000331 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000332 // Restore the value of LexingRawMode so that trailing comments
333 // are handled correctly, if we've reached the outermost block.
334 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000335 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000336 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000337 if (Callbacks)
338 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000339 break;
Richard Smithd0124572012-06-21 00:35:03 +0000340 } else {
341 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000342 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000343 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000344 // #else directive in a skipping conditional. If not in some other
345 // skipping conditional, and if #else hasn't already been seen, enter it
346 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000347 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000348
Chris Lattnerf64b3522008-03-09 01:54:53 +0000349 // If this is a #else with a #else before it, report the error.
350 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000351
Chris Lattnerf64b3522008-03-09 01:54:53 +0000352 // Note that we've seen a #else in this conditional.
353 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000354
Chris Lattnerf64b3522008-03-09 01:54:53 +0000355 // If the conditional is at the top level, and the #if block wasn't
356 // entered, enter the #else block now.
357 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
358 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000359 // Restore the value of LexingRawMode so that trailing comments
360 // are handled correctly.
361 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000362 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000363 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000364 if (Callbacks)
365 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000366 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000367 } else {
368 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000369 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000370 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000371 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000372
373 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000374 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000375 // If this is in a skipping block or if we're already handled this #if
376 // block, don't bother parsing the condition.
377 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
378 DiscardUntilEndOfDirective();
379 ShouldEnter = false;
380 } else {
381 // Restore the value of LexingRawMode so that identifiers are
382 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000383 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
384 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385 IdentifierInfo *IfNDefMacro = 0;
386 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000387 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000388 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000389 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000390
Chris Lattnerf64b3522008-03-09 01:54:53 +0000391 // If this is a #elif with a #else before it, report the error.
392 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000393
Chris Lattnerf64b3522008-03-09 01:54:53 +0000394 // If this condition is true, enter it!
395 if (ShouldEnter) {
396 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000397 if (Callbacks)
398 Callbacks->Elif(Tok.getLocation(),
399 SourceRange(ConditionalBegin, ConditionalEnd),
400 CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000401 break;
402 }
403 }
404 }
Mike Stump11289f42009-09-09 15:08:12 +0000405
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000406 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000407 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000408 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000409 }
410
411 // Finally, if we are out of the conditional (saw an #endif or ran off the end
412 // of the file, just stop skipping and return to lexing whatever came after
413 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000414 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000415
416 if (Callbacks) {
417 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
418 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
419 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000420}
421
Ted Kremenek56572ab2008-12-12 18:34:08 +0000422void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000423
424 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000425 assert(CurPTHLexer);
426 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000427
Ted Kremenek56572ab2008-12-12 18:34:08 +0000428 // Skip to the next '#else', '#elif', or #endif.
429 if (CurPTHLexer->SkipBlock()) {
430 // We have reached an #endif. Both the '#' and 'endif' tokens
431 // have been consumed by the PTHLexer. Just pop off the condition level.
432 PPConditionalInfo CondInfo;
433 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000434 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000435 assert(!InCond && "Can't be skipping if not in a conditional!");
436 break;
437 }
Mike Stump11289f42009-09-09 15:08:12 +0000438
Ted Kremenek56572ab2008-12-12 18:34:08 +0000439 // We have reached a '#else' or '#elif'. Lex the next token to get
440 // the directive flavor.
441 Token Tok;
442 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000443
Ted Kremenek56572ab2008-12-12 18:34:08 +0000444 // We can actually look up the IdentifierInfo here since we aren't in
445 // raw mode.
446 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
447
448 if (K == tok::pp_else) {
449 // #else: Enter the else condition. We aren't in a nested condition
450 // since we skip those. We're always in the one matching the last
451 // blocked we skipped.
452 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
453 // Note that we've seen a #else in this conditional.
454 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000455
Ted Kremenek56572ab2008-12-12 18:34:08 +0000456 // If the #if block wasn't entered then enter the #else block now.
457 if (!CondInfo.FoundNonSkip) {
458 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000459
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000460 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000461 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000462 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000463 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000464
Ted Kremenek56572ab2008-12-12 18:34:08 +0000465 break;
466 }
Mike Stump11289f42009-09-09 15:08:12 +0000467
Ted Kremenek56572ab2008-12-12 18:34:08 +0000468 // Otherwise skip this block.
469 continue;
470 }
Mike Stump11289f42009-09-09 15:08:12 +0000471
Ted Kremenek56572ab2008-12-12 18:34:08 +0000472 assert(K == tok::pp_elif);
473 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
474
475 // If this is a #elif with a #else before it, report the error.
476 if (CondInfo.FoundElse)
477 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000478
Ted Kremenek56572ab2008-12-12 18:34:08 +0000479 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000480 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000481 if (CondInfo.FoundNonSkip)
482 continue;
483
484 // Evaluate the condition of the #elif.
485 IdentifierInfo *IfNDefMacro = 0;
486 CurPTHLexer->ParsingPreprocessorDirective = true;
487 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
488 CurPTHLexer->ParsingPreprocessorDirective = false;
489
490 // If this condition is true, enter it!
491 if (ShouldEnter) {
492 CondInfo.FoundNonSkip = true;
493 break;
494 }
495
496 // Otherwise, skip this block and go to the next one.
497 continue;
498 }
499}
500
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000501const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000502 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000503 bool isAngled,
504 const DirectoryLookup *FromDir,
505 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000506 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000507 SmallVectorImpl<char> *RelativePath,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000508 Module **SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000509 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000510 // If the header lookup mechanism may be relative to the current file, pass in
511 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000512 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000513 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000514 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000515 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chris Lattner022923a2009-02-04 19:45:07 +0000517 // If there is no file entry associated with this file, it must be the
518 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000519 // it won't be scanned for preprocessor directives. If we have the
520 // predefines buffer, resolve #include references (which come from the
521 // -include command line argument) as if they came from the main file, this
522 // affects file lookup etc.
523 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000524 FID = SourceMgr.getMainFileID();
525 CurFileEnt = SourceMgr.getFileEntryForID(FID);
526 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000527 }
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000529 // Do a standard file entry lookup.
530 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000531 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000532 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000533 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerfde85352010-01-22 00:14:44 +0000534 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000535
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000536 // Otherwise, see if this is a subframework header. If so, this is relative
537 // to one of the headers on the #include stack. Walk the list of the current
538 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregor97eec242011-09-15 22:00:41 +0000539 // FIXME: SuggestedModule!
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000540 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000541 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000542 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000543 SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000544 return FE;
545 }
Mike Stump11289f42009-09-09 15:08:12 +0000546
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000547 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
548 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000549 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000550 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000551 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000552 if ((FE = HeaderInfo.LookupSubframeworkHeader(
553 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000554 return FE;
555 }
556 }
Mike Stump11289f42009-09-09 15:08:12 +0000557
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000558 // Otherwise, we really couldn't find the file.
559 return 0;
560}
561
Chris Lattnerf64b3522008-03-09 01:54:53 +0000562
563//===----------------------------------------------------------------------===//
564// Preprocessor Directive Handling.
565//===----------------------------------------------------------------------===//
566
David Blaikied5321242012-06-06 18:52:13 +0000567class Preprocessor::ResetMacroExpansionHelper {
568public:
569 ResetMacroExpansionHelper(Preprocessor *pp)
570 : PP(pp), save(pp->DisableMacroExpansion) {
571 if (pp->MacroExpansionInDirectivesOverride)
572 pp->DisableMacroExpansion = false;
573 }
574 ~ResetMacroExpansionHelper() {
575 PP->DisableMacroExpansion = save;
576 }
577private:
578 Preprocessor *PP;
579 bool save;
580};
581
Chris Lattnerf64b3522008-03-09 01:54:53 +0000582/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000583/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000584/// lexer/preprocessor state, and advances the lexer(s) so that the next token
585/// read is the correct one.
586void Preprocessor::HandleDirective(Token &Result) {
587 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000588
Chris Lattnerf64b3522008-03-09 01:54:53 +0000589 // We just parsed a # character at the start of a line, so we're in directive
590 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000591 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000592 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000593
Chris Lattnerf64b3522008-03-09 01:54:53 +0000594 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000595
Chris Lattnerf64b3522008-03-09 01:54:53 +0000596 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000597 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000598 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000599 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000600
Chris Lattner2d17ab72009-03-18 21:00:25 +0000601 // Save the '#' token in case we need to return it later.
602 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000603
Chris Lattnerf64b3522008-03-09 01:54:53 +0000604 // Read the next token, the directive flavor. This isn't expanded due to
605 // C99 6.10.3p8.
606 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000607
Chris Lattnerf64b3522008-03-09 01:54:53 +0000608 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
609 // #define A(x) #x
610 // A(abc
611 // #warning blah
612 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000613 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
614 // not support this for #include-like directives, since that can result in
615 // terrible diagnostics, and does not work in GCC.
616 if (InMacroArgs) {
617 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
618 switch (II->getPPKeywordID()) {
619 case tok::pp_include:
620 case tok::pp_import:
621 case tok::pp_include_next:
622 case tok::pp___include_macros:
623 Diag(Result, diag::err_embedded_include) << II->getName();
624 DiscardUntilEndOfDirective();
625 return;
626 default:
627 break;
628 }
629 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000630 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000631 }
Mike Stump11289f42009-09-09 15:08:12 +0000632
David Blaikied5321242012-06-06 18:52:13 +0000633 // Temporarily enable macro expansion if set so
634 // and reset to previous state when returning from this function.
635 ResetMacroExpansionHelper helper(this);
636
Chris Lattnerf64b3522008-03-09 01:54:53 +0000637TryAgain:
638 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000639 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000640 return; // null directive.
641 case tok::comment:
642 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
643 LexUnexpandedToken(Result);
644 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000645 case tok::code_completion:
646 if (CodeComplete)
647 CodeComplete->CodeCompleteDirective(
648 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000649 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000650 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000651 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000652 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000653 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000654 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000655 default:
656 IdentifierInfo *II = Result.getIdentifierInfo();
657 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000658
Chris Lattnerf64b3522008-03-09 01:54:53 +0000659 // Ask what the preprocessor keyword ID is.
660 switch (II->getPPKeywordID()) {
661 default: break;
662 // C99 6.10.1 - Conditional Inclusion.
663 case tok::pp_if:
664 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
665 case tok::pp_ifdef:
666 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
667 case tok::pp_ifndef:
668 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
669 case tok::pp_elif:
670 return HandleElifDirective(Result);
671 case tok::pp_else:
672 return HandleElseDirective(Result);
673 case tok::pp_endif:
674 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000675
Chris Lattnerf64b3522008-03-09 01:54:53 +0000676 // C99 6.10.2 - Source File Inclusion.
677 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000678 // Handle #include.
679 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000680 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000681 // Handle -imacros.
682 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000683
Chris Lattnerf64b3522008-03-09 01:54:53 +0000684 // C99 6.10.3 - Macro Replacement.
685 case tok::pp_define:
686 return HandleDefineDirective(Result);
687 case tok::pp_undef:
688 return HandleUndefDirective(Result);
689
690 // C99 6.10.4 - Line Control.
691 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000692 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000693
Chris Lattnerf64b3522008-03-09 01:54:53 +0000694 // C99 6.10.5 - Error Directive.
695 case tok::pp_error:
696 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattnerf64b3522008-03-09 01:54:53 +0000698 // C99 6.10.6 - Pragma Directive.
699 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000700 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000701
Chris Lattnerf64b3522008-03-09 01:54:53 +0000702 // GNU Extensions.
703 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000704 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000705 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000706 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000707
Chris Lattnerf64b3522008-03-09 01:54:53 +0000708 case tok::pp_warning:
709 Diag(Result, diag::ext_pp_warning_directive);
710 return HandleUserDiagnosticDirective(Result, true);
711 case tok::pp_ident:
712 return HandleIdentSCCSDirective(Result);
713 case tok::pp_sccs:
714 return HandleIdentSCCSDirective(Result);
715 case tok::pp_assert:
716 //isExtension = true; // FIXME: implement #assert
717 break;
718 case tok::pp_unassert:
719 //isExtension = true; // FIXME: implement #unassert
720 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000721
Douglas Gregor663b48f2012-01-03 19:48:16 +0000722 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000723 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000724 return HandleMacroPublicDirective(Result);
725 break;
726
Douglas Gregor663b48f2012-01-03 19:48:16 +0000727 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000728 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000729 return HandleMacroPrivateDirective(Result);
730 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000731 }
732 break;
733 }
Mike Stump11289f42009-09-09 15:08:12 +0000734
Chris Lattner2d17ab72009-03-18 21:00:25 +0000735 // If this is a .S file, treat unknown # directives as non-preprocessor
736 // directives. This is important because # may be a comment or introduce
737 // various pseudo-ops. Just return the # token and push back the following
738 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000739 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000740 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000741 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000742 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000743 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000744
745 // If the second token is a hashhash token, then we need to translate it to
746 // unknown so the token lexer doesn't try to perform token pasting.
747 if (Result.is(tok::hashhash))
748 Toks[1].setKind(tok::unknown);
749
Chris Lattner2d17ab72009-03-18 21:00:25 +0000750 // Enter this token stream so that we re-lex the tokens. Make sure to
751 // enable macro expansion, in case the token after the # is an identifier
752 // that is expanded.
753 EnterTokenStream(Toks, 2, false, true);
754 return;
755 }
Mike Stump11289f42009-09-09 15:08:12 +0000756
Chris Lattnerf64b3522008-03-09 01:54:53 +0000757 // If we reached here, the preprocessing token is not valid!
758 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000759
Chris Lattnerf64b3522008-03-09 01:54:53 +0000760 // Read the rest of the PP line.
761 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000762
Chris Lattnerf64b3522008-03-09 01:54:53 +0000763 // Okay, we're done parsing the directive.
764}
765
Chris Lattner76e68962009-01-26 06:19:46 +0000766/// GetLineValue - Convert a numeric token into an unsigned value, emitting
767/// Diagnostic DiagID if it is invalid, and returning the value in Val.
768static bool GetLineValue(Token &DigitTok, unsigned &Val,
769 unsigned DiagID, Preprocessor &PP) {
770 if (DigitTok.isNot(tok::numeric_constant)) {
771 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000772
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000773 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000774 PP.DiscardUntilEndOfDirective();
775 return true;
776 }
Mike Stump11289f42009-09-09 15:08:12 +0000777
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000778 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000779 IntegerBuffer.resize(DigitTok.getLength());
780 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000781 bool Invalid = false;
782 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
783 if (Invalid)
784 return true;
785
Chris Lattnerd66f1722009-04-18 18:35:15 +0000786 // Verify that we have a simple digit-sequence, and compute the value. This
787 // is always a simple digit string computed in decimal, so we do this manually
788 // here.
789 Val = 0;
790 for (unsigned i = 0; i != ActualLength; ++i) {
791 if (!isdigit(DigitTokBegin[i])) {
792 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
793 diag::err_pp_line_digit_sequence);
794 PP.DiscardUntilEndOfDirective();
795 return true;
796 }
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattnerd66f1722009-04-18 18:35:15 +0000798 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
799 if (NextVal < Val) { // overflow.
800 PP.Diag(DigitTok, DiagID);
801 PP.DiscardUntilEndOfDirective();
802 return true;
803 }
804 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000805 }
Mike Stump11289f42009-09-09 15:08:12 +0000806
807 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000808 if (Val == 0) {
809 PP.Diag(DigitTok, DiagID);
810 PP.DiscardUntilEndOfDirective();
811 return true;
812 }
Mike Stump11289f42009-09-09 15:08:12 +0000813
Chris Lattnerd66f1722009-04-18 18:35:15 +0000814 if (DigitTokBegin[0] == '0')
815 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000816
Chris Lattner76e68962009-01-26 06:19:46 +0000817 return false;
818}
819
James Dennettf6333ac2012-06-22 05:46:07 +0000820/// \brief Handle a \#line directive: C99 6.10.4.
821///
822/// The two acceptable forms are:
823/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000824/// # line digit-sequence
825/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000826/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000827void Preprocessor::HandleLineDirective(Token &Tok) {
828 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
829 // expanded.
830 Token DigitTok;
831 Lex(DigitTok);
832
Chris Lattner100c65e2009-01-26 05:29:08 +0000833 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000834 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000835 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000836 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000837
Chris Lattner76e68962009-01-26 06:19:46 +0000838 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
839 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000840 unsigned LineLimit = 32768U;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000841 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
Eli Friedman192e0342011-10-10 23:35:28 +0000842 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000843 if (LineNo >= LineLimit)
844 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000845 else if (LangOpts.CPlusPlus0x && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000846 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000848 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000849 Token StrTok;
850 Lex(StrTok);
851
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000852 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
853 // string followed by eod.
854 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000855 ; // ok
856 else if (StrTok.isNot(tok::string_literal)) {
857 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000858 return DiscardUntilEndOfDirective();
859 } else if (StrTok.hasUDSuffix()) {
860 Diag(StrTok, diag::err_invalid_string_udl);
861 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000862 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000863 // Parse and validate the string, converting it into a unique ID.
864 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000865 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000866 if (Literal.hadError)
867 return DiscardUntilEndOfDirective();
868 if (Literal.Pascal) {
869 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
870 return DiscardUntilEndOfDirective();
871 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000872 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000873
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000874 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000875 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
876 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000877 }
Mike Stump11289f42009-09-09 15:08:12 +0000878
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000879 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000880
Chris Lattner839150e2009-03-27 17:13:49 +0000881 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000882 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
883 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000884 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000885}
886
Chris Lattner76e68962009-01-26 06:19:46 +0000887/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
888/// marker directive.
889static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
890 bool &IsSystemHeader, bool &IsExternCHeader,
891 Preprocessor &PP) {
892 unsigned FlagVal;
893 Token FlagTok;
894 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000895 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000896 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
897 return true;
898
899 if (FlagVal == 1) {
900 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000901
Chris Lattner76e68962009-01-26 06:19:46 +0000902 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000903 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000904 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
905 return true;
906 } else if (FlagVal == 2) {
907 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000908
Chris Lattner1c967782009-02-04 06:25:26 +0000909 SourceManager &SM = PP.getSourceManager();
910 // If we are leaving the current presumed file, check to make sure the
911 // presumed include stack isn't empty!
912 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000913 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000914 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000915 if (PLoc.isInvalid())
916 return true;
917
Chris Lattner1c967782009-02-04 06:25:26 +0000918 // If there is no include loc (main file) or if the include loc is in a
919 // different physical file, then we aren't in a "1" line marker flag region.
920 SourceLocation IncLoc = PLoc.getIncludeLoc();
921 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000922 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000923 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
924 PP.DiscardUntilEndOfDirective();
925 return true;
926 }
Mike Stump11289f42009-09-09 15:08:12 +0000927
Chris Lattner76e68962009-01-26 06:19:46 +0000928 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000929 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000930 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
931 return true;
932 }
933
934 // We must have 3 if there are still flags.
935 if (FlagVal != 3) {
936 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000937 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000938 return true;
939 }
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattner76e68962009-01-26 06:19:46 +0000941 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattner76e68962009-01-26 06:19:46 +0000943 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000944 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000945 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000946 return true;
947
948 // We must have 4 if there is yet another flag.
949 if (FlagVal != 4) {
950 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000951 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000952 return true;
953 }
Mike Stump11289f42009-09-09 15:08:12 +0000954
Chris Lattner76e68962009-01-26 06:19:46 +0000955 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000956
Chris Lattner76e68962009-01-26 06:19:46 +0000957 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000958 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000959
960 // There are no more valid flags here.
961 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000962 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000963 return true;
964}
965
966/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
967/// one of the following forms:
968///
969/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000970/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000971/// # 42 "file" ('1' | '2')? '3' '4'?
972///
973void Preprocessor::HandleDigitDirective(Token &DigitTok) {
974 // Validate the number and convert it to an unsigned. GNU does not have a
975 // line # limit other than it fit in 32-bits.
976 unsigned LineNo;
977 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
978 *this))
979 return;
Mike Stump11289f42009-09-09 15:08:12 +0000980
Chris Lattner76e68962009-01-26 06:19:46 +0000981 Token StrTok;
982 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000983
Chris Lattner76e68962009-01-26 06:19:46 +0000984 bool IsFileEntry = false, IsFileExit = false;
985 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000986 int FilenameID = -1;
987
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000988 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
989 // string followed by eod.
990 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000991 ; // ok
992 else if (StrTok.isNot(tok::string_literal)) {
993 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000994 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +0000995 } else if (StrTok.hasUDSuffix()) {
996 Diag(StrTok, diag::err_invalid_string_udl);
997 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000998 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000999 // Parse and validate the string, converting it into a unique ID.
1000 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001001 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001002 if (Literal.hadError)
1003 return DiscardUntilEndOfDirective();
1004 if (Literal.Pascal) {
1005 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1006 return DiscardUntilEndOfDirective();
1007 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001008 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001009
Chris Lattner76e68962009-01-26 06:19:46 +00001010 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001011 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001012 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001013 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001016 // Create a line note with this information.
1017 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001018 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001019 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001020
Chris Lattner839150e2009-03-27 17:13:49 +00001021 // If the preprocessor has callbacks installed, notify them of the #line
1022 // change. This is used so that the line marker comes out in -E mode for
1023 // example.
1024 if (Callbacks) {
1025 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1026 if (IsFileEntry)
1027 Reason = PPCallbacks::EnterFile;
1028 else if (IsFileExit)
1029 Reason = PPCallbacks::ExitFile;
1030 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1031 if (IsExternCHeader)
1032 FileKind = SrcMgr::C_ExternCSystem;
1033 else if (IsSystemHeader)
1034 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001035
Chris Lattnerc745cec2010-04-14 04:28:50 +00001036 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001037 }
Chris Lattner76e68962009-01-26 06:19:46 +00001038}
1039
1040
Chris Lattner38d7fd22009-01-26 05:30:54 +00001041/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1042///
Mike Stump11289f42009-09-09 15:08:12 +00001043void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001044 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001045 // PTH doesn't emit #warning or #error directives.
1046 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001047 return CurPTHLexer->DiscardToEndOfLine();
1048
Chris Lattnerf64b3522008-03-09 01:54:53 +00001049 // Read the rest of the line raw. We do this because we don't want macros
1050 // to be expanded and we don't require that the tokens be valid preprocessing
1051 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1052 // collapse multiple consequtive white space between tokens, but this isn't
1053 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001054 SmallString<128> Message;
1055 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001056
1057 // Find the first non-whitespace character, so that we can make the
1058 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001059 StringRef Msg = Message.str().ltrim(" ");
1060
Chris Lattner100c65e2009-01-26 05:29:08 +00001061 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001062 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001063 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001064 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001065}
1066
1067/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1068///
1069void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1070 // Yes, this directive is an extension.
1071 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattnerf64b3522008-03-09 01:54:53 +00001073 // Read the string argument.
1074 Token StrTok;
1075 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001076
Chris Lattnerf64b3522008-03-09 01:54:53 +00001077 // If the token kind isn't a string, it's a malformed directive.
1078 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001079 StrTok.isNot(tok::wide_string_literal)) {
1080 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001081 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001082 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001083 return;
1084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
Richard Smithd67aea22012-03-06 03:21:47 +00001086 if (StrTok.hasUDSuffix()) {
1087 Diag(StrTok, diag::err_invalid_string_udl);
1088 return DiscardUntilEndOfDirective();
1089 }
1090
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001091 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001092 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001093
Douglas Gregordc970f02010-03-16 22:30:13 +00001094 if (Callbacks) {
1095 bool Invalid = false;
1096 std::string Str = getSpelling(StrTok, &Invalid);
1097 if (!Invalid)
1098 Callbacks->Ident(Tok.getLocation(), Str);
1099 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001100}
1101
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001102/// \brief Handle a #public directive.
1103void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001104 Token MacroNameTok;
1105 ReadMacroName(MacroNameTok, 2);
1106
1107 // Error reading macro name? If so, diagnostic already issued.
1108 if (MacroNameTok.is(tok::eod))
1109 return;
1110
Douglas Gregor663b48f2012-01-03 19:48:16 +00001111 // Check to see if this is the last token on the #__public_macro line.
1112 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001113
1114 // Okay, we finally have a valid identifier to undef.
1115 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1116
1117 // If the macro is not defined, this is an error.
1118 if (MI == 0) {
Douglas Gregorebf00492011-10-17 15:32:29 +00001119 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001120 << MacroNameTok.getIdentifierInfo();
1121 return;
1122 }
1123
1124 // Note that this macro has now been exported.
Douglas Gregorebf00492011-10-17 15:32:29 +00001125 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1126
1127 // If this macro definition came from a PCH file, mark it
1128 // as having changed since serialization.
1129 if (MI->isFromAST())
1130 MI->setChangedAfterLoad();
1131}
1132
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001133/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001134void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1135 Token MacroNameTok;
1136 ReadMacroName(MacroNameTok, 2);
1137
1138 // Error reading macro name? If so, diagnostic already issued.
1139 if (MacroNameTok.is(tok::eod))
1140 return;
1141
Douglas Gregor663b48f2012-01-03 19:48:16 +00001142 // Check to see if this is the last token on the #__private_macro line.
1143 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001144
1145 // Okay, we finally have a valid identifier to undef.
1146 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1147
1148 // If the macro is not defined, this is an error.
1149 if (MI == 0) {
1150 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1151 << MacroNameTok.getIdentifierInfo();
1152 return;
1153 }
1154
1155 // Note that this macro has now been marked private.
1156 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001157
1158 // If this macro definition came from a PCH file, mark it
1159 // as having changed since serialization.
1160 if (MI->isFromAST())
1161 MI->setChangedAfterLoad();
1162}
1163
Chris Lattnerf64b3522008-03-09 01:54:53 +00001164//===----------------------------------------------------------------------===//
1165// Preprocessor Include Directive Handling.
1166//===----------------------------------------------------------------------===//
1167
1168/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001169/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001170/// true if the input filename was in <>'s or false if it were in ""'s. The
1171/// caller is expected to provide a buffer that is large enough to hold the
1172/// spelling of the filename, but is also expected to handle the case when
1173/// this method decides to use a different buffer.
1174bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001175 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001176 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001177 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001178
Chris Lattnerf64b3522008-03-09 01:54:53 +00001179 // Make sure the filename is <x> or "x".
1180 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001181 if (Buffer[0] == '<') {
1182 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001183 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001184 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001185 return true;
1186 }
1187 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001188 } else if (Buffer[0] == '"') {
1189 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001190 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001191 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001192 return true;
1193 }
1194 isAngled = false;
1195 } else {
1196 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001197 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001198 return true;
1199 }
Mike Stump11289f42009-09-09 15:08:12 +00001200
Chris Lattnerf64b3522008-03-09 01:54:53 +00001201 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001202 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001203 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001204 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001205 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001206 }
Mike Stump11289f42009-09-09 15:08:12 +00001207
Chris Lattnerf64b3522008-03-09 01:54:53 +00001208 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001209 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001210 return isAngled;
1211}
1212
James Dennettf6333ac2012-06-22 05:46:07 +00001213/// \brief Handle cases where the \#include name is expanded from a macro
1214/// as multiple tokens, which need to be glued together.
1215///
1216/// This occurs for code like:
1217/// \code
1218/// \#define FOO <a/b.h>
1219/// \#include FOO
1220/// \endcode
Chris Lattnerf64b3522008-03-09 01:54:53 +00001221/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1222///
1223/// This code concatenates and consumes tokens up to the '>' token. It returns
1224/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001225/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001226bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001227 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001228 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001229 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001230
John Thompsonb5353522009-10-30 13:49:06 +00001231 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001232 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001233 End = CurTok.getLocation();
1234
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001235 // FIXME: Provide code completion for #includes.
1236 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001237 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001238 Lex(CurTok);
1239 continue;
1240 }
1241
Chris Lattnerf64b3522008-03-09 01:54:53 +00001242 // Append the spelling of this token to the buffer. If there was a space
1243 // before it, add it now.
1244 if (CurTok.hasLeadingSpace())
1245 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001246
Chris Lattnerf64b3522008-03-09 01:54:53 +00001247 // Get the spelling of the token, directly into FilenameBuffer if possible.
1248 unsigned PreAppendSize = FilenameBuffer.size();
1249 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001250
Chris Lattnerf64b3522008-03-09 01:54:53 +00001251 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001252 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001253
Chris Lattnerf64b3522008-03-09 01:54:53 +00001254 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1255 if (BufPtr != &FilenameBuffer[PreAppendSize])
1256 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001257
Chris Lattnerf64b3522008-03-09 01:54:53 +00001258 // Resize FilenameBuffer to the correct size.
1259 if (CurTok.getLength() != ActualLen)
1260 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattnerf64b3522008-03-09 01:54:53 +00001262 // If we found the '>' marker, return success.
1263 if (CurTok.is(tok::greater))
1264 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001265
John Thompsonb5353522009-10-30 13:49:06 +00001266 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001267 }
1268
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001269 // If we hit the eod marker, emit an error and return true so that the caller
1270 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001271 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001272 return true;
1273}
1274
James Dennettf6333ac2012-06-22 05:46:07 +00001275/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1276/// the file to be included from the lexer, then include it! This is a common
1277/// routine with functionality shared between \#include, \#include_next and
1278/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001279/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001280void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1281 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001282 const DirectoryLookup *LookupFrom,
1283 bool isImport) {
1284
1285 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001286 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001287
Chris Lattnerf64b3522008-03-09 01:54:53 +00001288 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001289 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001290 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001291 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001292 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001293
Chris Lattnerf64b3522008-03-09 01:54:53 +00001294 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001295 case tok::eod:
1296 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001297 return;
Mike Stump11289f42009-09-09 15:08:12 +00001298
Chris Lattnerf64b3522008-03-09 01:54:53 +00001299 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001300 case tok::string_literal:
1301 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001302 End = FilenameTok.getLocation();
Douglas Gregor41e115a2011-11-30 18:02:36 +00001303 CharEnd = End.getLocWithOffset(Filename.size());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001304 break;
Mike Stump11289f42009-09-09 15:08:12 +00001305
Chris Lattnerf64b3522008-03-09 01:54:53 +00001306 case tok::less:
1307 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1308 // case, glue the tokens together into FilenameBuffer and interpret those.
1309 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001310 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001311 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001312 Filename = FilenameBuffer.str();
Douglas Gregor41e115a2011-11-30 18:02:36 +00001313 CharEnd = getLocForEndOfToken(End);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001314 break;
1315 default:
1316 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1317 DiscardUntilEndOfDirective();
1318 return;
1319 }
Mike Stump11289f42009-09-09 15:08:12 +00001320
Aaron Ballman611306e2012-03-02 22:51:54 +00001321 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001322 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001323 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001324 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1325 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001326 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001327 DiscardUntilEndOfDirective();
1328 return;
1329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001331 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001332 // we allow macros that expand to nothing after the filename, because this
1333 // falls into the category of "#include pp-tokens new-line" specified in
1334 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001335 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001336
1337 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001338 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1339 Diag(FilenameTok, diag::err_pp_include_too_deep);
1340 return;
1341 }
Mike Stump11289f42009-09-09 15:08:12 +00001342
John McCall32f5fe12011-09-30 05:12:12 +00001343 // Complain about attempts to #include files in an audit pragma.
1344 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1345 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1346 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1347
1348 // Immediately leave the pragma.
1349 PragmaARCCFCodeAuditedLoc = SourceLocation();
1350 }
1351
Aaron Ballman611306e2012-03-02 22:51:54 +00001352 if (HeaderInfo.HasIncludeAliasMap()) {
1353 // Map the filename with the brackets still attached. If the name doesn't
1354 // map to anything, fall back on the filename we've already gotten the
1355 // spelling for.
1356 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1357 if (!NewName.empty())
1358 Filename = NewName;
1359 }
1360
Chris Lattnerf64b3522008-03-09 01:54:53 +00001361 // Search include directories.
1362 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001363 SmallString<1024> SearchPath;
1364 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001365 // We get the raw path only if we have 'Callbacks' to which we later pass
1366 // the path.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001367 Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001368 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001369 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001370 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001371 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001372
Douglas Gregor11729f02011-11-30 18:12:06 +00001373 if (Callbacks) {
1374 if (!File) {
1375 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001376 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001377 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1378 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1379 // Add the recovery path to the list of search paths.
1380 DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
1381 HeaderInfo.AddSearchPath(DL, isAngled);
1382
1383 // Try the lookup again, skipping the cache.
1384 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001385 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001386 /*SkipCache*/true);
1387 }
1388 }
1389 }
1390
1391 // Notify the callback object that we've seen an inclusion directive.
1392 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1393 End, SearchPath, RelativePath);
1394 }
1395
1396 if (File == 0) {
1397 if (!SuppressIncludeNotFoundError)
1398 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1399 return;
1400 }
1401
Douglas Gregor97eec242011-09-15 22:00:41 +00001402 // If we are supposed to import a module rather than including the header,
1403 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001404 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001405 // Compute the module access path corresponding to this module.
1406 // FIXME: Should we have a second loadModule() overload to avoid this
1407 // extra lookup step?
1408 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregorde3ef502011-11-30 23:21:26 +00001409 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001410 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1411 FilenameTok.getLocation()));
1412 std::reverse(Path.begin(), Path.end());
1413
Douglas Gregor41e115a2011-11-30 18:02:36 +00001414 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001415 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001416 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1417 if (I)
1418 PathString += '.';
1419 PathString += Path[I].first->getName();
1420 }
1421 int IncludeKind = 0;
1422
1423 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1424 case tok::pp_include:
1425 IncludeKind = 0;
1426 break;
1427
1428 case tok::pp_import:
1429 IncludeKind = 1;
1430 break;
1431
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001432 case tok::pp_include_next:
1433 IncludeKind = 2;
1434 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001435
1436 case tok::pp___include_macros:
1437 IncludeKind = 3;
1438 break;
1439
1440 default:
1441 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001442 }
1443
Douglas Gregor2537a362011-12-08 17:01:29 +00001444 // Determine whether we are actually building the module that this
1445 // include directive maps to.
1446 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001447 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001448
David Blaikiebbafb8a2012-03-11 07:00:24 +00001449 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001450 // If we're not building the imported module, warn that we're going
1451 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001452 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001453 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1454 /*IsTokenRange=*/false);
1455 Diag(HashLoc, diag::warn_auto_module_import)
1456 << IncludeKind << PathString
1457 << FixItHint::CreateReplacement(ReplaceRange,
Ted Kremenekc1e4dd02012-03-01 22:07:04 +00001458 "@__experimental_modules_import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001459 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001460
Douglas Gregor71944202011-11-30 00:36:36 +00001461 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001462 // If this was an #__include_macros directive, only make macros visible.
1463 Module::NameVisibilityKind Visibility
1464 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor98a52db2011-12-20 00:28:52 +00001465 Module *Imported
1466 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1467 /*IsIncludeDirective=*/true);
Douglas Gregor2537a362011-12-08 17:01:29 +00001468
1469 // If this header isn't part of the module we're building, we're done.
Douglas Gregor98a52db2011-12-20 00:28:52 +00001470 if (!BuildingImportedModule && Imported)
Douglas Gregor2537a362011-12-08 17:01:29 +00001471 return;
Douglas Gregor97eec242011-09-15 22:00:41 +00001472 }
1473
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001474 // The #included file will be considered to be a system header if either it is
1475 // in a system include directory, or if the #includer is a system include
1476 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001477 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001478 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001479 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001480
Chris Lattner72286d62010-04-19 20:44:31 +00001481 // Ask HeaderInfo if we should enter this #include file. If not, #including
1482 // this file will have no effect.
1483 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001484 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001485 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001486 return;
1487 }
1488
Chris Lattnerf64b3522008-03-09 01:54:53 +00001489 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001490 SourceLocation IncludePos = End;
1491 // If the filename string was the result of macro expansions, set the include
1492 // position on the file where it will be included and after the expansions.
1493 if (IncludePos.isMacroID())
1494 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1495 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001496 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001497
1498 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001499 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001500}
1501
James Dennettf6333ac2012-06-22 05:46:07 +00001502/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001503///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001504void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1505 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001506 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001507
Chris Lattnerf64b3522008-03-09 01:54:53 +00001508 // #include_next is like #include, except that we start searching after
1509 // the current found directory. If we can't do this, issue a
1510 // diagnostic.
1511 const DirectoryLookup *Lookup = CurDirLookup;
1512 if (isInPrimaryFile()) {
1513 Lookup = 0;
1514 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1515 } else if (Lookup == 0) {
1516 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1517 } else {
1518 // Start looking up in the next directory.
1519 ++Lookup;
1520 }
Mike Stump11289f42009-09-09 15:08:12 +00001521
Douglas Gregor796d76a2010-10-20 22:00:55 +00001522 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001523}
1524
James Dennettf6333ac2012-06-22 05:46:07 +00001525/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001526void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1527 // The Microsoft #import directive takes a type library and generates header
1528 // files from it, and includes those. This is beyond the scope of what clang
1529 // does, so we ignore it and error out. However, #import can optionally have
1530 // trailing attributes that span multiple lines. We're going to eat those
1531 // so we can continue processing from there.
1532 Diag(Tok, diag::err_pp_import_directive_ms );
1533
1534 // Read tokens until we get to the end of the directive. Note that the
1535 // directive can be split over multiple lines using the backslash character.
1536 DiscardUntilEndOfDirective();
1537}
1538
James Dennettf6333ac2012-06-22 05:46:07 +00001539/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001540///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001541void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1542 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001543 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1544 if (LangOpts.MicrosoftMode)
1545 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001546 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001547 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001548 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001549}
1550
Chris Lattner58a1eb02009-04-08 18:46:40 +00001551/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1552/// pseudo directive in the predefines buffer. This handles it by sucking all
1553/// tokens through the preprocessor and discarding them (only keeping the side
1554/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001555void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1556 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001557 // This directive should only occur in the predefines buffer. If not, emit an
1558 // error and reject it.
1559 SourceLocation Loc = IncludeMacrosTok.getLocation();
1560 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1561 Diag(IncludeMacrosTok.getLocation(),
1562 diag::pp_include_macros_out_of_predefines);
1563 DiscardUntilEndOfDirective();
1564 return;
1565 }
Mike Stump11289f42009-09-09 15:08:12 +00001566
Chris Lattnere01d82b2009-04-08 20:53:24 +00001567 // Treat this as a normal #include for checking purposes. If this is
1568 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001569 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001570
Chris Lattnere01d82b2009-04-08 20:53:24 +00001571 Token TmpTok;
1572 do {
1573 Lex(TmpTok);
1574 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1575 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001576}
1577
Chris Lattnerf64b3522008-03-09 01:54:53 +00001578//===----------------------------------------------------------------------===//
1579// Preprocessor Macro Directive Handling.
1580//===----------------------------------------------------------------------===//
1581
1582/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1583/// definition has just been read. Lex the rest of the arguments and the
1584/// closing ), updating MI with what we learn. Return true if an error occurs
1585/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001586bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001587 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001588
Chris Lattnerf64b3522008-03-09 01:54:53 +00001589 while (1) {
1590 LexUnexpandedToken(Tok);
1591 switch (Tok.getKind()) {
1592 case tok::r_paren:
1593 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001594 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001595 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001596 // Otherwise we have #define FOO(A,)
1597 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1598 return true;
1599 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001600 if (!LangOpts.C99)
1601 Diag(Tok, LangOpts.CPlusPlus0x ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001602 diag::warn_cxx98_compat_variadic_macro :
1603 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001604
1605 // Lex the token after the identifier.
1606 LexUnexpandedToken(Tok);
1607 if (Tok.isNot(tok::r_paren)) {
1608 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1609 return true;
1610 }
1611 // Add the __VA_ARGS__ identifier as an argument.
1612 Arguments.push_back(Ident__VA_ARGS__);
1613 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001614 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001615 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001616 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001617 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1618 return true;
1619 default:
1620 // Handle keywords and identifiers here to accept things like
1621 // #define Foo(for) for.
1622 IdentifierInfo *II = Tok.getIdentifierInfo();
1623 if (II == 0) {
1624 // #define X(1
1625 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1626 return true;
1627 }
1628
1629 // If this is already used as an argument, it is used multiple times (e.g.
1630 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001631 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001632 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001633 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001634 return true;
1635 }
Mike Stump11289f42009-09-09 15:08:12 +00001636
Chris Lattnerf64b3522008-03-09 01:54:53 +00001637 // Add the argument to the macro info.
1638 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001639
Chris Lattnerf64b3522008-03-09 01:54:53 +00001640 // Lex the token after the identifier.
1641 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001642
Chris Lattnerf64b3522008-03-09 01:54:53 +00001643 switch (Tok.getKind()) {
1644 default: // #define X(A B
1645 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1646 return true;
1647 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001648 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001649 return false;
1650 case tok::comma: // #define X(A,
1651 break;
1652 case tok::ellipsis: // #define X(A... -> GCC extension
1653 // Diagnose extension.
1654 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001655
Chris Lattnerf64b3522008-03-09 01:54:53 +00001656 // Lex the token after the identifier.
1657 LexUnexpandedToken(Tok);
1658 if (Tok.isNot(tok::r_paren)) {
1659 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1660 return true;
1661 }
Mike Stump11289f42009-09-09 15:08:12 +00001662
Chris Lattnerf64b3522008-03-09 01:54:53 +00001663 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001664 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001665 return false;
1666 }
1667 }
1668 }
1669}
1670
James Dennettf6333ac2012-06-22 05:46:07 +00001671/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001672/// line then lets the caller lex the next real token.
1673void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1674 ++NumDefined;
1675
1676 Token MacroNameTok;
1677 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001678
Chris Lattnerf64b3522008-03-09 01:54:53 +00001679 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001680 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001681 return;
1682
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001683 Token LastTok = MacroNameTok;
1684
Chris Lattnerf64b3522008-03-09 01:54:53 +00001685 // If we are supposed to keep comments in #defines, reenable comment saving
1686 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001687 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001688
Chris Lattnerf64b3522008-03-09 01:54:53 +00001689 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001690 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001691
Chris Lattnerf64b3522008-03-09 01:54:53 +00001692 Token Tok;
1693 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001694
Chris Lattnerf64b3522008-03-09 01:54:53 +00001695 // If this is a function-like macro definition, parse the argument list,
1696 // marking each of the identifiers as being used as macro arguments. Also,
1697 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001698 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001699 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001700 } else if (Tok.hasLeadingSpace()) {
1701 // This is a normal token with leading space. Clear the leading space
1702 // marker on the first token to get proper expansion.
1703 Tok.clearFlag(Token::LeadingSpace);
1704 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001705 // This is a function-like macro definition. Read the argument list.
1706 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001707 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001708 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001709 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001710 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001711 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001712 DiscardUntilEndOfDirective();
1713 return;
1714 }
1715
Chris Lattner249c38b2009-04-19 18:26:34 +00001716 // If this is a definition of a variadic C99 function-like macro, not using
1717 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001718
Chris Lattner249c38b2009-04-19 18:26:34 +00001719 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1720 // This gets unpoisoned where it is allowed.
1721 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1722 if (MI->isC99Varargs())
1723 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001724
Chris Lattnerf64b3522008-03-09 01:54:53 +00001725 // Read the first token after the arg list for down below.
1726 LexUnexpandedToken(Tok);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001727 } else if (LangOpts.C99 || LangOpts.CPlusPlus0x) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001728 // C99 requires whitespace between the macro definition and the body. Emit
1729 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001730 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001731 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001732 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1733 // first character of a replacement list is not a character required by
1734 // subclause 5.2.1, then there shall be white-space separation between the
1735 // identifier and the replacement list.". 5.2.1 lists this set:
1736 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1737 // is irrelevant here.
1738 bool isInvalid = false;
1739 if (Tok.is(tok::at)) // @ is not in the list above.
1740 isInvalid = true;
1741 else if (Tok.is(tok::unknown)) {
1742 // If we have an unknown token, it is something strange like "`". Since
1743 // all of valid characters would have lexed into a single character
1744 // token of some sort, we know this is not a valid case.
1745 isInvalid = true;
1746 }
1747 if (isInvalid)
1748 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1749 else
1750 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001751 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001752
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001753 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001754 LastTok = Tok;
1755
Chris Lattnerf64b3522008-03-09 01:54:53 +00001756 // Read the rest of the macro body.
1757 if (MI->isObjectLike()) {
1758 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001759 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001760 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001761 MI->AddTokenToBody(Tok);
1762 // Get the next token of the macro.
1763 LexUnexpandedToken(Tok);
1764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765
Chris Lattnerf64b3522008-03-09 01:54:53 +00001766 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001767 // Otherwise, read the body of a function-like macro. While we are at it,
1768 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1769 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001770 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001771 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001772
Chris Lattnerf64b3522008-03-09 01:54:53 +00001773 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001774 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Chris Lattnerf64b3522008-03-09 01:54:53 +00001776 // Get the next token of the macro.
1777 LexUnexpandedToken(Tok);
1778 continue;
1779 }
Mike Stump11289f42009-09-09 15:08:12 +00001780
Chris Lattnerf64b3522008-03-09 01:54:53 +00001781 // Get the next token of the macro.
1782 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001783
Chris Lattner83bd8282009-05-25 17:16:10 +00001784 // Check for a valid macro arg identifier.
1785 if (Tok.getIdentifierInfo() == 0 ||
1786 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1787
1788 // If this is assembler-with-cpp mode, we accept random gibberish after
1789 // the '#' because '#' is often a comment character. However, change
1790 // the kind of the token to tok::unknown so that the preprocessor isn't
1791 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001792 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001793 LastTok.setKind(tok::unknown);
1794 } else {
1795 Diag(Tok, diag::err_pp_stringize_not_parameter);
1796 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001797
Chris Lattner83bd8282009-05-25 17:16:10 +00001798 // Disable __VA_ARGS__ again.
1799 Ident__VA_ARGS__->setIsPoisoned(true);
1800 return;
1801 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001802 }
Mike Stump11289f42009-09-09 15:08:12 +00001803
Chris Lattner83bd8282009-05-25 17:16:10 +00001804 // Things look ok, add the '#' and param name tokens to the macro.
1805 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001806 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001807 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001808
Chris Lattnerf64b3522008-03-09 01:54:53 +00001809 // Get the next token of the macro.
1810 LexUnexpandedToken(Tok);
1811 }
1812 }
Mike Stump11289f42009-09-09 15:08:12 +00001813
1814
Chris Lattnerf64b3522008-03-09 01:54:53 +00001815 // Disable __VA_ARGS__ again.
1816 Ident__VA_ARGS__->setIsPoisoned(true);
1817
Chris Lattner57540c52011-04-15 05:22:18 +00001818 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001819 // replacement list.
1820 unsigned NumTokens = MI->getNumTokens();
1821 if (NumTokens != 0) {
1822 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1823 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001824 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001825 return;
1826 }
1827 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1828 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001829 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001830 return;
1831 }
1832 }
Mike Stump11289f42009-09-09 15:08:12 +00001833
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001834 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001835
Chris Lattnerf64b3522008-03-09 01:54:53 +00001836 // Finally, if this identifier already had a macro defined for it, verify that
1837 // the macro bodies are identical and free the old definition.
1838 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001839 // It is very common for system headers to have tons of macro redefinitions
1840 // and for warnings to be disabled in system headers. If this is the case,
1841 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001842 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001843 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001844 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001845 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001846
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001847 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001848 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001849 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001850 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001851 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1852 << MacroNameTok.getIdentifierInfo();
1853 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1854 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001855 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001856 if (OtherMI->isWarnIfUnused())
1857 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001858 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001859 }
Mike Stump11289f42009-09-09 15:08:12 +00001860
Chris Lattnerf64b3522008-03-09 01:54:53 +00001861 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001862
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001863 assert(!MI->isUsed());
1864 // If we need warning for not using the macro, add its location in the
1865 // warn-because-unused-macro set. If it gets used it will be removed from set.
1866 if (isInPrimaryFile() && // don't warn for include'd macros.
1867 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00001868 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001869 MI->setIsWarnIfUnused(true);
1870 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1871 }
1872
Chris Lattner928e9092009-04-12 01:39:54 +00001873 // If the callbacks want to know, tell them about the macro definition.
1874 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001875 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001876}
1877
James Dennettf6333ac2012-06-22 05:46:07 +00001878/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001879///
1880void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1881 ++NumUndefined;
1882
1883 Token MacroNameTok;
1884 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001885
Chris Lattnerf64b3522008-03-09 01:54:53 +00001886 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001887 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001888 return;
Mike Stump11289f42009-09-09 15:08:12 +00001889
Chris Lattnerf64b3522008-03-09 01:54:53 +00001890 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001891 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001892
Chris Lattnerf64b3522008-03-09 01:54:53 +00001893 // Okay, we finally have a valid identifier to undef.
1894 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001895
Chris Lattnerf64b3522008-03-09 01:54:53 +00001896 // If the macro is not defined, this is a noop undef, just return.
1897 if (MI == 0) return;
1898
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00001899 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00001900 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001901
1902 // If the callbacks want to know, tell them about the macro #undef.
1903 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001904 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001905
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001906 if (MI->isWarnIfUnused())
1907 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1908
Chris Lattnerf64b3522008-03-09 01:54:53 +00001909 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001910 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001911 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1912}
1913
1914
1915//===----------------------------------------------------------------------===//
1916// Preprocessor Conditional Directive Handling.
1917//===----------------------------------------------------------------------===//
1918
James Dennettf6333ac2012-06-22 05:46:07 +00001919/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
1920/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
1921/// true if any tokens have been returned or pp-directives activated before this
1922/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001923///
1924void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1925 bool ReadAnyTokensBeforeDirective) {
1926 ++NumIf;
1927 Token DirectiveTok = Result;
1928
1929 Token MacroNameTok;
1930 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001931
Chris Lattnerf64b3522008-03-09 01:54:53 +00001932 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001933 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001934 // Skip code until we get to #endif. This helps with recovery by not
1935 // emitting an error when the #endif is reached.
1936 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1937 /*Foundnonskip*/false, /*FoundElse*/false);
1938 return;
1939 }
Mike Stump11289f42009-09-09 15:08:12 +00001940
Chris Lattnerf64b3522008-03-09 01:54:53 +00001941 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001942 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001943
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001944 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1945 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001946
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001947 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001948 // If the start of a top-level #ifdef and if the macro is not defined,
1949 // inform MIOpt that this might be the start of a proper include guard.
1950 // Otherwise it is some other form of unknown conditional which we can't
1951 // handle.
1952 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001953 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001954 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001955 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001956 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001957 }
1958
Chris Lattnerf64b3522008-03-09 01:54:53 +00001959 // If there is a macro, process it.
1960 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001961 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001962
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00001963 if (Callbacks) {
1964 if (isIfndef)
1965 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok);
1966 else
1967 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok);
1968 }
1969
Chris Lattnerf64b3522008-03-09 01:54:53 +00001970 // Should we include the stuff contained by this directive?
1971 if (!MI == isIfndef) {
1972 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001973 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1974 /*wasskip*/false, /*foundnonskip*/true,
1975 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001976 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001977 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001978 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001979 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001980 /*FoundElse*/false);
1981 }
1982}
1983
James Dennettf6333ac2012-06-22 05:46:07 +00001984/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001985///
1986void Preprocessor::HandleIfDirective(Token &IfToken,
1987 bool ReadAnyTokensBeforeDirective) {
1988 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001989
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001990 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001991 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001992 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1993 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1994 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001995
1996 // If this condition is equivalent to #ifndef X, and if this is the first
1997 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001998 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001999 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002000 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00002001 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002002 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002003 }
2004
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002005 if (Callbacks)
2006 Callbacks->If(IfToken.getLocation(),
2007 SourceRange(ConditionalBegin, ConditionalEnd));
2008
Chris Lattnerf64b3522008-03-09 01:54:53 +00002009 // Should we include the stuff contained by this directive?
2010 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002011 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002012 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002013 /*foundnonskip*/true, /*foundelse*/false);
2014 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002015 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002016 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002017 /*FoundElse*/false);
2018 }
2019}
2020
James Dennettf6333ac2012-06-22 05:46:07 +00002021/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002022///
2023void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2024 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002025
Chris Lattnerf64b3522008-03-09 01:54:53 +00002026 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002027 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002028
Chris Lattnerf64b3522008-03-09 01:54:53 +00002029 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002030 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002031 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002032 Diag(EndifToken, diag::err_pp_endif_without_if);
2033 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035
Chris Lattnerf64b3522008-03-09 01:54:53 +00002036 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002037 if (CurPPLexer->getConditionalStackDepth() == 0)
2038 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002039
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002040 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002041 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002042
2043 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002044 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002045}
2046
James Dennettf6333ac2012-06-22 05:46:07 +00002047/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002048///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002049void Preprocessor::HandleElseDirective(Token &Result) {
2050 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002051
Chris Lattnerf64b3522008-03-09 01:54:53 +00002052 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002053 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002054
Chris Lattnerf64b3522008-03-09 01:54:53 +00002055 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002056 if (CurPPLexer->popConditionalLevel(CI)) {
2057 Diag(Result, diag::pp_err_else_without_if);
2058 return;
2059 }
Mike Stump11289f42009-09-09 15:08:12 +00002060
Chris Lattnerf64b3522008-03-09 01:54:53 +00002061 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002062 if (CurPPLexer->getConditionalStackDepth() == 0)
2063 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002064
2065 // If this is a #else with a #else before it, report the error.
2066 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002067
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002068 if (Callbacks)
2069 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2070
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002071 // Finally, skip the rest of the contents of this block.
2072 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002073 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002074}
2075
James Dennettf6333ac2012-06-22 05:46:07 +00002076/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002077///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002078void Preprocessor::HandleElifDirective(Token &ElifToken) {
2079 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002080
Chris Lattnerf64b3522008-03-09 01:54:53 +00002081 // #elif directive in a non-skipping conditional... start skipping.
2082 // We don't care what the condition is, because we will always skip it (since
2083 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002084 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002085 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002086 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002087
2088 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002089 if (CurPPLexer->popConditionalLevel(CI)) {
2090 Diag(ElifToken, diag::pp_err_elif_without_if);
2091 return;
2092 }
Mike Stump11289f42009-09-09 15:08:12 +00002093
Chris Lattnerf64b3522008-03-09 01:54:53 +00002094 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002095 if (CurPPLexer->getConditionalStackDepth() == 0)
2096 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002097
Chris Lattnerf64b3522008-03-09 01:54:53 +00002098 // If this is a #elif with a #else before it, report the error.
2099 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002100
2101 if (Callbacks)
2102 Callbacks->Elif(ElifToken.getLocation(),
2103 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002104
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002105 // Finally, skip the rest of the contents of this block.
2106 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002107 /*FoundElse*/CI.FoundElse,
2108 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002109}