blob: b12eb81e6be434543450e4e8ffb592db42f302cb [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 Smithd0124572012-06-21 00:35:03 +0000332 CheckEndOfDirective("endif");
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000333 if (Callbacks)
334 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000335 break;
Richard Smithd0124572012-06-21 00:35:03 +0000336 } else {
337 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000338 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000339 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000340 // #else directive in a skipping conditional. If not in some other
341 // skipping conditional, and if #else hasn't already been seen, enter it
342 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000343 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000344
Chris Lattnerf64b3522008-03-09 01:54:53 +0000345 // If this is a #else with a #else before it, report the error.
346 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000347
Chris Lattnerf64b3522008-03-09 01:54:53 +0000348 // Note that we've seen a #else in this conditional.
349 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000350
Chris Lattnerf64b3522008-03-09 01:54:53 +0000351 // If the conditional is at the top level, and the #if block wasn't
352 // entered, enter the #else block now.
353 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
354 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000355 CheckEndOfDirective("else");
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000356 if (Callbacks)
357 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000358 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000359 } else {
360 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000361 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000362 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000363 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000364
365 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000366 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000367 // If this is in a skipping block or if we're already handled this #if
368 // block, don't bother parsing the condition.
369 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
370 DiscardUntilEndOfDirective();
371 ShouldEnter = false;
372 } else {
373 // Restore the value of LexingRawMode so that identifiers are
374 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000375 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
376 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000377 IdentifierInfo *IfNDefMacro = 0;
378 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000379 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000380 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000381 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattnerf64b3522008-03-09 01:54:53 +0000383 // If this is a #elif with a #else before it, report the error.
384 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 // If this condition is true, enter it!
387 if (ShouldEnter) {
388 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000389 if (Callbacks)
390 Callbacks->Elif(Tok.getLocation(),
391 SourceRange(ConditionalBegin, ConditionalEnd),
392 CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000393 break;
394 }
395 }
396 }
Mike Stump11289f42009-09-09 15:08:12 +0000397
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000398 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000399 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000400 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000401 }
402
403 // Finally, if we are out of the conditional (saw an #endif or ran off the end
404 // of the file, just stop skipping and return to lexing whatever came after
405 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000406 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000407
408 if (Callbacks) {
409 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
410 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
411 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000412}
413
Ted Kremenek56572ab2008-12-12 18:34:08 +0000414void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000415
416 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000417 assert(CurPTHLexer);
418 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000419
Ted Kremenek56572ab2008-12-12 18:34:08 +0000420 // Skip to the next '#else', '#elif', or #endif.
421 if (CurPTHLexer->SkipBlock()) {
422 // We have reached an #endif. Both the '#' and 'endif' tokens
423 // have been consumed by the PTHLexer. Just pop off the condition level.
424 PPConditionalInfo CondInfo;
425 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000426 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000427 assert(!InCond && "Can't be skipping if not in a conditional!");
428 break;
429 }
Mike Stump11289f42009-09-09 15:08:12 +0000430
Ted Kremenek56572ab2008-12-12 18:34:08 +0000431 // We have reached a '#else' or '#elif'. Lex the next token to get
432 // the directive flavor.
433 Token Tok;
434 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000435
Ted Kremenek56572ab2008-12-12 18:34:08 +0000436 // We can actually look up the IdentifierInfo here since we aren't in
437 // raw mode.
438 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
439
440 if (K == tok::pp_else) {
441 // #else: Enter the else condition. We aren't in a nested condition
442 // since we skip those. We're always in the one matching the last
443 // blocked we skipped.
444 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
445 // Note that we've seen a #else in this conditional.
446 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000447
Ted Kremenek56572ab2008-12-12 18:34:08 +0000448 // If the #if block wasn't entered then enter the #else block now.
449 if (!CondInfo.FoundNonSkip) {
450 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000451
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000452 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000453 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000454 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000455 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000456
Ted Kremenek56572ab2008-12-12 18:34:08 +0000457 break;
458 }
Mike Stump11289f42009-09-09 15:08:12 +0000459
Ted Kremenek56572ab2008-12-12 18:34:08 +0000460 // Otherwise skip this block.
461 continue;
462 }
Mike Stump11289f42009-09-09 15:08:12 +0000463
Ted Kremenek56572ab2008-12-12 18:34:08 +0000464 assert(K == tok::pp_elif);
465 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
466
467 // If this is a #elif with a #else before it, report the error.
468 if (CondInfo.FoundElse)
469 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000470
Ted Kremenek56572ab2008-12-12 18:34:08 +0000471 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000472 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000473 if (CondInfo.FoundNonSkip)
474 continue;
475
476 // Evaluate the condition of the #elif.
477 IdentifierInfo *IfNDefMacro = 0;
478 CurPTHLexer->ParsingPreprocessorDirective = true;
479 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
480 CurPTHLexer->ParsingPreprocessorDirective = false;
481
482 // If this condition is true, enter it!
483 if (ShouldEnter) {
484 CondInfo.FoundNonSkip = true;
485 break;
486 }
487
488 // Otherwise, skip this block and go to the next one.
489 continue;
490 }
491}
492
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000493const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000494 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000495 bool isAngled,
496 const DirectoryLookup *FromDir,
497 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000499 SmallVectorImpl<char> *RelativePath,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000500 Module **SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000501 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000502 // If the header lookup mechanism may be relative to the current file, pass in
503 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000504 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000505 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000506 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000507 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattner022923a2009-02-04 19:45:07 +0000509 // If there is no file entry associated with this file, it must be the
510 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000511 // it won't be scanned for preprocessor directives. If we have the
512 // predefines buffer, resolve #include references (which come from the
513 // -include command line argument) as if they came from the main file, this
514 // affects file lookup etc.
515 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000516 FID = SourceMgr.getMainFileID();
517 CurFileEnt = SourceMgr.getFileEntryForID(FID);
518 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000519 }
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000521 // Do a standard file entry lookup.
522 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000523 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000524 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000525 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerfde85352010-01-22 00:14:44 +0000526 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000528 // Otherwise, see if this is a subframework header. If so, this is relative
529 // to one of the headers on the #include stack. Walk the list of the current
530 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregor97eec242011-09-15 22:00:41 +0000531 // FIXME: SuggestedModule!
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000532 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000533 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000534 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000535 SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000536 return FE;
537 }
Mike Stump11289f42009-09-09 15:08:12 +0000538
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000539 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
540 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000541 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000542 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000543 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000544 if ((FE = HeaderInfo.LookupSubframeworkHeader(
545 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000546 return FE;
547 }
548 }
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000550 // Otherwise, we really couldn't find the file.
551 return 0;
552}
553
Chris Lattnerf64b3522008-03-09 01:54:53 +0000554
555//===----------------------------------------------------------------------===//
556// Preprocessor Directive Handling.
557//===----------------------------------------------------------------------===//
558
David Blaikied5321242012-06-06 18:52:13 +0000559class Preprocessor::ResetMacroExpansionHelper {
560public:
561 ResetMacroExpansionHelper(Preprocessor *pp)
562 : PP(pp), save(pp->DisableMacroExpansion) {
563 if (pp->MacroExpansionInDirectivesOverride)
564 pp->DisableMacroExpansion = false;
565 }
566 ~ResetMacroExpansionHelper() {
567 PP->DisableMacroExpansion = save;
568 }
569private:
570 Preprocessor *PP;
571 bool save;
572};
573
Chris Lattnerf64b3522008-03-09 01:54:53 +0000574/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000575/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000576/// lexer/preprocessor state, and advances the lexer(s) so that the next token
577/// read is the correct one.
578void Preprocessor::HandleDirective(Token &Result) {
579 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000580
Chris Lattnerf64b3522008-03-09 01:54:53 +0000581 // We just parsed a # character at the start of a line, so we're in directive
582 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000583 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000584 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000585
Chris Lattnerf64b3522008-03-09 01:54:53 +0000586 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000587
Chris Lattnerf64b3522008-03-09 01:54:53 +0000588 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000589 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000590 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000591 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000592
Chris Lattner2d17ab72009-03-18 21:00:25 +0000593 // Save the '#' token in case we need to return it later.
594 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000595
Chris Lattnerf64b3522008-03-09 01:54:53 +0000596 // Read the next token, the directive flavor. This isn't expanded due to
597 // C99 6.10.3p8.
598 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000599
Chris Lattnerf64b3522008-03-09 01:54:53 +0000600 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
601 // #define A(x) #x
602 // A(abc
603 // #warning blah
604 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000605 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
606 // not support this for #include-like directives, since that can result in
607 // terrible diagnostics, and does not work in GCC.
608 if (InMacroArgs) {
609 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
610 switch (II->getPPKeywordID()) {
611 case tok::pp_include:
612 case tok::pp_import:
613 case tok::pp_include_next:
614 case tok::pp___include_macros:
615 Diag(Result, diag::err_embedded_include) << II->getName();
616 DiscardUntilEndOfDirective();
617 return;
618 default:
619 break;
620 }
621 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000622 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000623 }
Mike Stump11289f42009-09-09 15:08:12 +0000624
David Blaikied5321242012-06-06 18:52:13 +0000625 // Temporarily enable macro expansion if set so
626 // and reset to previous state when returning from this function.
627 ResetMacroExpansionHelper helper(this);
628
Chris Lattnerf64b3522008-03-09 01:54:53 +0000629TryAgain:
630 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000631 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000632 return; // null directive.
633 case tok::comment:
634 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
635 LexUnexpandedToken(Result);
636 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000637 case tok::code_completion:
638 if (CodeComplete)
639 CodeComplete->CodeCompleteDirective(
640 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000641 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000642 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000643 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000644 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000645 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000646 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000647 default:
648 IdentifierInfo *II = Result.getIdentifierInfo();
649 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000650
Chris Lattnerf64b3522008-03-09 01:54:53 +0000651 // Ask what the preprocessor keyword ID is.
652 switch (II->getPPKeywordID()) {
653 default: break;
654 // C99 6.10.1 - Conditional Inclusion.
655 case tok::pp_if:
656 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
657 case tok::pp_ifdef:
658 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
659 case tok::pp_ifndef:
660 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
661 case tok::pp_elif:
662 return HandleElifDirective(Result);
663 case tok::pp_else:
664 return HandleElseDirective(Result);
665 case tok::pp_endif:
666 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000667
Chris Lattnerf64b3522008-03-09 01:54:53 +0000668 // C99 6.10.2 - Source File Inclusion.
669 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000670 // Handle #include.
671 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000672 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000673 // Handle -imacros.
674 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000675
Chris Lattnerf64b3522008-03-09 01:54:53 +0000676 // C99 6.10.3 - Macro Replacement.
677 case tok::pp_define:
678 return HandleDefineDirective(Result);
679 case tok::pp_undef:
680 return HandleUndefDirective(Result);
681
682 // C99 6.10.4 - Line Control.
683 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000684 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000685
Chris Lattnerf64b3522008-03-09 01:54:53 +0000686 // C99 6.10.5 - Error Directive.
687 case tok::pp_error:
688 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000689
Chris Lattnerf64b3522008-03-09 01:54:53 +0000690 // C99 6.10.6 - Pragma Directive.
691 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000692 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000693
Chris Lattnerf64b3522008-03-09 01:54:53 +0000694 // GNU Extensions.
695 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000696 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000697 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000698 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattnerf64b3522008-03-09 01:54:53 +0000700 case tok::pp_warning:
701 Diag(Result, diag::ext_pp_warning_directive);
702 return HandleUserDiagnosticDirective(Result, true);
703 case tok::pp_ident:
704 return HandleIdentSCCSDirective(Result);
705 case tok::pp_sccs:
706 return HandleIdentSCCSDirective(Result);
707 case tok::pp_assert:
708 //isExtension = true; // FIXME: implement #assert
709 break;
710 case tok::pp_unassert:
711 //isExtension = true; // FIXME: implement #unassert
712 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000713
Douglas Gregor663b48f2012-01-03 19:48:16 +0000714 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000715 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000716 return HandleMacroPublicDirective(Result);
717 break;
718
Douglas Gregor663b48f2012-01-03 19:48:16 +0000719 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000720 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000721 return HandleMacroPrivateDirective(Result);
722 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000723 }
724 break;
725 }
Mike Stump11289f42009-09-09 15:08:12 +0000726
Chris Lattner2d17ab72009-03-18 21:00:25 +0000727 // If this is a .S file, treat unknown # directives as non-preprocessor
728 // directives. This is important because # may be a comment or introduce
729 // various pseudo-ops. Just return the # token and push back the following
730 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000731 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000732 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000733 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000734 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000735 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000736
737 // If the second token is a hashhash token, then we need to translate it to
738 // unknown so the token lexer doesn't try to perform token pasting.
739 if (Result.is(tok::hashhash))
740 Toks[1].setKind(tok::unknown);
741
Chris Lattner2d17ab72009-03-18 21:00:25 +0000742 // Enter this token stream so that we re-lex the tokens. Make sure to
743 // enable macro expansion, in case the token after the # is an identifier
744 // that is expanded.
745 EnterTokenStream(Toks, 2, false, true);
746 return;
747 }
Mike Stump11289f42009-09-09 15:08:12 +0000748
Chris Lattnerf64b3522008-03-09 01:54:53 +0000749 // If we reached here, the preprocessing token is not valid!
750 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000751
Chris Lattnerf64b3522008-03-09 01:54:53 +0000752 // Read the rest of the PP line.
753 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000754
Chris Lattnerf64b3522008-03-09 01:54:53 +0000755 // Okay, we're done parsing the directive.
756}
757
Chris Lattner76e68962009-01-26 06:19:46 +0000758/// GetLineValue - Convert a numeric token into an unsigned value, emitting
759/// Diagnostic DiagID if it is invalid, and returning the value in Val.
760static bool GetLineValue(Token &DigitTok, unsigned &Val,
761 unsigned DiagID, Preprocessor &PP) {
762 if (DigitTok.isNot(tok::numeric_constant)) {
763 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000764
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000765 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000766 PP.DiscardUntilEndOfDirective();
767 return true;
768 }
Mike Stump11289f42009-09-09 15:08:12 +0000769
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000770 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000771 IntegerBuffer.resize(DigitTok.getLength());
772 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000773 bool Invalid = false;
774 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
775 if (Invalid)
776 return true;
777
Chris Lattnerd66f1722009-04-18 18:35:15 +0000778 // Verify that we have a simple digit-sequence, and compute the value. This
779 // is always a simple digit string computed in decimal, so we do this manually
780 // here.
781 Val = 0;
782 for (unsigned i = 0; i != ActualLength; ++i) {
783 if (!isdigit(DigitTokBegin[i])) {
784 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
785 diag::err_pp_line_digit_sequence);
786 PP.DiscardUntilEndOfDirective();
787 return true;
788 }
Mike Stump11289f42009-09-09 15:08:12 +0000789
Chris Lattnerd66f1722009-04-18 18:35:15 +0000790 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
791 if (NextVal < Val) { // overflow.
792 PP.Diag(DigitTok, DiagID);
793 PP.DiscardUntilEndOfDirective();
794 return true;
795 }
796 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000797 }
Mike Stump11289f42009-09-09 15:08:12 +0000798
799 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000800 if (Val == 0) {
801 PP.Diag(DigitTok, DiagID);
802 PP.DiscardUntilEndOfDirective();
803 return true;
804 }
Mike Stump11289f42009-09-09 15:08:12 +0000805
Chris Lattnerd66f1722009-04-18 18:35:15 +0000806 if (DigitTokBegin[0] == '0')
807 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000808
Chris Lattner76e68962009-01-26 06:19:46 +0000809 return false;
810}
811
James Dennettf6333ac2012-06-22 05:46:07 +0000812/// \brief Handle a \#line directive: C99 6.10.4.
813///
814/// The two acceptable forms are:
815/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000816/// # line digit-sequence
817/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000818/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000819void Preprocessor::HandleLineDirective(Token &Tok) {
820 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
821 // expanded.
822 Token DigitTok;
823 Lex(DigitTok);
824
Chris Lattner100c65e2009-01-26 05:29:08 +0000825 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000826 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000827 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000828 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000829
Chris Lattner76e68962009-01-26 06:19:46 +0000830 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
831 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000832 unsigned LineLimit = 32768U;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000833 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
Eli Friedman192e0342011-10-10 23:35:28 +0000834 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000835 if (LineNo >= LineLimit)
836 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000837 else if (LangOpts.CPlusPlus0x && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000838 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000839
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000840 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000841 Token StrTok;
842 Lex(StrTok);
843
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000844 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
845 // string followed by eod.
846 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000847 ; // ok
848 else if (StrTok.isNot(tok::string_literal)) {
849 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000850 return DiscardUntilEndOfDirective();
851 } else if (StrTok.hasUDSuffix()) {
852 Diag(StrTok, diag::err_invalid_string_udl);
853 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000854 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000855 // Parse and validate the string, converting it into a unique ID.
856 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000857 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000858 if (Literal.hadError)
859 return DiscardUntilEndOfDirective();
860 if (Literal.Pascal) {
861 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
862 return DiscardUntilEndOfDirective();
863 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000864 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000865
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000866 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000867 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
868 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000869 }
Mike Stump11289f42009-09-09 15:08:12 +0000870
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000871 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000872
Chris Lattner839150e2009-03-27 17:13:49 +0000873 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000874 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
875 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000876 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000877}
878
Chris Lattner76e68962009-01-26 06:19:46 +0000879/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
880/// marker directive.
881static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
882 bool &IsSystemHeader, bool &IsExternCHeader,
883 Preprocessor &PP) {
884 unsigned FlagVal;
885 Token FlagTok;
886 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000887 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000888 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
889 return true;
890
891 if (FlagVal == 1) {
892 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000893
Chris Lattner76e68962009-01-26 06:19:46 +0000894 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 } else if (FlagVal == 2) {
899 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000900
Chris Lattner1c967782009-02-04 06:25:26 +0000901 SourceManager &SM = PP.getSourceManager();
902 // If we are leaving the current presumed file, check to make sure the
903 // presumed include stack isn't empty!
904 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000905 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000906 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000907 if (PLoc.isInvalid())
908 return true;
909
Chris Lattner1c967782009-02-04 06:25:26 +0000910 // If there is no include loc (main file) or if the include loc is in a
911 // different physical file, then we aren't in a "1" line marker flag region.
912 SourceLocation IncLoc = PLoc.getIncludeLoc();
913 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000914 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000915 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
916 PP.DiscardUntilEndOfDirective();
917 return true;
918 }
Mike Stump11289f42009-09-09 15:08:12 +0000919
Chris Lattner76e68962009-01-26 06:19:46 +0000920 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000921 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000922 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
923 return true;
924 }
925
926 // We must have 3 if there are still flags.
927 if (FlagVal != 3) {
928 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000929 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000930 return true;
931 }
Mike Stump11289f42009-09-09 15:08:12 +0000932
Chris Lattner76e68962009-01-26 06:19:46 +0000933 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000934
Chris Lattner76e68962009-01-26 06:19:46 +0000935 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000936 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000937 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000938 return true;
939
940 // We must have 4 if there is yet another flag.
941 if (FlagVal != 4) {
942 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000943 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000944 return true;
945 }
Mike Stump11289f42009-09-09 15:08:12 +0000946
Chris Lattner76e68962009-01-26 06:19:46 +0000947 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000948
Chris Lattner76e68962009-01-26 06:19:46 +0000949 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000950 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000951
952 // There are no more valid flags here.
953 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000954 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000955 return true;
956}
957
958/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
959/// one of the following forms:
960///
961/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000962/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000963/// # 42 "file" ('1' | '2')? '3' '4'?
964///
965void Preprocessor::HandleDigitDirective(Token &DigitTok) {
966 // Validate the number and convert it to an unsigned. GNU does not have a
967 // line # limit other than it fit in 32-bits.
968 unsigned LineNo;
969 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
970 *this))
971 return;
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattner76e68962009-01-26 06:19:46 +0000973 Token StrTok;
974 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Chris Lattner76e68962009-01-26 06:19:46 +0000976 bool IsFileEntry = false, IsFileExit = false;
977 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000978 int FilenameID = -1;
979
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000980 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
981 // string followed by eod.
982 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000983 ; // ok
984 else if (StrTok.isNot(tok::string_literal)) {
985 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000986 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +0000987 } else if (StrTok.hasUDSuffix()) {
988 Diag(StrTok, diag::err_invalid_string_udl);
989 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000990 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000991 // Parse and validate the string, converting it into a unique ID.
992 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000993 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000994 if (Literal.hadError)
995 return DiscardUntilEndOfDirective();
996 if (Literal.Pascal) {
997 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
998 return DiscardUntilEndOfDirective();
999 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001000 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001001
Chris Lattner76e68962009-01-26 06:19:46 +00001002 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001003 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001004 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001005 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001006 }
Mike Stump11289f42009-09-09 15:08:12 +00001007
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001008 // Create a line note with this information.
1009 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001010 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001011 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001012
Chris Lattner839150e2009-03-27 17:13:49 +00001013 // If the preprocessor has callbacks installed, notify them of the #line
1014 // change. This is used so that the line marker comes out in -E mode for
1015 // example.
1016 if (Callbacks) {
1017 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1018 if (IsFileEntry)
1019 Reason = PPCallbacks::EnterFile;
1020 else if (IsFileExit)
1021 Reason = PPCallbacks::ExitFile;
1022 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1023 if (IsExternCHeader)
1024 FileKind = SrcMgr::C_ExternCSystem;
1025 else if (IsSystemHeader)
1026 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001027
Chris Lattnerc745cec2010-04-14 04:28:50 +00001028 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001029 }
Chris Lattner76e68962009-01-26 06:19:46 +00001030}
1031
1032
Chris Lattner38d7fd22009-01-26 05:30:54 +00001033/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1034///
Mike Stump11289f42009-09-09 15:08:12 +00001035void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001036 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001037 // PTH doesn't emit #warning or #error directives.
1038 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001039 return CurPTHLexer->DiscardToEndOfLine();
1040
Chris Lattnerf64b3522008-03-09 01:54:53 +00001041 // Read the rest of the line raw. We do this because we don't want macros
1042 // to be expanded and we don't require that the tokens be valid preprocessing
1043 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1044 // collapse multiple consequtive white space between tokens, but this isn't
1045 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001046 SmallString<128> Message;
1047 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001048
1049 // Find the first non-whitespace character, so that we can make the
1050 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001051 StringRef Msg = Message.str().ltrim(" ");
1052
Chris Lattner100c65e2009-01-26 05:29:08 +00001053 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001054 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001055 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001056 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001057}
1058
1059/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1060///
1061void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1062 // Yes, this directive is an extension.
1063 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001064
Chris Lattnerf64b3522008-03-09 01:54:53 +00001065 // Read the string argument.
1066 Token StrTok;
1067 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001068
Chris Lattnerf64b3522008-03-09 01:54:53 +00001069 // If the token kind isn't a string, it's a malformed directive.
1070 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001071 StrTok.isNot(tok::wide_string_literal)) {
1072 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001073 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001074 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001075 return;
1076 }
Mike Stump11289f42009-09-09 15:08:12 +00001077
Richard Smithd67aea22012-03-06 03:21:47 +00001078 if (StrTok.hasUDSuffix()) {
1079 Diag(StrTok, diag::err_invalid_string_udl);
1080 return DiscardUntilEndOfDirective();
1081 }
1082
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001083 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001084 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001085
Douglas Gregordc970f02010-03-16 22:30:13 +00001086 if (Callbacks) {
1087 bool Invalid = false;
1088 std::string Str = getSpelling(StrTok, &Invalid);
1089 if (!Invalid)
1090 Callbacks->Ident(Tok.getLocation(), Str);
1091 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001092}
1093
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001094/// \brief Handle a #public directive.
1095void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001096 Token MacroNameTok;
1097 ReadMacroName(MacroNameTok, 2);
1098
1099 // Error reading macro name? If so, diagnostic already issued.
1100 if (MacroNameTok.is(tok::eod))
1101 return;
1102
Douglas Gregor663b48f2012-01-03 19:48:16 +00001103 // Check to see if this is the last token on the #__public_macro line.
1104 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001105
1106 // Okay, we finally have a valid identifier to undef.
1107 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1108
1109 // If the macro is not defined, this is an error.
1110 if (MI == 0) {
Douglas Gregorebf00492011-10-17 15:32:29 +00001111 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001112 << MacroNameTok.getIdentifierInfo();
1113 return;
1114 }
1115
1116 // Note that this macro has now been exported.
Douglas Gregorebf00492011-10-17 15:32:29 +00001117 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1118
1119 // If this macro definition came from a PCH file, mark it
1120 // as having changed since serialization.
1121 if (MI->isFromAST())
1122 MI->setChangedAfterLoad();
1123}
1124
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001125/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001126void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1127 Token MacroNameTok;
1128 ReadMacroName(MacroNameTok, 2);
1129
1130 // Error reading macro name? If so, diagnostic already issued.
1131 if (MacroNameTok.is(tok::eod))
1132 return;
1133
Douglas Gregor663b48f2012-01-03 19:48:16 +00001134 // Check to see if this is the last token on the #__private_macro line.
1135 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001136
1137 // Okay, we finally have a valid identifier to undef.
1138 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1139
1140 // If the macro is not defined, this is an error.
1141 if (MI == 0) {
1142 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1143 << MacroNameTok.getIdentifierInfo();
1144 return;
1145 }
1146
1147 // Note that this macro has now been marked private.
1148 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001149
1150 // If this macro definition came from a PCH file, mark it
1151 // as having changed since serialization.
1152 if (MI->isFromAST())
1153 MI->setChangedAfterLoad();
1154}
1155
Chris Lattnerf64b3522008-03-09 01:54:53 +00001156//===----------------------------------------------------------------------===//
1157// Preprocessor Include Directive Handling.
1158//===----------------------------------------------------------------------===//
1159
1160/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001161/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001162/// true if the input filename was in <>'s or false if it were in ""'s. The
1163/// caller is expected to provide a buffer that is large enough to hold the
1164/// spelling of the filename, but is also expected to handle the case when
1165/// this method decides to use a different buffer.
1166bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001167 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001168 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001169 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001170
Chris Lattnerf64b3522008-03-09 01:54:53 +00001171 // Make sure the filename is <x> or "x".
1172 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001173 if (Buffer[0] == '<') {
1174 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001175 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001176 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001177 return true;
1178 }
1179 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001180 } else if (Buffer[0] == '"') {
1181 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001182 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001183 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001184 return true;
1185 }
1186 isAngled = false;
1187 } else {
1188 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001189 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001190 return true;
1191 }
Mike Stump11289f42009-09-09 15:08:12 +00001192
Chris Lattnerf64b3522008-03-09 01:54:53 +00001193 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001194 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001195 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001196 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001197 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001198 }
Mike Stump11289f42009-09-09 15:08:12 +00001199
Chris Lattnerf64b3522008-03-09 01:54:53 +00001200 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001201 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001202 return isAngled;
1203}
1204
James Dennettf6333ac2012-06-22 05:46:07 +00001205/// \brief Handle cases where the \#include name is expanded from a macro
1206/// as multiple tokens, which need to be glued together.
1207///
1208/// This occurs for code like:
1209/// \code
1210/// \#define FOO <a/b.h>
1211/// \#include FOO
1212/// \endcode
Chris Lattnerf64b3522008-03-09 01:54:53 +00001213/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1214///
1215/// This code concatenates and consumes tokens up to the '>' token. It returns
1216/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001217/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001218bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001219 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001220 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001221 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001222
John Thompsonb5353522009-10-30 13:49:06 +00001223 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001224 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001225 End = CurTok.getLocation();
1226
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001227 // FIXME: Provide code completion for #includes.
1228 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001229 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001230 Lex(CurTok);
1231 continue;
1232 }
1233
Chris Lattnerf64b3522008-03-09 01:54:53 +00001234 // Append the spelling of this token to the buffer. If there was a space
1235 // before it, add it now.
1236 if (CurTok.hasLeadingSpace())
1237 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001238
Chris Lattnerf64b3522008-03-09 01:54:53 +00001239 // Get the spelling of the token, directly into FilenameBuffer if possible.
1240 unsigned PreAppendSize = FilenameBuffer.size();
1241 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001242
Chris Lattnerf64b3522008-03-09 01:54:53 +00001243 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001244 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001245
Chris Lattnerf64b3522008-03-09 01:54:53 +00001246 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1247 if (BufPtr != &FilenameBuffer[PreAppendSize])
1248 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001249
Chris Lattnerf64b3522008-03-09 01:54:53 +00001250 // Resize FilenameBuffer to the correct size.
1251 if (CurTok.getLength() != ActualLen)
1252 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001253
Chris Lattnerf64b3522008-03-09 01:54:53 +00001254 // If we found the '>' marker, return success.
1255 if (CurTok.is(tok::greater))
1256 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001257
John Thompsonb5353522009-10-30 13:49:06 +00001258 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001259 }
1260
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001261 // If we hit the eod marker, emit an error and return true so that the caller
1262 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001263 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001264 return true;
1265}
1266
James Dennettf6333ac2012-06-22 05:46:07 +00001267/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1268/// the file to be included from the lexer, then include it! This is a common
1269/// routine with functionality shared between \#include, \#include_next and
1270/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001271/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001272void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1273 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001274 const DirectoryLookup *LookupFrom,
1275 bool isImport) {
1276
1277 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001278 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001279
Chris Lattnerf64b3522008-03-09 01:54:53 +00001280 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001281 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001282 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001283 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001284 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001285
Chris Lattnerf64b3522008-03-09 01:54:53 +00001286 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001287 case tok::eod:
1288 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001289 return;
Mike Stump11289f42009-09-09 15:08:12 +00001290
Chris Lattnerf64b3522008-03-09 01:54:53 +00001291 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001292 case tok::string_literal:
1293 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001294 End = FilenameTok.getLocation();
Douglas Gregor41e115a2011-11-30 18:02:36 +00001295 CharEnd = End.getLocWithOffset(Filename.size());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001296 break;
Mike Stump11289f42009-09-09 15:08:12 +00001297
Chris Lattnerf64b3522008-03-09 01:54:53 +00001298 case tok::less:
1299 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1300 // case, glue the tokens together into FilenameBuffer and interpret those.
1301 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001302 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001303 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001304 Filename = FilenameBuffer.str();
Douglas Gregor41e115a2011-11-30 18:02:36 +00001305 CharEnd = getLocForEndOfToken(End);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001306 break;
1307 default:
1308 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1309 DiscardUntilEndOfDirective();
1310 return;
1311 }
Mike Stump11289f42009-09-09 15:08:12 +00001312
Aaron Ballman611306e2012-03-02 22:51:54 +00001313 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001314 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001315 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001316 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1317 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001318 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001319 DiscardUntilEndOfDirective();
1320 return;
1321 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001323 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001324 // we allow macros that expand to nothing after the filename, because this
1325 // falls into the category of "#include pp-tokens new-line" specified in
1326 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001327 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001328
1329 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001330 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1331 Diag(FilenameTok, diag::err_pp_include_too_deep);
1332 return;
1333 }
Mike Stump11289f42009-09-09 15:08:12 +00001334
John McCall32f5fe12011-09-30 05:12:12 +00001335 // Complain about attempts to #include files in an audit pragma.
1336 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1337 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1338 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1339
1340 // Immediately leave the pragma.
1341 PragmaARCCFCodeAuditedLoc = SourceLocation();
1342 }
1343
Aaron Ballman611306e2012-03-02 22:51:54 +00001344 if (HeaderInfo.HasIncludeAliasMap()) {
1345 // Map the filename with the brackets still attached. If the name doesn't
1346 // map to anything, fall back on the filename we've already gotten the
1347 // spelling for.
1348 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1349 if (!NewName.empty())
1350 Filename = NewName;
1351 }
1352
Chris Lattnerf64b3522008-03-09 01:54:53 +00001353 // Search include directories.
1354 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001355 SmallString<1024> SearchPath;
1356 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001357 // We get the raw path only if we have 'Callbacks' to which we later pass
1358 // the path.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001359 Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001360 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001361 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001362 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001363 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001364
Douglas Gregor11729f02011-11-30 18:12:06 +00001365 if (Callbacks) {
1366 if (!File) {
1367 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001368 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001369 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1370 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1371 // Add the recovery path to the list of search paths.
1372 DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
1373 HeaderInfo.AddSearchPath(DL, isAngled);
1374
1375 // Try the lookup again, skipping the cache.
1376 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001377 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001378 /*SkipCache*/true);
1379 }
1380 }
1381 }
1382
1383 // Notify the callback object that we've seen an inclusion directive.
1384 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1385 End, SearchPath, RelativePath);
1386 }
1387
1388 if (File == 0) {
1389 if (!SuppressIncludeNotFoundError)
1390 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1391 return;
1392 }
1393
Douglas Gregor97eec242011-09-15 22:00:41 +00001394 // If we are supposed to import a module rather than including the header,
1395 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001396 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001397 // Compute the module access path corresponding to this module.
1398 // FIXME: Should we have a second loadModule() overload to avoid this
1399 // extra lookup step?
1400 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregorde3ef502011-11-30 23:21:26 +00001401 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001402 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1403 FilenameTok.getLocation()));
1404 std::reverse(Path.begin(), Path.end());
1405
Douglas Gregor41e115a2011-11-30 18:02:36 +00001406 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001407 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001408 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1409 if (I)
1410 PathString += '.';
1411 PathString += Path[I].first->getName();
1412 }
1413 int IncludeKind = 0;
1414
1415 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1416 case tok::pp_include:
1417 IncludeKind = 0;
1418 break;
1419
1420 case tok::pp_import:
1421 IncludeKind = 1;
1422 break;
1423
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001424 case tok::pp_include_next:
1425 IncludeKind = 2;
1426 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001427
1428 case tok::pp___include_macros:
1429 IncludeKind = 3;
1430 break;
1431
1432 default:
1433 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001434 }
1435
Douglas Gregor2537a362011-12-08 17:01:29 +00001436 // Determine whether we are actually building the module that this
1437 // include directive maps to.
1438 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001439 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001440
David Blaikiebbafb8a2012-03-11 07:00:24 +00001441 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001442 // If we're not building the imported module, warn that we're going
1443 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001444 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001445 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1446 /*IsTokenRange=*/false);
1447 Diag(HashLoc, diag::warn_auto_module_import)
1448 << IncludeKind << PathString
1449 << FixItHint::CreateReplacement(ReplaceRange,
Ted Kremenekc1e4dd02012-03-01 22:07:04 +00001450 "@__experimental_modules_import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001451 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001452
Douglas Gregor71944202011-11-30 00:36:36 +00001453 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001454 // If this was an #__include_macros directive, only make macros visible.
1455 Module::NameVisibilityKind Visibility
1456 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor98a52db2011-12-20 00:28:52 +00001457 Module *Imported
1458 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1459 /*IsIncludeDirective=*/true);
Douglas Gregor2537a362011-12-08 17:01:29 +00001460
1461 // If this header isn't part of the module we're building, we're done.
Douglas Gregor98a52db2011-12-20 00:28:52 +00001462 if (!BuildingImportedModule && Imported)
Douglas Gregor2537a362011-12-08 17:01:29 +00001463 return;
Douglas Gregor97eec242011-09-15 22:00:41 +00001464 }
1465
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001466 // The #included file will be considered to be a system header if either it is
1467 // in a system include directory, or if the #includer is a system include
1468 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001469 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001470 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001471 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001472
Chris Lattner72286d62010-04-19 20:44:31 +00001473 // Ask HeaderInfo if we should enter this #include file. If not, #including
1474 // this file will have no effect.
1475 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001476 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001477 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001478 return;
1479 }
1480
Chris Lattnerf64b3522008-03-09 01:54:53 +00001481 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001482 SourceLocation IncludePos = End;
1483 // If the filename string was the result of macro expansions, set the include
1484 // position on the file where it will be included and after the expansions.
1485 if (IncludePos.isMacroID())
1486 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1487 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001488 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001489
1490 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001491 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001492}
1493
James Dennettf6333ac2012-06-22 05:46:07 +00001494/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001495///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001496void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1497 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001498 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001499
Chris Lattnerf64b3522008-03-09 01:54:53 +00001500 // #include_next is like #include, except that we start searching after
1501 // the current found directory. If we can't do this, issue a
1502 // diagnostic.
1503 const DirectoryLookup *Lookup = CurDirLookup;
1504 if (isInPrimaryFile()) {
1505 Lookup = 0;
1506 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1507 } else if (Lookup == 0) {
1508 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1509 } else {
1510 // Start looking up in the next directory.
1511 ++Lookup;
1512 }
Mike Stump11289f42009-09-09 15:08:12 +00001513
Douglas Gregor796d76a2010-10-20 22:00:55 +00001514 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001515}
1516
James Dennettf6333ac2012-06-22 05:46:07 +00001517/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001518void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1519 // The Microsoft #import directive takes a type library and generates header
1520 // files from it, and includes those. This is beyond the scope of what clang
1521 // does, so we ignore it and error out. However, #import can optionally have
1522 // trailing attributes that span multiple lines. We're going to eat those
1523 // so we can continue processing from there.
1524 Diag(Tok, diag::err_pp_import_directive_ms );
1525
1526 // Read tokens until we get to the end of the directive. Note that the
1527 // directive can be split over multiple lines using the backslash character.
1528 DiscardUntilEndOfDirective();
1529}
1530
James Dennettf6333ac2012-06-22 05:46:07 +00001531/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001532///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001533void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1534 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001535 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1536 if (LangOpts.MicrosoftMode)
1537 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001538 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001539 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001540 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001541}
1542
Chris Lattner58a1eb02009-04-08 18:46:40 +00001543/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1544/// pseudo directive in the predefines buffer. This handles it by sucking all
1545/// tokens through the preprocessor and discarding them (only keeping the side
1546/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001547void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1548 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001549 // This directive should only occur in the predefines buffer. If not, emit an
1550 // error and reject it.
1551 SourceLocation Loc = IncludeMacrosTok.getLocation();
1552 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1553 Diag(IncludeMacrosTok.getLocation(),
1554 diag::pp_include_macros_out_of_predefines);
1555 DiscardUntilEndOfDirective();
1556 return;
1557 }
Mike Stump11289f42009-09-09 15:08:12 +00001558
Chris Lattnere01d82b2009-04-08 20:53:24 +00001559 // Treat this as a normal #include for checking purposes. If this is
1560 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001561 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001562
Chris Lattnere01d82b2009-04-08 20:53:24 +00001563 Token TmpTok;
1564 do {
1565 Lex(TmpTok);
1566 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1567 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001568}
1569
Chris Lattnerf64b3522008-03-09 01:54:53 +00001570//===----------------------------------------------------------------------===//
1571// Preprocessor Macro Directive Handling.
1572//===----------------------------------------------------------------------===//
1573
1574/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1575/// definition has just been read. Lex the rest of the arguments and the
1576/// closing ), updating MI with what we learn. Return true if an error occurs
1577/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001578bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001579 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001580
Chris Lattnerf64b3522008-03-09 01:54:53 +00001581 while (1) {
1582 LexUnexpandedToken(Tok);
1583 switch (Tok.getKind()) {
1584 case tok::r_paren:
1585 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001586 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001587 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001588 // Otherwise we have #define FOO(A,)
1589 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1590 return true;
1591 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001592 if (!LangOpts.C99)
1593 Diag(Tok, LangOpts.CPlusPlus0x ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001594 diag::warn_cxx98_compat_variadic_macro :
1595 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001596
1597 // Lex the token after the identifier.
1598 LexUnexpandedToken(Tok);
1599 if (Tok.isNot(tok::r_paren)) {
1600 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1601 return true;
1602 }
1603 // Add the __VA_ARGS__ identifier as an argument.
1604 Arguments.push_back(Ident__VA_ARGS__);
1605 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001606 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001607 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001608 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001609 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1610 return true;
1611 default:
1612 // Handle keywords and identifiers here to accept things like
1613 // #define Foo(for) for.
1614 IdentifierInfo *II = Tok.getIdentifierInfo();
1615 if (II == 0) {
1616 // #define X(1
1617 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1618 return true;
1619 }
1620
1621 // If this is already used as an argument, it is used multiple times (e.g.
1622 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001623 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001624 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001625 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001626 return true;
1627 }
Mike Stump11289f42009-09-09 15:08:12 +00001628
Chris Lattnerf64b3522008-03-09 01:54:53 +00001629 // Add the argument to the macro info.
1630 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001631
Chris Lattnerf64b3522008-03-09 01:54:53 +00001632 // Lex the token after the identifier.
1633 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chris Lattnerf64b3522008-03-09 01:54:53 +00001635 switch (Tok.getKind()) {
1636 default: // #define X(A B
1637 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1638 return true;
1639 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001640 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001641 return false;
1642 case tok::comma: // #define X(A,
1643 break;
1644 case tok::ellipsis: // #define X(A... -> GCC extension
1645 // Diagnose extension.
1646 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001647
Chris Lattnerf64b3522008-03-09 01:54:53 +00001648 // Lex the token after the identifier.
1649 LexUnexpandedToken(Tok);
1650 if (Tok.isNot(tok::r_paren)) {
1651 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1652 return true;
1653 }
Mike Stump11289f42009-09-09 15:08:12 +00001654
Chris Lattnerf64b3522008-03-09 01:54:53 +00001655 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001656 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001657 return false;
1658 }
1659 }
1660 }
1661}
1662
James Dennettf6333ac2012-06-22 05:46:07 +00001663/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001664/// line then lets the caller lex the next real token.
1665void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1666 ++NumDefined;
1667
1668 Token MacroNameTok;
1669 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001670
Chris Lattnerf64b3522008-03-09 01:54:53 +00001671 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001672 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001673 return;
1674
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001675 Token LastTok = MacroNameTok;
1676
Chris Lattnerf64b3522008-03-09 01:54:53 +00001677 // If we are supposed to keep comments in #defines, reenable comment saving
1678 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001679 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattnerf64b3522008-03-09 01:54:53 +00001681 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001682 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001683
Chris Lattnerf64b3522008-03-09 01:54:53 +00001684 Token Tok;
1685 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001686
Chris Lattnerf64b3522008-03-09 01:54:53 +00001687 // If this is a function-like macro definition, parse the argument list,
1688 // marking each of the identifiers as being used as macro arguments. Also,
1689 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001690 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001691 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001692 } else if (Tok.hasLeadingSpace()) {
1693 // This is a normal token with leading space. Clear the leading space
1694 // marker on the first token to get proper expansion.
1695 Tok.clearFlag(Token::LeadingSpace);
1696 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001697 // This is a function-like macro definition. Read the argument list.
1698 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001699 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001700 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001701 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001702 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001703 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001704 DiscardUntilEndOfDirective();
1705 return;
1706 }
1707
Chris Lattner249c38b2009-04-19 18:26:34 +00001708 // If this is a definition of a variadic C99 function-like macro, not using
1709 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001710
Chris Lattner249c38b2009-04-19 18:26:34 +00001711 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1712 // This gets unpoisoned where it is allowed.
1713 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1714 if (MI->isC99Varargs())
1715 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001716
Chris Lattnerf64b3522008-03-09 01:54:53 +00001717 // Read the first token after the arg list for down below.
1718 LexUnexpandedToken(Tok);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001719 } else if (LangOpts.C99 || LangOpts.CPlusPlus0x) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001720 // C99 requires whitespace between the macro definition and the body. Emit
1721 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001722 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001723 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001724 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1725 // first character of a replacement list is not a character required by
1726 // subclause 5.2.1, then there shall be white-space separation between the
1727 // identifier and the replacement list.". 5.2.1 lists this set:
1728 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1729 // is irrelevant here.
1730 bool isInvalid = false;
1731 if (Tok.is(tok::at)) // @ is not in the list above.
1732 isInvalid = true;
1733 else if (Tok.is(tok::unknown)) {
1734 // If we have an unknown token, it is something strange like "`". Since
1735 // all of valid characters would have lexed into a single character
1736 // token of some sort, we know this is not a valid case.
1737 isInvalid = true;
1738 }
1739 if (isInvalid)
1740 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1741 else
1742 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001743 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001744
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001745 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001746 LastTok = Tok;
1747
Chris Lattnerf64b3522008-03-09 01:54:53 +00001748 // Read the rest of the macro body.
1749 if (MI->isObjectLike()) {
1750 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001751 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001752 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001753 MI->AddTokenToBody(Tok);
1754 // Get the next token of the macro.
1755 LexUnexpandedToken(Tok);
1756 }
Mike Stump11289f42009-09-09 15:08:12 +00001757
Chris Lattnerf64b3522008-03-09 01:54:53 +00001758 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001759 // Otherwise, read the body of a function-like macro. While we are at it,
1760 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1761 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001762 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001763 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001764
Chris Lattnerf64b3522008-03-09 01:54:53 +00001765 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001766 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001767
Chris Lattnerf64b3522008-03-09 01:54:53 +00001768 // Get the next token of the macro.
1769 LexUnexpandedToken(Tok);
1770 continue;
1771 }
Mike Stump11289f42009-09-09 15:08:12 +00001772
Chris Lattnerf64b3522008-03-09 01:54:53 +00001773 // Get the next token of the macro.
1774 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Chris Lattner83bd8282009-05-25 17:16:10 +00001776 // Check for a valid macro arg identifier.
1777 if (Tok.getIdentifierInfo() == 0 ||
1778 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1779
1780 // If this is assembler-with-cpp mode, we accept random gibberish after
1781 // the '#' because '#' is often a comment character. However, change
1782 // the kind of the token to tok::unknown so that the preprocessor isn't
1783 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001784 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001785 LastTok.setKind(tok::unknown);
1786 } else {
1787 Diag(Tok, diag::err_pp_stringize_not_parameter);
1788 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001789
Chris Lattner83bd8282009-05-25 17:16:10 +00001790 // Disable __VA_ARGS__ again.
1791 Ident__VA_ARGS__->setIsPoisoned(true);
1792 return;
1793 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001794 }
Mike Stump11289f42009-09-09 15:08:12 +00001795
Chris Lattner83bd8282009-05-25 17:16:10 +00001796 // Things look ok, add the '#' and param name tokens to the macro.
1797 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001798 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001799 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001800
Chris Lattnerf64b3522008-03-09 01:54:53 +00001801 // Get the next token of the macro.
1802 LexUnexpandedToken(Tok);
1803 }
1804 }
Mike Stump11289f42009-09-09 15:08:12 +00001805
1806
Chris Lattnerf64b3522008-03-09 01:54:53 +00001807 // Disable __VA_ARGS__ again.
1808 Ident__VA_ARGS__->setIsPoisoned(true);
1809
Chris Lattner57540c52011-04-15 05:22:18 +00001810 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001811 // replacement list.
1812 unsigned NumTokens = MI->getNumTokens();
1813 if (NumTokens != 0) {
1814 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1815 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001816 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001817 return;
1818 }
1819 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1820 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001821 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001822 return;
1823 }
1824 }
Mike Stump11289f42009-09-09 15:08:12 +00001825
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001826 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001827
Chris Lattnerf64b3522008-03-09 01:54:53 +00001828 // Finally, if this identifier already had a macro defined for it, verify that
1829 // the macro bodies are identical and free the old definition.
1830 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001831 // It is very common for system headers to have tons of macro redefinitions
1832 // and for warnings to be disabled in system headers. If this is the case,
1833 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001834 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001835 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001836 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001837 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001838
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001839 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001840 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001841 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001842 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001843 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1844 << MacroNameTok.getIdentifierInfo();
1845 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1846 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001847 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001848 if (OtherMI->isWarnIfUnused())
1849 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001850 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001851 }
Mike Stump11289f42009-09-09 15:08:12 +00001852
Chris Lattnerf64b3522008-03-09 01:54:53 +00001853 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001854
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001855 assert(!MI->isUsed());
1856 // If we need warning for not using the macro, add its location in the
1857 // warn-because-unused-macro set. If it gets used it will be removed from set.
1858 if (isInPrimaryFile() && // don't warn for include'd macros.
1859 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00001860 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001861 MI->setIsWarnIfUnused(true);
1862 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1863 }
1864
Chris Lattner928e9092009-04-12 01:39:54 +00001865 // If the callbacks want to know, tell them about the macro definition.
1866 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001867 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001868}
1869
James Dennettf6333ac2012-06-22 05:46:07 +00001870/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001871///
1872void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1873 ++NumUndefined;
1874
1875 Token MacroNameTok;
1876 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001877
Chris Lattnerf64b3522008-03-09 01:54:53 +00001878 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001879 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001880 return;
Mike Stump11289f42009-09-09 15:08:12 +00001881
Chris Lattnerf64b3522008-03-09 01:54:53 +00001882 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001883 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001884
Chris Lattnerf64b3522008-03-09 01:54:53 +00001885 // Okay, we finally have a valid identifier to undef.
1886 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001887
Chris Lattnerf64b3522008-03-09 01:54:53 +00001888 // If the macro is not defined, this is a noop undef, just return.
1889 if (MI == 0) return;
1890
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00001891 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00001892 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001893
1894 // If the callbacks want to know, tell them about the macro #undef.
1895 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001896 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001897
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001898 if (MI->isWarnIfUnused())
1899 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1900
Chris Lattnerf64b3522008-03-09 01:54:53 +00001901 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001902 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001903 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1904}
1905
1906
1907//===----------------------------------------------------------------------===//
1908// Preprocessor Conditional Directive Handling.
1909//===----------------------------------------------------------------------===//
1910
James Dennettf6333ac2012-06-22 05:46:07 +00001911/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
1912/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
1913/// true if any tokens have been returned or pp-directives activated before this
1914/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001915///
1916void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1917 bool ReadAnyTokensBeforeDirective) {
1918 ++NumIf;
1919 Token DirectiveTok = Result;
1920
1921 Token MacroNameTok;
1922 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001923
Chris Lattnerf64b3522008-03-09 01:54:53 +00001924 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001925 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001926 // Skip code until we get to #endif. This helps with recovery by not
1927 // emitting an error when the #endif is reached.
1928 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1929 /*Foundnonskip*/false, /*FoundElse*/false);
1930 return;
1931 }
Mike Stump11289f42009-09-09 15:08:12 +00001932
Chris Lattnerf64b3522008-03-09 01:54:53 +00001933 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001934 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001935
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001936 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1937 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001938
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001939 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001940 // If the start of a top-level #ifdef and if the macro is not defined,
1941 // inform MIOpt that this might be the start of a proper include guard.
1942 // Otherwise it is some other form of unknown conditional which we can't
1943 // handle.
1944 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001945 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001946 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001947 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001948 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001949 }
1950
Chris Lattnerf64b3522008-03-09 01:54:53 +00001951 // If there is a macro, process it.
1952 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001953 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001954
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00001955 if (Callbacks) {
1956 if (isIfndef)
1957 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok);
1958 else
1959 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok);
1960 }
1961
Chris Lattnerf64b3522008-03-09 01:54:53 +00001962 // Should we include the stuff contained by this directive?
1963 if (!MI == isIfndef) {
1964 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001965 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1966 /*wasskip*/false, /*foundnonskip*/true,
1967 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001968 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001969 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001970 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001971 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001972 /*FoundElse*/false);
1973 }
1974}
1975
James Dennettf6333ac2012-06-22 05:46:07 +00001976/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001977///
1978void Preprocessor::HandleIfDirective(Token &IfToken,
1979 bool ReadAnyTokensBeforeDirective) {
1980 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001981
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001982 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001983 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001984 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1985 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1986 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001987
1988 // If this condition is equivalent to #ifndef X, and if this is the first
1989 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001990 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001991 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001992 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001993 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001994 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001995 }
1996
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00001997 if (Callbacks)
1998 Callbacks->If(IfToken.getLocation(),
1999 SourceRange(ConditionalBegin, ConditionalEnd));
2000
Chris Lattnerf64b3522008-03-09 01:54:53 +00002001 // Should we include the stuff contained by this directive?
2002 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002003 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002004 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002005 /*foundnonskip*/true, /*foundelse*/false);
2006 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002007 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002008 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002009 /*FoundElse*/false);
2010 }
2011}
2012
James Dennettf6333ac2012-06-22 05:46:07 +00002013/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002014///
2015void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2016 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002017
Chris Lattnerf64b3522008-03-09 01:54:53 +00002018 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002019 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002020
Chris Lattnerf64b3522008-03-09 01:54:53 +00002021 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002022 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002023 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002024 Diag(EndifToken, diag::err_pp_endif_without_if);
2025 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002026 }
Mike Stump11289f42009-09-09 15:08:12 +00002027
Chris Lattnerf64b3522008-03-09 01:54:53 +00002028 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002029 if (CurPPLexer->getConditionalStackDepth() == 0)
2030 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002031
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002032 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002033 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002034
2035 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002036 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002037}
2038
James Dennettf6333ac2012-06-22 05:46:07 +00002039/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002040///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002041void Preprocessor::HandleElseDirective(Token &Result) {
2042 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002043
Chris Lattnerf64b3522008-03-09 01:54:53 +00002044 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002045 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002046
Chris Lattnerf64b3522008-03-09 01:54:53 +00002047 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002048 if (CurPPLexer->popConditionalLevel(CI)) {
2049 Diag(Result, diag::pp_err_else_without_if);
2050 return;
2051 }
Mike Stump11289f42009-09-09 15:08:12 +00002052
Chris Lattnerf64b3522008-03-09 01:54:53 +00002053 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002054 if (CurPPLexer->getConditionalStackDepth() == 0)
2055 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002056
2057 // If this is a #else with a #else before it, report the error.
2058 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002059
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002060 if (Callbacks)
2061 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2062
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002063 // Finally, skip the rest of the contents of this block.
2064 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002065 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002066}
2067
James Dennettf6333ac2012-06-22 05:46:07 +00002068/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002069///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002070void Preprocessor::HandleElifDirective(Token &ElifToken) {
2071 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002072
Chris Lattnerf64b3522008-03-09 01:54:53 +00002073 // #elif directive in a non-skipping conditional... start skipping.
2074 // We don't care what the condition is, because we will always skip it (since
2075 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002076 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002077 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002078 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002079
2080 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002081 if (CurPPLexer->popConditionalLevel(CI)) {
2082 Diag(ElifToken, diag::pp_err_elif_without_if);
2083 return;
2084 }
Mike Stump11289f42009-09-09 15:08:12 +00002085
Chris Lattnerf64b3522008-03-09 01:54:53 +00002086 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002087 if (CurPPLexer->getConditionalStackDepth() == 0)
2088 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002089
Chris Lattnerf64b3522008-03-09 01:54:53 +00002090 // If this is a #elif with a #else before it, report the error.
2091 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002092
2093 if (Callbacks)
2094 Callbacks->Elif(ElifToken.getLocation(),
2095 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002096
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002097 // Finally, skip the rest of the contents of this block.
2098 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002099 /*FoundElse*/CI.FoundElse,
2100 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002101}