blob: a6b7b52624ef8c0cc97263bc2da5c7111678a9b8 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettdc201692012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattner141e71f2008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner359cc442009-01-26 05:29:08 +000016#include "clang/Lex/LiteralSupport.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000017#include "clang/Lex/HeaderSearch.h"
18#include "clang/Lex/MacroInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000019#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf44e8542010-08-24 19:08:16 +000020#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregorfba18aa2011-09-15 22:00:41 +000021#include "clang/Lex/ModuleLoader.h"
Douglas Gregor80c60f72010-09-09 22:45:38 +000022#include "clang/Lex/Pragma.h"
Chris Lattner6e290142009-11-30 04:18:44 +000023#include "clang/Basic/FileManager.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000025#include "llvm/ADT/APInt.h"
Douglas Gregore3a82562011-11-30 18:02:36 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000027using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// Utility Methods for Preprocessor Directive Handling.
31//===----------------------------------------------------------------------===//
32
Chris Lattnerf47724b2010-08-17 15:55:45 +000033MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenek9714a232010-10-19 22:15:20 +000034 MacroInfoChain *MIChain;
Mike Stump1eb44332009-09-09 15:08:12 +000035
Ted Kremenek9714a232010-10-19 22:15:20 +000036 if (MICache) {
37 MIChain = MICache;
38 MICache = MICache->Next;
Ted Kremenekaf8fa252010-10-19 18:16:54 +000039 }
Ted Kremenek9714a232010-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 Lattnerf47724b2010-08-17 15:55:45 +000051}
52
53MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
54 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek0ea76722008-12-15 19:56:42 +000055 new (MI) MacroInfo(L);
56 return MI;
57}
58
Chris Lattnerf47724b2010-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 Dennettdc201692012-06-22 05:46:07 +000065/// \brief Release the specified MacroInfo to be reused for allocating
66/// new MacroInfo objects.
Chris Lattner2c1ab902010-08-18 16:08:51 +000067void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenek9714a232010-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 Lattner0301b3f2009-02-20 22:19:20 +000082
Ted Kremenek9714a232010-10-19 22:15:20 +000083 MI->Destroy();
84}
Chris Lattner0301b3f2009-02-20 22:19:20 +000085
James Dennettdc201692012-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 Lattner141e71f2008-03-09 01:54:53 +000088void Preprocessor::DiscardUntilEndOfDirective() {
89 Token Tmp;
90 do {
91 LexUnexpandedToken(Tmp);
Peter Collingbournea5ef5842011-02-22 13:49:06 +000092 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne84021552011-02-28 02:37:51 +000093 } while (Tmp.isNot(tok::eod));
Chris Lattner141e71f2008-03-09 01:54:53 +000094}
95
James Dennettdc201692012-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 Lattner141e71f2008-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 Stump1eb44332009-09-09 15:08:12 +0000106
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000107 if (MacroNameTok.is(tok::code_completion)) {
108 if (CodeComplete)
109 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000110 setCodeCompletionReached();
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000111 LexUnexpandedToken(MacroNameTok);
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000112 }
113
Chris Lattner141e71f2008-03-09 01:54:53 +0000114 // Missing macro name?
Peter Collingbourne84021552011-02-28 02:37:51 +0000115 if (MacroNameTok.is(tok::eod)) {
Chris Lattner3692b092008-11-18 07:59:24 +0000116 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
117 return;
118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Chris Lattner141e71f2008-03-09 01:54:53 +0000120 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
121 if (II == 0) {
Douglas Gregor453091c2010-03-16 22:30:13 +0000122 bool Invalid = false;
123 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
124 if (Invalid)
125 return;
Nico Weberf4fb07e2012-02-29 22:54:43 +0000126
Chris Lattner9485d232008-12-13 20:12:40 +0000127 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weberf4fb07e2012-02-29 22:54:43 +0000128
129 // Allow #defining |and| and friends in microsoft mode.
David Blaikie4e4d0842012-03-11 07:00:24 +0000130 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weberf4fb07e2012-02-29 22:54:43 +0000131 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
132 return;
133 }
134
Chris Lattner9485d232008-12-13 20:12:40 +0000135 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +0000136 // C++ 2.5p2: Alternative tokens behave the same as its primary token
137 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +0000138 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-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 Stump1eb44332009-09-09 15:08:12 +0000156
Chris Lattner141e71f2008-03-09 01:54:53 +0000157 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne84021552011-02-28 02:37:51 +0000158 // token kind to tok::eod.
159 MacroNameTok.setKind(tok::eod);
Chris Lattner141e71f2008-03-09 01:54:53 +0000160 return DiscardUntilEndOfDirective();
161}
162
James Dennettdc201692012-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 Lattnerab82f412009-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 Lattner141e71f2008-03-09 01:54:53 +0000168 Token Tmp;
Chris Lattnerab82f412009-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 Stump1eb44332009-09-09 15:08:12 +0000176
Chris Lattner141e71f2008-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 Stump1eb44332009-09-09 15:08:12 +0000181
Peter Collingbourne84021552011-02-28 02:37:51 +0000182 if (Tmp.isNot(tok::eod)) {
Chris Lattner959875a2009-04-14 05:15:20 +0000183 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourneb2eb53d2011-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 Gregor849b2432010-03-31 17:46:05 +0000187 FixItHint Hint;
David Blaikie4e4d0842012-03-11 07:00:24 +0000188 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000189 !CurTokenLexer)
Douglas Gregor849b2432010-03-31 17:46:05 +0000190 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
191 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattner141e71f2008-03-09 01:54:53 +0000192 DiscardUntilEndOfDirective();
193 }
194}
195
196
197
James Dennettdc201692012-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 Lattner141e71f2008-03-09 01:54:53 +0000201/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettdc201692012-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 Lattner141e71f2008-03-09 01:54:53 +0000206void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
207 bool FoundNonSkipPortion,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000208 bool FoundElse,
209 SourceLocation ElseLoc) {
Chris Lattner141e71f2008-03-09 01:54:53 +0000210 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000211 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000212
Ted Kremenek60e45d42008-11-18 00:34:22 +0000213 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000214 FoundNonSkipPortion, FoundElse);
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Ted Kremenek268ee702008-12-12 18:34:08 +0000216 if (CurPTHLexer) {
217 PTHSkipExcludedConditionalBlock();
218 return;
219 }
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Chris Lattner141e71f2008-03-09 01:54:53 +0000221 // Enter raw mode to disable identifier lookup (and thus macro expansion),
222 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000223 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000224 Token Tok;
225 while (1) {
Chris Lattner2c6b1932010-01-18 22:33:01 +0000226 CurLexer->Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Douglas Gregorf44e8542010-08-24 19:08:16 +0000228 if (Tok.is(tok::code_completion)) {
229 if (CodeComplete)
230 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000231 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000232 continue;
233 }
234
Chris Lattner141e71f2008-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 Kremenek60e45d42008-11-18 00:34:22 +0000239 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000240 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +0000241 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
242 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000243 CurPPLexer->ConditionalStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000244 }
245
Chris Lattner141e71f2008-03-09 01:54:53 +0000246 // Just return and let the caller lex after this #include.
247 break;
248 }
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Chris Lattner141e71f2008-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 Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattner141e71f2008-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 Collingbourne84021552011-02-28 02:37:51 +0000256 // converted into an EOD token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000257 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000258 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000259
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattner141e71f2008-03-09 01:54:53 +0000261 // Read the next token, the directive flavor.
262 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattner141e71f2008-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 Bagnarac4bf2b92010-12-22 08:23:18 +0000266 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000267 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000268 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000269 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-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 Bagnarac4bf2b92010-12-22 08:23:18 +0000278 const char *RawCharData = Tok.getRawIdentifierData();
279
Chris Lattner141e71f2008-03-09 01:54:53 +0000280 char FirstChar = RawCharData[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000281 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000282 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000283 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000284 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000285 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000286 continue;
287 }
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Chris Lattner141e71f2008-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 Kramerb939a4e2009-12-31 13:32:38 +0000292 char DirectiveBuf[20];
Chris Lattner5f9e2722011-07-23 10:55:15 +0000293 StringRef Directive;
Chris Lattner141e71f2008-03-09 01:54:53 +0000294 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000295 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattner141e71f2008-03-09 01:54:53 +0000296 } else {
297 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000298 unsigned IdLen = DirectiveStr.size();
Chris Lattner141e71f2008-03-09 01:54:53 +0000299 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000300 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000301 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000302 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000303 continue;
304 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000305 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000306 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattner141e71f2008-03-09 01:54:53 +0000307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000309 if (Directive.startswith("if")) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000310 StringRef Sub = Directive.substr(2);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000311 if (Sub.empty() || // "if"
312 Sub == "def" || // "ifdef"
313 Sub == "ndef") { // "ifndef"
Chris Lattner141e71f2008-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 Kremenek60e45d42008-11-18 00:34:22 +0000317 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000318 /*foundnonskip*/false,
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000319 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000320 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000321 } else if (Directive[0] == 'e') {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000322 StringRef Sub = Directive.substr(1);
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000323 if (Sub == "ndif") { // "endif"
Chris Lattner141e71f2008-03-09 01:54:53 +0000324 PPConditionalInfo CondInfo;
325 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000326 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000327 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattner141e71f2008-03-09 01:54:53 +0000328 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Chris Lattner141e71f2008-03-09 01:54:53 +0000330 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000331 if (!CondInfo.WasSkipping) {
Richard Smithbc9e5582012-06-24 23:56:26 +0000332 // Restore the value of LexingRawMode so that trailing comments
333 // are handled correctly, if we've reached the outermost block.
334 CurPPLexer->LexingRawMode = false;
Richard Smith986f3172012-06-21 00:35:03 +0000335 CheckEndOfDirective("endif");
Richard Smithbc9e5582012-06-24 23:56:26 +0000336 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000337 if (Callbacks)
338 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000339 break;
Richard Smith986f3172012-06-21 00:35:03 +0000340 } else {
341 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000342 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000343 } else if (Sub == "lse") { // "else".
Chris Lattner141e71f2008-03-09 01:54:53 +0000344 // #else directive in a skipping conditional. If not in some other
345 // skipping conditional, and if #else hasn't already been seen, enter it
346 // as a non-skipping conditional.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000347 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Chris Lattner141e71f2008-03-09 01:54:53 +0000349 // If this is a #else with a #else before it, report the error.
350 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Chris Lattner141e71f2008-03-09 01:54:53 +0000352 // Note that we've seen a #else in this conditional.
353 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Chris Lattner141e71f2008-03-09 01:54:53 +0000355 // If the conditional is at the top level, and the #if block wasn't
356 // entered, enter the #else block now.
357 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
358 CondInfo.FoundNonSkip = true;
Richard Smithbc9e5582012-06-24 23:56:26 +0000359 // Restore the value of LexingRawMode so that trailing comments
360 // are handled correctly.
361 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000362 CheckEndOfDirective("else");
Richard Smithbc9e5582012-06-24 23:56:26 +0000363 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000364 if (Callbacks)
365 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000366 break;
Argyrios Kyrtzidise26224e2011-05-21 04:26:04 +0000367 } else {
368 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattner141e71f2008-03-09 01:54:53 +0000369 }
Benjamin Kramerb939a4e2009-12-31 13:32:38 +0000370 } else if (Sub == "lif") { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000371 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000372
373 bool ShouldEnter;
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000374 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +0000375 // If this is in a skipping block or if we're already handled this #if
376 // block, don't bother parsing the condition.
377 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
378 DiscardUntilEndOfDirective();
379 ShouldEnter = false;
380 } else {
381 // Restore the value of LexingRawMode so that identifiers are
382 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000383 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
384 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000385 IdentifierInfo *IfNDefMacro = 0;
386 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000387 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000388 }
Chandler Carruth3a1a8742011-01-03 17:40:17 +0000389 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Chris Lattner141e71f2008-03-09 01:54:53 +0000391 // If this is a #elif with a #else before it, report the error.
392 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Chris Lattner141e71f2008-03-09 01:54:53 +0000394 // If this condition is true, enter it!
395 if (ShouldEnter) {
396 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +0000397 if (Callbacks)
398 Callbacks->Elif(Tok.getLocation(),
399 SourceRange(ConditionalBegin, ConditionalEnd),
400 CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +0000401 break;
402 }
403 }
404 }
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Ted Kremenek60e45d42008-11-18 00:34:22 +0000406 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000407 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000408 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000409 }
410
411 // Finally, if we are out of the conditional (saw an #endif or ran off the end
412 // of the file, just stop skipping and return to lexing whatever came after
413 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000414 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +0000415
416 if (Callbacks) {
417 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
418 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
419 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000420}
421
Ted Kremenek268ee702008-12-12 18:34:08 +0000422void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump1eb44332009-09-09 15:08:12 +0000423
424 while (1) {
Ted Kremenek268ee702008-12-12 18:34:08 +0000425 assert(CurPTHLexer);
426 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Ted Kremenek268ee702008-12-12 18:34:08 +0000428 // Skip to the next '#else', '#elif', or #endif.
429 if (CurPTHLexer->SkipBlock()) {
430 // We have reached an #endif. Both the '#' and 'endif' tokens
431 // have been consumed by the PTHLexer. Just pop off the condition level.
432 PPConditionalInfo CondInfo;
433 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000434 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek268ee702008-12-12 18:34:08 +0000435 assert(!InCond && "Can't be skipping if not in a conditional!");
436 break;
437 }
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Ted Kremenek268ee702008-12-12 18:34:08 +0000439 // We have reached a '#else' or '#elif'. Lex the next token to get
440 // the directive flavor.
441 Token Tok;
442 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Ted Kremenek268ee702008-12-12 18:34:08 +0000444 // We can actually look up the IdentifierInfo here since we aren't in
445 // raw mode.
446 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
447
448 if (K == tok::pp_else) {
449 // #else: Enter the else condition. We aren't in a nested condition
450 // since we skip those. We're always in the one matching the last
451 // blocked we skipped.
452 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
453 // Note that we've seen a #else in this conditional.
454 CondInfo.FoundElse = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Ted Kremenek268ee702008-12-12 18:34:08 +0000456 // If the #if block wasn't entered then enter the #else block now.
457 if (!CondInfo.FoundNonSkip) {
458 CondInfo.FoundNonSkip = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Peter Collingbourne84021552011-02-28 02:37:51 +0000460 // Scan until the eod token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000461 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar8533bd52009-04-13 17:57:49 +0000462 DiscardUntilEndOfDirective();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000463 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Ted Kremenek268ee702008-12-12 18:34:08 +0000465 break;
466 }
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Ted Kremenek268ee702008-12-12 18:34:08 +0000468 // Otherwise skip this block.
469 continue;
470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Ted Kremenek268ee702008-12-12 18:34:08 +0000472 assert(K == tok::pp_elif);
473 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
474
475 // If this is a #elif with a #else before it, report the error.
476 if (CondInfo.FoundElse)
477 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Ted Kremenek268ee702008-12-12 18:34:08 +0000479 // If this is in a skipping block or if we're already handled this #if
Mike Stump1eb44332009-09-09 15:08:12 +0000480 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek268ee702008-12-12 18:34:08 +0000481 if (CondInfo.FoundNonSkip)
482 continue;
483
484 // Evaluate the condition of the #elif.
485 IdentifierInfo *IfNDefMacro = 0;
486 CurPTHLexer->ParsingPreprocessorDirective = true;
487 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
488 CurPTHLexer->ParsingPreprocessorDirective = false;
489
490 // If this condition is true, enter it!
491 if (ShouldEnter) {
492 CondInfo.FoundNonSkip = true;
493 break;
494 }
495
496 // Otherwise, skip this block and go to the next one.
497 continue;
498 }
499}
500
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000501const FileEntry *Preprocessor::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000502 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000503 bool isAngled,
504 const DirectoryLookup *FromDir,
505 const DirectoryLookup *&CurDir,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000506 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000507 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000508 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000509 bool SkipCache) {
Chris Lattner10725092008-03-09 04:17:44 +0000510 // If the header lookup mechanism may be relative to the current file, pass in
511 // info about where the current file is.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000512 const FileEntry *CurFileEnt = 0;
Chris Lattner10725092008-03-09 04:17:44 +0000513 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000514 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000515 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000517 // If there is no file entry associated with this file, it must be the
518 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000519 // it won't be scanned for preprocessor directives. If we have the
520 // predefines buffer, resolve #include references (which come from the
521 // -include command line argument) as if they came from the main file, this
522 // affects file lookup etc.
523 if (CurFileEnt == 0) {
Chris Lattnerbe5c64d2009-02-04 19:45:07 +0000524 FID = SourceMgr.getMainFileID();
525 CurFileEnt = SourceMgr.getFileEntryForID(FID);
526 }
Chris Lattner10725092008-03-09 04:17:44 +0000527 }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Chris Lattner10725092008-03-09 04:17:44 +0000529 // Do a standard file entry lookup.
530 CurDir = CurDirLookup;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000531 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +0000532 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000533 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerf45b6462010-01-22 00:14:44 +0000534 if (FE) return FE;
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Chris Lattner10725092008-03-09 04:17:44 +0000536 // Otherwise, see if this is a subframework header. If so, this is relative
537 // to one of the headers on the #include stack. Walk the list of the current
538 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000539 // FIXME: SuggestedModule!
Ted Kremenek81d24e12008-11-20 16:19:53 +0000540 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000541 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000542 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek74124942011-04-26 21:50:03 +0000543 SearchPath, RelativePath)))
Chris Lattner10725092008-03-09 04:17:44 +0000544 return FE;
545 }
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Chris Lattner10725092008-03-09 04:17:44 +0000547 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
548 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000549 if (IsFileLexer(ISEntry)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000550 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000551 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek74124942011-04-26 21:50:03 +0000552 if ((FE = HeaderInfo.LookupSubframeworkHeader(
553 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattner10725092008-03-09 04:17:44 +0000554 return FE;
555 }
556 }
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Chris Lattner10725092008-03-09 04:17:44 +0000558 // Otherwise, we really couldn't find the file.
559 return 0;
560}
561
Chris Lattner141e71f2008-03-09 01:54:53 +0000562
563//===----------------------------------------------------------------------===//
564// Preprocessor Directive Handling.
565//===----------------------------------------------------------------------===//
566
David Blaikie8c0b3782012-06-06 18:52:13 +0000567class Preprocessor::ResetMacroExpansionHelper {
568public:
569 ResetMacroExpansionHelper(Preprocessor *pp)
570 : PP(pp), save(pp->DisableMacroExpansion) {
571 if (pp->MacroExpansionInDirectivesOverride)
572 pp->DisableMacroExpansion = false;
573 }
574 ~ResetMacroExpansionHelper() {
575 PP->DisableMacroExpansion = save;
576 }
577private:
578 Preprocessor *PP;
579 bool save;
580};
581
Chris Lattner141e71f2008-03-09 01:54:53 +0000582/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump1eb44332009-09-09 15:08:12 +0000583/// at the start of a line. This consumes the directive, modifies the
Chris Lattner141e71f2008-03-09 01:54:53 +0000584/// lexer/preprocessor state, and advances the lexer(s) so that the next token
585/// read is the correct one.
586void Preprocessor::HandleDirective(Token &Result) {
587 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Chris Lattner141e71f2008-03-09 01:54:53 +0000589 // We just parsed a # character at the start of a line, so we're in directive
590 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne84021552011-02-28 02:37:51 +0000591 // EOD token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000592 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Chris Lattner141e71f2008-03-09 01:54:53 +0000594 ++NumDirectives;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000595
Chris Lattner141e71f2008-03-09 01:54:53 +0000596 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump1eb44332009-09-09 15:08:12 +0000597 // work, we have to remember if we had read any tokens *before* this
Chris Lattner141e71f2008-03-09 01:54:53 +0000598 // pp-directive.
Chris Lattner1d9c54d2009-12-14 04:54:40 +0000599 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Chris Lattner42aa16c2009-03-18 21:00:25 +0000601 // Save the '#' token in case we need to return it later.
602 Token SavedHash = Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Chris Lattner141e71f2008-03-09 01:54:53 +0000604 // Read the next token, the directive flavor. This isn't expanded due to
605 // C99 6.10.3p8.
606 LexUnexpandedToken(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Chris Lattner141e71f2008-03-09 01:54:53 +0000608 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
609 // #define A(x) #x
610 // A(abc
611 // #warning blah
612 // def)
Richard Smitha3ca4d62011-12-16 22:50:01 +0000613 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
614 // not support this for #include-like directives, since that can result in
615 // terrible diagnostics, and does not work in GCC.
616 if (InMacroArgs) {
617 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
618 switch (II->getPPKeywordID()) {
619 case tok::pp_include:
620 case tok::pp_import:
621 case tok::pp_include_next:
622 case tok::pp___include_macros:
623 Diag(Result, diag::err_embedded_include) << II->getName();
624 DiscardUntilEndOfDirective();
625 return;
626 default:
627 break;
628 }
629 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000630 Diag(Result, diag::ext_embedded_directive);
Richard Smitha3ca4d62011-12-16 22:50:01 +0000631 }
Mike Stump1eb44332009-09-09 15:08:12 +0000632
David Blaikie8c0b3782012-06-06 18:52:13 +0000633 // Temporarily enable macro expansion if set so
634 // and reset to previous state when returning from this function.
635 ResetMacroExpansionHelper helper(this);
636
Chris Lattner141e71f2008-03-09 01:54:53 +0000637TryAgain:
638 switch (Result.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000639 case tok::eod:
Chris Lattner141e71f2008-03-09 01:54:53 +0000640 return; // null directive.
641 case tok::comment:
642 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
643 LexUnexpandedToken(Result);
644 goto TryAgain;
Douglas Gregorf44e8542010-08-24 19:08:16 +0000645 case tok::code_completion:
646 if (CodeComplete)
647 CodeComplete->CodeCompleteDirective(
648 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000649 setCodeCompletionReached();
Douglas Gregorf44e8542010-08-24 19:08:16 +0000650 return;
Chris Lattner478a18e2009-01-26 06:19:46 +0000651 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikie4e4d0842012-03-11 07:00:24 +0000652 if (getLangOpts().AsmPreprocessor)
Chris Lattner5f607c42009-03-18 20:41:10 +0000653 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner478a18e2009-01-26 06:19:46 +0000654 return HandleDigitDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000655 default:
656 IdentifierInfo *II = Result.getIdentifierInfo();
657 if (II == 0) break; // Not an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Chris Lattner141e71f2008-03-09 01:54:53 +0000659 // Ask what the preprocessor keyword ID is.
660 switch (II->getPPKeywordID()) {
661 default: break;
662 // C99 6.10.1 - Conditional Inclusion.
663 case tok::pp_if:
664 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
665 case tok::pp_ifdef:
666 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
667 case tok::pp_ifndef:
668 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
669 case tok::pp_elif:
670 return HandleElifDirective(Result);
671 case tok::pp_else:
672 return HandleElseDirective(Result);
673 case tok::pp_endif:
674 return HandleEndifDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Chris Lattner141e71f2008-03-09 01:54:53 +0000676 // C99 6.10.2 - Source File Inclusion.
677 case tok::pp_include:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000678 // Handle #include.
679 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000680 case tok::pp___include_macros:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000681 // Handle -imacros.
682 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattner141e71f2008-03-09 01:54:53 +0000684 // C99 6.10.3 - Macro Replacement.
685 case tok::pp_define:
686 return HandleDefineDirective(Result);
687 case tok::pp_undef:
688 return HandleUndefDirective(Result);
689
690 // C99 6.10.4 - Line Control.
691 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000692 return HandleLineDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Chris Lattner141e71f2008-03-09 01:54:53 +0000694 // C99 6.10.5 - Error Directive.
695 case tok::pp_error:
696 return HandleUserDiagnosticDirective(Result, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Chris Lattner141e71f2008-03-09 01:54:53 +0000698 // C99 6.10.6 - Pragma Directive.
699 case tok::pp_pragma:
Douglas Gregor80c60f72010-09-09 22:45:38 +0000700 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Chris Lattner141e71f2008-03-09 01:54:53 +0000702 // GNU Extensions.
703 case tok::pp_import:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000704 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000705 case tok::pp_include_next:
Douglas Gregorecdcb882010-10-20 22:00:55 +0000706 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Chris Lattner141e71f2008-03-09 01:54:53 +0000708 case tok::pp_warning:
709 Diag(Result, diag::ext_pp_warning_directive);
710 return HandleUserDiagnosticDirective(Result, true);
711 case tok::pp_ident:
712 return HandleIdentSCCSDirective(Result);
713 case tok::pp_sccs:
714 return HandleIdentSCCSDirective(Result);
715 case tok::pp_assert:
716 //isExtension = true; // FIXME: implement #assert
717 break;
718 case tok::pp_unassert:
719 //isExtension = true; // FIXME: implement #unassert
720 break;
Douglas Gregor7143aab2011-09-01 17:04:32 +0000721
Douglas Gregor1ac13c32012-01-03 19:48:16 +0000722 case tok::pp___public_macro:
David Blaikie4e4d0842012-03-11 07:00:24 +0000723 if (getLangOpts().Modules)
Douglas Gregor94ad28b2012-01-03 18:24:14 +0000724 return HandleMacroPublicDirective(Result);
725 break;
726
Douglas Gregor1ac13c32012-01-03 19:48:16 +0000727 case tok::pp___private_macro:
David Blaikie4e4d0842012-03-11 07:00:24 +0000728 if (getLangOpts().Modules)
Douglas Gregor94ad28b2012-01-03 18:24:14 +0000729 return HandleMacroPrivateDirective(Result);
730 break;
Chris Lattner141e71f2008-03-09 01:54:53 +0000731 }
732 break;
733 }
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattner42aa16c2009-03-18 21:00:25 +0000735 // If this is a .S file, treat unknown # directives as non-preprocessor
736 // directives. This is important because # may be a comment or introduce
737 // various pseudo-ops. Just return the # token and push back the following
738 // token to be lexed next time.
David Blaikie4e4d0842012-03-11 07:00:24 +0000739 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar3d399a02009-07-13 21:48:50 +0000740 Token *Toks = new Token[2];
Chris Lattner42aa16c2009-03-18 21:00:25 +0000741 // Return the # and the token after it.
Mike Stump1eb44332009-09-09 15:08:12 +0000742 Toks[0] = SavedHash;
Chris Lattner42aa16c2009-03-18 21:00:25 +0000743 Toks[1] = Result;
Chris Lattnerba3ca522011-01-06 05:01:51 +0000744
745 // If the second token is a hashhash token, then we need to translate it to
746 // unknown so the token lexer doesn't try to perform token pasting.
747 if (Result.is(tok::hashhash))
748 Toks[1].setKind(tok::unknown);
749
Chris Lattner42aa16c2009-03-18 21:00:25 +0000750 // Enter this token stream so that we re-lex the tokens. Make sure to
751 // enable macro expansion, in case the token after the # is an identifier
752 // that is expanded.
753 EnterTokenStream(Toks, 2, false, true);
754 return;
755 }
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Chris Lattner141e71f2008-03-09 01:54:53 +0000757 // If we reached here, the preprocessing token is not valid!
758 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Chris Lattner141e71f2008-03-09 01:54:53 +0000760 // Read the rest of the PP line.
761 DiscardUntilEndOfDirective();
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Chris Lattner141e71f2008-03-09 01:54:53 +0000763 // Okay, we're done parsing the directive.
764}
765
Chris Lattner478a18e2009-01-26 06:19:46 +0000766/// GetLineValue - Convert a numeric token into an unsigned value, emitting
767/// Diagnostic DiagID if it is invalid, and returning the value in Val.
768static bool GetLineValue(Token &DigitTok, unsigned &Val,
769 unsigned DiagID, Preprocessor &PP) {
770 if (DigitTok.isNot(tok::numeric_constant)) {
771 PP.Diag(DigitTok, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Peter Collingbourne84021552011-02-28 02:37:51 +0000773 if (DigitTok.isNot(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000774 PP.DiscardUntilEndOfDirective();
775 return true;
776 }
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000778 SmallString<64> IntegerBuffer;
Chris Lattner478a18e2009-01-26 06:19:46 +0000779 IntegerBuffer.resize(DigitTok.getLength());
780 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregor453091c2010-03-16 22:30:13 +0000781 bool Invalid = false;
782 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
783 if (Invalid)
784 return true;
785
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000786 // Verify that we have a simple digit-sequence, and compute the value. This
787 // is always a simple digit string computed in decimal, so we do this manually
788 // here.
789 Val = 0;
790 for (unsigned i = 0; i != ActualLength; ++i) {
791 if (!isdigit(DigitTokBegin[i])) {
792 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
793 diag::err_pp_line_digit_sequence);
794 PP.DiscardUntilEndOfDirective();
795 return true;
796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000798 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
799 if (NextVal < Val) { // overflow.
800 PP.Diag(DigitTok, DiagID);
801 PP.DiscardUntilEndOfDirective();
802 return true;
803 }
804 Val = NextVal;
Chris Lattner478a18e2009-01-26 06:19:46 +0000805 }
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Fariborz Jahanian540f9ae2012-06-26 21:19:20 +0000807 if (DigitTokBegin[0] == '0' && Val)
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000808 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Chris Lattner478a18e2009-01-26 06:19:46 +0000810 return false;
811}
812
James Dennettdc201692012-06-22 05:46:07 +0000813/// \brief Handle a \#line directive: C99 6.10.4.
814///
815/// The two acceptable forms are:
816/// \verbatim
Chris Lattner359cc442009-01-26 05:29:08 +0000817/// # line digit-sequence
818/// # line digit-sequence "s-char-sequence"
James Dennettdc201692012-06-22 05:46:07 +0000819/// \endverbatim
Chris Lattner359cc442009-01-26 05:29:08 +0000820void Preprocessor::HandleLineDirective(Token &Tok) {
821 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
822 // expanded.
823 Token DigitTok;
824 Lex(DigitTok);
825
Chris Lattner359cc442009-01-26 05:29:08 +0000826 // Validate the number and convert it to an unsigned.
Chris Lattner478a18e2009-01-26 06:19:46 +0000827 unsigned LineNo;
Chris Lattnerdc8c90d2009-04-18 18:35:15 +0000828 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner359cc442009-01-26 05:29:08 +0000829 return;
Fariborz Jahanian540f9ae2012-06-26 21:19:20 +0000830
831 if (LineNo == 0)
832 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner359cc442009-01-26 05:29:08 +0000833
Chris Lattner478a18e2009-01-26 06:19:46 +0000834 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
835 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman158ebfb2011-10-10 23:35:28 +0000836 unsigned LineLimit = 32768U;
David Blaikie4e4d0842012-03-11 07:00:24 +0000837 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
Eli Friedman158ebfb2011-10-10 23:35:28 +0000838 LineLimit = 2147483648U;
Chris Lattner359cc442009-01-26 05:29:08 +0000839 if (LineNo >= LineLimit)
840 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
David Blaikie4e4d0842012-03-11 07:00:24 +0000841 else if (LangOpts.CPlusPlus0x && LineNo >= 32768U)
Richard Smith661a9962011-10-15 01:18:56 +0000842 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Chris Lattner5b9a5042009-01-26 07:57:50 +0000844 int FilenameID = -1;
Chris Lattner359cc442009-01-26 05:29:08 +0000845 Token StrTok;
846 Lex(StrTok);
847
Peter Collingbourne84021552011-02-28 02:37:51 +0000848 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
849 // string followed by eod.
850 if (StrTok.is(tok::eod))
Chris Lattner359cc442009-01-26 05:29:08 +0000851 ; // ok
852 else if (StrTok.isNot(tok::string_literal)) {
853 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smith99831e42012-03-06 03:21:47 +0000854 return DiscardUntilEndOfDirective();
855 } else if (StrTok.hasUDSuffix()) {
856 Diag(StrTok, diag::err_invalid_string_udl);
857 return DiscardUntilEndOfDirective();
Chris Lattner359cc442009-01-26 05:29:08 +0000858 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000859 // Parse and validate the string, converting it into a unique ID.
860 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000861 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000862 if (Literal.hadError)
863 return DiscardUntilEndOfDirective();
864 if (Literal.Pascal) {
865 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
866 return DiscardUntilEndOfDirective();
867 }
Jay Foad65aa6882011-06-21 15:13:30 +0000868 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Peter Collingbourne84021552011-02-28 02:37:51 +0000870 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattnerab82f412009-04-17 23:30:53 +0000871 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
872 CheckEndOfDirective("line", true);
Chris Lattner359cc442009-01-26 05:29:08 +0000873 }
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Chris Lattner4c4ea172009-02-03 21:52:55 +0000875 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Chris Lattner16629382009-03-27 17:13:49 +0000877 if (Callbacks)
Chris Lattner86d0ef72010-04-14 04:28:50 +0000878 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
879 PPCallbacks::RenameFile,
Chris Lattner16629382009-03-27 17:13:49 +0000880 SrcMgr::C_User);
Chris Lattner359cc442009-01-26 05:29:08 +0000881}
882
Chris Lattner478a18e2009-01-26 06:19:46 +0000883/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
884/// marker directive.
885static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
886 bool &IsSystemHeader, bool &IsExternCHeader,
887 Preprocessor &PP) {
888 unsigned FlagVal;
889 Token FlagTok;
890 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000891 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000892 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
893 return true;
894
895 if (FlagVal == 1) {
896 IsFileEntry = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Chris Lattner478a18e2009-01-26 06:19:46 +0000898 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000899 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000900 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
901 return true;
902 } else if (FlagVal == 2) {
903 IsFileExit = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Chris Lattner137b6a62009-02-04 06:25:26 +0000905 SourceManager &SM = PP.getSourceManager();
906 // If we are leaving the current presumed file, check to make sure the
907 // presumed include stack isn't empty!
908 FileID CurFileID =
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000909 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner137b6a62009-02-04 06:25:26 +0000910 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000911 if (PLoc.isInvalid())
912 return true;
913
Chris Lattner137b6a62009-02-04 06:25:26 +0000914 // If there is no include loc (main file) or if the include loc is in a
915 // different physical file, then we aren't in a "1" line marker flag region.
916 SourceLocation IncLoc = PLoc.getIncludeLoc();
917 if (IncLoc.isInvalid() ||
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000918 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner137b6a62009-02-04 06:25:26 +0000919 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
920 PP.DiscardUntilEndOfDirective();
921 return true;
922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Chris Lattner478a18e2009-01-26 06:19:46 +0000924 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000925 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000926 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
927 return true;
928 }
929
930 // We must have 3 if there are still flags.
931 if (FlagVal != 3) {
932 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000933 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000934 return true;
935 }
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Chris Lattner478a18e2009-01-26 06:19:46 +0000937 IsSystemHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner478a18e2009-01-26 06:19:46 +0000939 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000940 if (FlagTok.is(tok::eod)) return false;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000941 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner478a18e2009-01-26 06:19:46 +0000942 return true;
943
944 // We must have 4 if there is yet another flag.
945 if (FlagVal != 4) {
946 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000947 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000948 return true;
949 }
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattner478a18e2009-01-26 06:19:46 +0000951 IsExternCHeader = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Chris Lattner478a18e2009-01-26 06:19:46 +0000953 PP.Lex(FlagTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000954 if (FlagTok.is(tok::eod)) return false;
Chris Lattner478a18e2009-01-26 06:19:46 +0000955
956 // There are no more valid flags here.
957 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000958 PP.DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000959 return true;
960}
961
962/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
963/// one of the following forms:
964///
965/// # 42
Mike Stump1eb44332009-09-09 15:08:12 +0000966/// # 42 "file" ('1' | '2')?
Chris Lattner478a18e2009-01-26 06:19:46 +0000967/// # 42 "file" ('1' | '2')? '3' '4'?
968///
969void Preprocessor::HandleDigitDirective(Token &DigitTok) {
970 // Validate the number and convert it to an unsigned. GNU does not have a
971 // line # limit other than it fit in 32-bits.
972 unsigned LineNo;
973 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
974 *this))
975 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Chris Lattner478a18e2009-01-26 06:19:46 +0000977 Token StrTok;
978 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Chris Lattner478a18e2009-01-26 06:19:46 +0000980 bool IsFileEntry = false, IsFileExit = false;
981 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000982 int FilenameID = -1;
983
Peter Collingbourne84021552011-02-28 02:37:51 +0000984 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
985 // string followed by eod.
986 if (StrTok.is(tok::eod))
Chris Lattner478a18e2009-01-26 06:19:46 +0000987 ; // ok
988 else if (StrTok.isNot(tok::string_literal)) {
989 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000990 return DiscardUntilEndOfDirective();
Richard Smith99831e42012-03-06 03:21:47 +0000991 } else if (StrTok.hasUDSuffix()) {
992 Diag(StrTok, diag::err_invalid_string_udl);
993 return DiscardUntilEndOfDirective();
Chris Lattner478a18e2009-01-26 06:19:46 +0000994 } else {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000995 // Parse and validate the string, converting it into a unique ID.
996 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregor5cee1192011-07-27 05:40:30 +0000997 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattner5b9a5042009-01-26 07:57:50 +0000998 if (Literal.hadError)
999 return DiscardUntilEndOfDirective();
1000 if (Literal.Pascal) {
1001 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1002 return DiscardUntilEndOfDirective();
1003 }
Jay Foad65aa6882011-06-21 15:13:30 +00001004 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chris Lattner478a18e2009-01-26 06:19:46 +00001006 // If a filename was present, read any flags that are present.
Mike Stump1eb44332009-09-09 15:08:12 +00001007 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattner5b9a5042009-01-26 07:57:50 +00001008 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner478a18e2009-01-26 06:19:46 +00001009 return;
Chris Lattner478a18e2009-01-26 06:19:46 +00001010 }
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Chris Lattner9d79eba2009-02-04 05:21:58 +00001012 // Create a line note with this information.
1013 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump1eb44332009-09-09 15:08:12 +00001014 IsFileEntry, IsFileExit,
Chris Lattner9d79eba2009-02-04 05:21:58 +00001015 IsSystemHeader, IsExternCHeader);
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattner16629382009-03-27 17:13:49 +00001017 // If the preprocessor has callbacks installed, notify them of the #line
1018 // change. This is used so that the line marker comes out in -E mode for
1019 // example.
1020 if (Callbacks) {
1021 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1022 if (IsFileEntry)
1023 Reason = PPCallbacks::EnterFile;
1024 else if (IsFileExit)
1025 Reason = PPCallbacks::ExitFile;
1026 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1027 if (IsExternCHeader)
1028 FileKind = SrcMgr::C_ExternCSystem;
1029 else if (IsSystemHeader)
1030 FileKind = SrcMgr::C_System;
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Chris Lattner86d0ef72010-04-14 04:28:50 +00001032 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner16629382009-03-27 17:13:49 +00001033 }
Chris Lattner478a18e2009-01-26 06:19:46 +00001034}
1035
1036
Chris Lattner099dd052009-01-26 05:30:54 +00001037/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1038///
Mike Stump1eb44332009-09-09 15:08:12 +00001039void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001040 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +00001041 // PTH doesn't emit #warning or #error directives.
1042 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +00001043 return CurPTHLexer->DiscardToEndOfLine();
1044
Chris Lattner141e71f2008-03-09 01:54:53 +00001045 // Read the rest of the line raw. We do this because we don't want macros
1046 // to be expanded and we don't require that the tokens be valid preprocessing
1047 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1048 // collapse multiple consequtive white space between tokens, but this isn't
1049 // specified by the standard.
Benjamin Kramer3093b202012-05-18 19:32:16 +00001050 SmallString<128> Message;
1051 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek34a2c422012-02-02 00:16:13 +00001052
1053 // Find the first non-whitespace character, so that we can make the
1054 // diagnostic more succinct.
Benjamin Kramer3093b202012-05-18 19:32:16 +00001055 StringRef Msg = Message.str().ltrim(" ");
1056
Chris Lattner359cc442009-01-26 05:29:08 +00001057 if (isWarning)
Ted Kremenek34a2c422012-02-02 00:16:13 +00001058 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner359cc442009-01-26 05:29:08 +00001059 else
Ted Kremenek34a2c422012-02-02 00:16:13 +00001060 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattner141e71f2008-03-09 01:54:53 +00001061}
1062
1063/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1064///
1065void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1066 // Yes, this directive is an extension.
1067 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Chris Lattner141e71f2008-03-09 01:54:53 +00001069 // Read the string argument.
1070 Token StrTok;
1071 Lex(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Chris Lattner141e71f2008-03-09 01:54:53 +00001073 // If the token kind isn't a string, it's a malformed directive.
1074 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +00001075 StrTok.isNot(tok::wide_string_literal)) {
1076 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne84021552011-02-28 02:37:51 +00001077 if (StrTok.isNot(tok::eod))
Chris Lattner099dd052009-01-26 05:30:54 +00001078 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +00001079 return;
1080 }
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Richard Smith99831e42012-03-06 03:21:47 +00001082 if (StrTok.hasUDSuffix()) {
1083 Diag(StrTok, diag::err_invalid_string_udl);
1084 return DiscardUntilEndOfDirective();
1085 }
1086
Peter Collingbourne84021552011-02-28 02:37:51 +00001087 // Verify that there is nothing after the string, other than EOD.
Chris Lattner35410d52009-04-14 05:07:49 +00001088 CheckEndOfDirective("ident");
Chris Lattner141e71f2008-03-09 01:54:53 +00001089
Douglas Gregor453091c2010-03-16 22:30:13 +00001090 if (Callbacks) {
1091 bool Invalid = false;
1092 std::string Str = getSpelling(StrTok, &Invalid);
1093 if (!Invalid)
1094 Callbacks->Ident(Tok.getLocation(), Str);
1095 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001096}
1097
Douglas Gregor94ad28b2012-01-03 18:24:14 +00001098/// \brief Handle a #public directive.
1099void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor7143aab2011-09-01 17:04:32 +00001100 Token MacroNameTok;
1101 ReadMacroName(MacroNameTok, 2);
1102
1103 // Error reading macro name? If so, diagnostic already issued.
1104 if (MacroNameTok.is(tok::eod))
1105 return;
1106
Douglas Gregor1ac13c32012-01-03 19:48:16 +00001107 // Check to see if this is the last token on the #__public_macro line.
1108 CheckEndOfDirective("__public_macro");
Douglas Gregor7143aab2011-09-01 17:04:32 +00001109
1110 // Okay, we finally have a valid identifier to undef.
1111 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1112
1113 // If the macro is not defined, this is an error.
1114 if (MI == 0) {
Douglas Gregoraa93a872011-10-17 15:32:29 +00001115 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor7143aab2011-09-01 17:04:32 +00001116 << MacroNameTok.getIdentifierInfo();
1117 return;
1118 }
1119
1120 // Note that this macro has now been exported.
Douglas Gregoraa93a872011-10-17 15:32:29 +00001121 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1122
1123 // If this macro definition came from a PCH file, mark it
1124 // as having changed since serialization.
1125 if (MI->isFromAST())
1126 MI->setChangedAfterLoad();
1127}
1128
Douglas Gregor94ad28b2012-01-03 18:24:14 +00001129/// \brief Handle a #private directive.
Douglas Gregoraa93a872011-10-17 15:32:29 +00001130void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1131 Token MacroNameTok;
1132 ReadMacroName(MacroNameTok, 2);
1133
1134 // Error reading macro name? If so, diagnostic already issued.
1135 if (MacroNameTok.is(tok::eod))
1136 return;
1137
Douglas Gregor1ac13c32012-01-03 19:48:16 +00001138 // Check to see if this is the last token on the #__private_macro line.
1139 CheckEndOfDirective("__private_macro");
Douglas Gregoraa93a872011-10-17 15:32:29 +00001140
1141 // Okay, we finally have a valid identifier to undef.
1142 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1143
1144 // If the macro is not defined, this is an error.
1145 if (MI == 0) {
1146 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1147 << MacroNameTok.getIdentifierInfo();
1148 return;
1149 }
1150
1151 // Note that this macro has now been marked private.
1152 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor7143aab2011-09-01 17:04:32 +00001153
1154 // If this macro definition came from a PCH file, mark it
1155 // as having changed since serialization.
1156 if (MI->isFromAST())
1157 MI->setChangedAfterLoad();
1158}
1159
Chris Lattner141e71f2008-03-09 01:54:53 +00001160//===----------------------------------------------------------------------===//
1161// Preprocessor Include Directive Handling.
1162//===----------------------------------------------------------------------===//
1163
1164/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettdc201692012-06-22 05:46:07 +00001165/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattner141e71f2008-03-09 01:54:53 +00001166/// true if the input filename was in <>'s or false if it were in ""'s. The
1167/// caller is expected to provide a buffer that is large enough to hold the
1168/// spelling of the filename, but is also expected to handle the case when
1169/// this method decides to use a different buffer.
1170bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001171 StringRef &Buffer) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001172 // Get the text form of the filename.
Chris Lattnera1394812010-01-10 01:35:12 +00001173 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Chris Lattner141e71f2008-03-09 01:54:53 +00001175 // Make sure the filename is <x> or "x".
1176 bool isAngled;
Chris Lattnera1394812010-01-10 01:35:12 +00001177 if (Buffer[0] == '<') {
1178 if (Buffer.back() != '>') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001179 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001180 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001181 return true;
1182 }
1183 isAngled = true;
Chris Lattnera1394812010-01-10 01:35:12 +00001184 } else if (Buffer[0] == '"') {
1185 if (Buffer.back() != '"') {
Chris Lattner141e71f2008-03-09 01:54:53 +00001186 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001187 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001188 return true;
1189 }
1190 isAngled = false;
1191 } else {
1192 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001193 Buffer = StringRef();
Chris Lattner141e71f2008-03-09 01:54:53 +00001194 return true;
1195 }
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Chris Lattner141e71f2008-03-09 01:54:53 +00001197 // Diagnose #include "" as invalid.
Chris Lattnera1394812010-01-10 01:35:12 +00001198 if (Buffer.size() <= 2) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001199 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001200 Buffer = StringRef();
Chris Lattnera1394812010-01-10 01:35:12 +00001201 return true;
Chris Lattner141e71f2008-03-09 01:54:53 +00001202 }
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Chris Lattner141e71f2008-03-09 01:54:53 +00001204 // Skip the brackets.
Chris Lattnera1394812010-01-10 01:35:12 +00001205 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattner141e71f2008-03-09 01:54:53 +00001206 return isAngled;
1207}
1208
James Dennettdc201692012-06-22 05:46:07 +00001209/// \brief Handle cases where the \#include name is expanded from a macro
1210/// as multiple tokens, which need to be glued together.
1211///
1212/// This occurs for code like:
1213/// \code
1214/// \#define FOO <a/b.h>
1215/// \#include FOO
1216/// \endcode
Chris Lattner141e71f2008-03-09 01:54:53 +00001217/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1218///
1219/// This code concatenates and consumes tokens up to the '>' token. It returns
1220/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne84021552011-02-28 02:37:51 +00001221/// the EOD marker.
John Thompsona28cc092009-10-30 13:49:06 +00001222bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001223 SmallString<128> &FilenameBuffer,
Douglas Gregorecdcb882010-10-20 22:00:55 +00001224 SourceLocation &End) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001225 Token CurTok;
Mike Stump1eb44332009-09-09 15:08:12 +00001226
John Thompsona28cc092009-10-30 13:49:06 +00001227 Lex(CurTok);
Peter Collingbourne84021552011-02-28 02:37:51 +00001228 while (CurTok.isNot(tok::eod)) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001229 End = CurTok.getLocation();
1230
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001231 // FIXME: Provide code completion for #includes.
1232 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001233 setCodeCompletionReached();
Douglas Gregor25bb03b2010-12-09 23:35:36 +00001234 Lex(CurTok);
1235 continue;
1236 }
1237
Chris Lattner141e71f2008-03-09 01:54:53 +00001238 // Append the spelling of this token to the buffer. If there was a space
1239 // before it, add it now.
1240 if (CurTok.hasLeadingSpace())
1241 FilenameBuffer.push_back(' ');
Mike Stump1eb44332009-09-09 15:08:12 +00001242
Chris Lattner141e71f2008-03-09 01:54:53 +00001243 // Get the spelling of the token, directly into FilenameBuffer if possible.
1244 unsigned PreAppendSize = FilenameBuffer.size();
1245 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Chris Lattner141e71f2008-03-09 01:54:53 +00001247 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsona28cc092009-10-30 13:49:06 +00001248 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Chris Lattner141e71f2008-03-09 01:54:53 +00001250 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1251 if (BufPtr != &FilenameBuffer[PreAppendSize])
1252 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Chris Lattner141e71f2008-03-09 01:54:53 +00001254 // Resize FilenameBuffer to the correct size.
1255 if (CurTok.getLength() != ActualLen)
1256 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Chris Lattner141e71f2008-03-09 01:54:53 +00001258 // If we found the '>' marker, return success.
1259 if (CurTok.is(tok::greater))
1260 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001261
John Thompsona28cc092009-10-30 13:49:06 +00001262 Lex(CurTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001263 }
1264
Peter Collingbourne84021552011-02-28 02:37:51 +00001265 // If we hit the eod marker, emit an error and return true so that the caller
1266 // knows the EOD has been read.
John Thompsona28cc092009-10-30 13:49:06 +00001267 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001268 return true;
1269}
1270
James Dennettdc201692012-06-22 05:46:07 +00001271/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1272/// the file to be included from the lexer, then include it! This is a common
1273/// routine with functionality shared between \#include, \#include_next and
1274/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump1eb44332009-09-09 15:08:12 +00001275/// specifies the file to start searching from.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001276void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1277 Token &IncludeTok,
Chris Lattner141e71f2008-03-09 01:54:53 +00001278 const DirectoryLookup *LookupFrom,
1279 bool isImport) {
1280
1281 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001282 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Chris Lattner141e71f2008-03-09 01:54:53 +00001284 // Reserve a buffer to get the spelling.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001285 SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001286 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001287 SourceLocation End;
Douglas Gregore3a82562011-11-30 18:02:36 +00001288 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregorecdcb882010-10-20 22:00:55 +00001289
Chris Lattner141e71f2008-03-09 01:54:53 +00001290 switch (FilenameTok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +00001291 case tok::eod:
1292 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattner141e71f2008-03-09 01:54:53 +00001293 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Chris Lattner141e71f2008-03-09 01:54:53 +00001295 case tok::angle_string_literal:
Benjamin Kramerddeea562010-02-27 13:44:12 +00001296 case tok::string_literal:
1297 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregorecdcb882010-10-20 22:00:55 +00001298 End = FilenameTok.getLocation();
Douglas Gregore3a82562011-11-30 18:02:36 +00001299 CharEnd = End.getLocWithOffset(Filename.size());
Chris Lattner141e71f2008-03-09 01:54:53 +00001300 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Chris Lattner141e71f2008-03-09 01:54:53 +00001302 case tok::less:
1303 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1304 // case, glue the tokens together into FilenameBuffer and interpret those.
1305 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +00001306 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne84021552011-02-28 02:37:51 +00001307 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +00001308 Filename = FilenameBuffer.str();
Douglas Gregore3a82562011-11-30 18:02:36 +00001309 CharEnd = getLocForEndOfToken(End);
Chris Lattner141e71f2008-03-09 01:54:53 +00001310 break;
1311 default:
1312 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1313 DiscardUntilEndOfDirective();
1314 return;
1315 }
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Aaron Ballman4c55c542012-03-02 22:51:54 +00001317 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001318 bool isAngled =
Chris Lattnera1394812010-01-10 01:35:12 +00001319 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattner141e71f2008-03-09 01:54:53 +00001320 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1321 // error.
Chris Lattnera1394812010-01-10 01:35:12 +00001322 if (Filename.empty()) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001323 DiscardUntilEndOfDirective();
1324 return;
1325 }
Mike Stump1eb44332009-09-09 15:08:12 +00001326
Peter Collingbourne84021552011-02-28 02:37:51 +00001327 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001328 // we allow macros that expand to nothing after the filename, because this
1329 // falls into the category of "#include pp-tokens new-line" specified in
1330 // C99 6.10.2p4.
Daniel Dunbare013d682009-10-18 20:26:12 +00001331 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001332
1333 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +00001334 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1335 Diag(FilenameTok, diag::err_pp_include_too_deep);
1336 return;
1337 }
Mike Stump1eb44332009-09-09 15:08:12 +00001338
John McCall8dfac0b2011-09-30 05:12:12 +00001339 // Complain about attempts to #include files in an audit pragma.
1340 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1341 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1342 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1343
1344 // Immediately leave the pragma.
1345 PragmaARCCFCodeAuditedLoc = SourceLocation();
1346 }
1347
Aaron Ballman4c55c542012-03-02 22:51:54 +00001348 if (HeaderInfo.HasIncludeAliasMap()) {
1349 // Map the filename with the brackets still attached. If the name doesn't
1350 // map to anything, fall back on the filename we've already gotten the
1351 // spelling for.
1352 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1353 if (!NewName.empty())
1354 Filename = NewName;
1355 }
1356
Chris Lattner141e71f2008-03-09 01:54:53 +00001357 // Search include directories.
1358 const DirectoryLookup *CurDir;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001359 SmallString<1024> SearchPath;
1360 SmallString<1024> RelativePath;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001361 // We get the raw path only if we have 'Callbacks' to which we later pass
1362 // the path.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001363 Module *SuggestedModule = 0;
Chandler Carruthb5142bb2011-03-16 18:34:36 +00001364 const FileEntry *File = LookupFile(
Manuel Klimek74124942011-04-26 21:50:03 +00001365 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001366 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikie4e4d0842012-03-11 07:00:24 +00001367 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001368
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001369 if (Callbacks) {
1370 if (!File) {
1371 // Give the clients a chance to recover.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001372 SmallString<128> RecoveryPath;
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001373 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1374 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1375 // Add the recovery path to the list of search paths.
1376 DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
1377 HeaderInfo.AddSearchPath(DL, isAngled);
1378
1379 // Try the lookup again, skipping the cache.
1380 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikie4e4d0842012-03-11 07:00:24 +00001381 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor8cfbe6a2011-11-30 18:12:06 +00001382 /*SkipCache*/true);
1383 }
1384 }
1385 }
1386
1387 // Notify the callback object that we've seen an inclusion directive.
1388 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1389 End, SearchPath, RelativePath);
1390 }
1391
1392 if (File == 0) {
1393 if (!SuppressIncludeNotFoundError)
1394 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1395 return;
1396 }
1397
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001398 // If we are supposed to import a module rather than including the header,
1399 // do so now.
Douglas Gregorc69c42e2011-11-17 22:44:56 +00001400 if (SuggestedModule) {
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001401 // Compute the module access path corresponding to this module.
1402 // FIXME: Should we have a second loadModule() overload to avoid this
1403 // extra lookup step?
1404 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001405 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001406 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1407 FilenameTok.getLocation()));
1408 std::reverse(Path.begin(), Path.end());
1409
Douglas Gregore3a82562011-11-30 18:02:36 +00001410 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001411 SmallString<128> PathString;
Douglas Gregore3a82562011-11-30 18:02:36 +00001412 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1413 if (I)
1414 PathString += '.';
1415 PathString += Path[I].first->getName();
1416 }
1417 int IncludeKind = 0;
1418
1419 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1420 case tok::pp_include:
1421 IncludeKind = 0;
1422 break;
1423
1424 case tok::pp_import:
1425 IncludeKind = 1;
1426 break;
1427
Douglas Gregoredee9692011-11-30 18:03:26 +00001428 case tok::pp_include_next:
1429 IncludeKind = 2;
1430 break;
Douglas Gregore3a82562011-11-30 18:02:36 +00001431
1432 case tok::pp___include_macros:
1433 IncludeKind = 3;
1434 break;
1435
1436 default:
1437 llvm_unreachable("unknown include directive kind");
Douglas Gregore3a82562011-11-30 18:02:36 +00001438 }
1439
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001440 // Determine whether we are actually building the module that this
1441 // include directive maps to.
1442 bool BuildingImportedModule
David Blaikie4e4d0842012-03-11 07:00:24 +00001443 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001444
David Blaikie4e4d0842012-03-11 07:00:24 +00001445 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001446 // If we're not building the imported module, warn that we're going
1447 // to automatically turn this inclusion directive into a module import.
Douglas Gregorc13a34b2012-01-03 19:32:59 +00001448 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001449 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1450 /*IsTokenRange=*/false);
1451 Diag(HashLoc, diag::warn_auto_module_import)
1452 << IncludeKind << PathString
1453 << FixItHint::CreateReplacement(ReplaceRange,
Ted Kremenek32ad2ee2012-03-01 22:07:04 +00001454 "@__experimental_modules_import " + PathString.str().str() + ";");
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001455 }
Douglas Gregore3a82562011-11-30 18:02:36 +00001456
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001457 // Load the module.
Douglas Gregor5e356932011-12-01 17:11:21 +00001458 // If this was an #__include_macros directive, only make macros visible.
1459 Module::NameVisibilityKind Visibility
1460 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor305dc3e2011-12-20 00:28:52 +00001461 Module *Imported
1462 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1463 /*IsIncludeDirective=*/true);
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001464
1465 // If this header isn't part of the module we're building, we're done.
Douglas Gregor305dc3e2011-12-20 00:28:52 +00001466 if (!BuildingImportedModule && Imported)
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001467 return;
Douglas Gregorfba18aa2011-09-15 22:00:41 +00001468 }
1469
Chris Lattner72181832008-09-26 20:12:23 +00001470 // The #included file will be considered to be a system header if either it is
1471 // in a system include directory, or if the #includer is a system include
1472 // header.
Mike Stump1eb44332009-09-09 15:08:12 +00001473 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +00001474 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +00001475 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001477 // Ask HeaderInfo if we should enter this #include file. If not, #including
1478 // this file will have no effect.
1479 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001480 if (Callbacks)
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001481 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner6fbe3eb2010-04-19 20:44:31 +00001482 return;
1483 }
1484
Chris Lattner141e71f2008-03-09 01:54:53 +00001485 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisdb81d382012-03-27 18:47:48 +00001486 SourceLocation IncludePos = End;
1487 // If the filename string was the result of macro expansions, set the include
1488 // position on the file where it will be included and after the expansions.
1489 if (IncludePos.isMacroID())
1490 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1491 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned57b7ff2011-06-30 16:41:03 +00001492 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattner141e71f2008-03-09 01:54:53 +00001493
1494 // Finally, if all is good, enter the new file!
Chris Lattnere127a0d2010-04-20 20:35:58 +00001495 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001496}
1497
James Dennettdc201692012-06-22 05:46:07 +00001498/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattner141e71f2008-03-09 01:54:53 +00001499///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001500void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1501 Token &IncludeNextTok) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001502 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Chris Lattner141e71f2008-03-09 01:54:53 +00001504 // #include_next is like #include, except that we start searching after
1505 // the current found directory. If we can't do this, issue a
1506 // diagnostic.
1507 const DirectoryLookup *Lookup = CurDirLookup;
1508 if (isInPrimaryFile()) {
1509 Lookup = 0;
1510 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1511 } else if (Lookup == 0) {
1512 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1513 } else {
1514 // Start looking up in the next directory.
1515 ++Lookup;
1516 }
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Douglas Gregorecdcb882010-10-20 22:00:55 +00001518 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattner141e71f2008-03-09 01:54:53 +00001519}
1520
James Dennettdc201692012-06-22 05:46:07 +00001521/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman4207eda2012-03-18 03:10:37 +00001522void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1523 // The Microsoft #import directive takes a type library and generates header
1524 // files from it, and includes those. This is beyond the scope of what clang
1525 // does, so we ignore it and error out. However, #import can optionally have
1526 // trailing attributes that span multiple lines. We're going to eat those
1527 // so we can continue processing from there.
1528 Diag(Tok, diag::err_pp_import_directive_ms );
1529
1530 // Read tokens until we get to the end of the directive. Note that the
1531 // directive can be split over multiple lines using the backslash character.
1532 DiscardUntilEndOfDirective();
1533}
1534
James Dennettdc201692012-06-22 05:46:07 +00001535/// HandleImportDirective - Implements \#import.
Chris Lattner141e71f2008-03-09 01:54:53 +00001536///
Douglas Gregorecdcb882010-10-20 22:00:55 +00001537void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1538 Token &ImportTok) {
Aaron Ballman4207eda2012-03-18 03:10:37 +00001539 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1540 if (LangOpts.MicrosoftMode)
1541 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerb627c8d2009-03-06 04:28:03 +00001542 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman4207eda2012-03-18 03:10:37 +00001543 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00001544 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattner141e71f2008-03-09 01:54:53 +00001545}
1546
Chris Lattnerde076652009-04-08 18:46:40 +00001547/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1548/// pseudo directive in the predefines buffer. This handles it by sucking all
1549/// tokens through the preprocessor and discarding them (only keeping the side
1550/// effects on the preprocessor).
Douglas Gregorecdcb882010-10-20 22:00:55 +00001551void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1552 Token &IncludeMacrosTok) {
Chris Lattnerde076652009-04-08 18:46:40 +00001553 // This directive should only occur in the predefines buffer. If not, emit an
1554 // error and reject it.
1555 SourceLocation Loc = IncludeMacrosTok.getLocation();
1556 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1557 Diag(IncludeMacrosTok.getLocation(),
1558 diag::pp_include_macros_out_of_predefines);
1559 DiscardUntilEndOfDirective();
1560 return;
1561 }
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Chris Lattnerfd105112009-04-08 20:53:24 +00001563 // Treat this as a normal #include for checking purposes. If this is
1564 // successful, it will push a new lexer onto the include stack.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001565 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Chris Lattnerfd105112009-04-08 20:53:24 +00001567 Token TmpTok;
1568 do {
1569 Lex(TmpTok);
1570 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1571 } while (TmpTok.isNot(tok::hashhash));
Chris Lattnerde076652009-04-08 18:46:40 +00001572}
1573
Chris Lattner141e71f2008-03-09 01:54:53 +00001574//===----------------------------------------------------------------------===//
1575// Preprocessor Macro Directive Handling.
1576//===----------------------------------------------------------------------===//
1577
1578/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1579/// definition has just been read. Lex the rest of the arguments and the
1580/// closing ), updating MI with what we learn. Return true if an error occurs
1581/// parsing the arg list.
Abramo Bagnarae2e87682012-03-31 20:17:27 +00001582bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001583 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Chris Lattner141e71f2008-03-09 01:54:53 +00001585 while (1) {
1586 LexUnexpandedToken(Tok);
1587 switch (Tok.getKind()) {
1588 case tok::r_paren:
1589 // Found the end of the argument list.
Chris Lattnercf29e072009-02-20 22:31:31 +00001590 if (Arguments.empty()) // #define FOO()
Chris Lattner141e71f2008-03-09 01:54:53 +00001591 return false;
Chris Lattner141e71f2008-03-09 01:54:53 +00001592 // Otherwise we have #define FOO(A,)
1593 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1594 return true;
1595 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikie4e4d0842012-03-11 07:00:24 +00001596 if (!LangOpts.C99)
1597 Diag(Tok, LangOpts.CPlusPlus0x ?
Richard Smith661a9962011-10-15 01:18:56 +00001598 diag::warn_cxx98_compat_variadic_macro :
1599 diag::ext_variadic_macro);
Chris Lattner141e71f2008-03-09 01:54:53 +00001600
1601 // Lex the token after the identifier.
1602 LexUnexpandedToken(Tok);
1603 if (Tok.isNot(tok::r_paren)) {
1604 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1605 return true;
1606 }
1607 // Add the __VA_ARGS__ identifier as an argument.
1608 Arguments.push_back(Ident__VA_ARGS__);
1609 MI->setIsC99Varargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001610 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001611 return false;
Peter Collingbourne84021552011-02-28 02:37:51 +00001612 case tok::eod: // #define X(
Chris Lattner141e71f2008-03-09 01:54:53 +00001613 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1614 return true;
1615 default:
1616 // Handle keywords and identifiers here to accept things like
1617 // #define Foo(for) for.
1618 IdentifierInfo *II = Tok.getIdentifierInfo();
1619 if (II == 0) {
1620 // #define X(1
1621 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1622 return true;
1623 }
1624
1625 // If this is already used as an argument, it is used multiple times (e.g.
1626 // #define X(A,A.
Mike Stump1eb44332009-09-09 15:08:12 +00001627 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattner141e71f2008-03-09 01:54:53 +00001628 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +00001629 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +00001630 return true;
1631 }
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Chris Lattner141e71f2008-03-09 01:54:53 +00001633 // Add the argument to the macro info.
1634 Arguments.push_back(II);
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Chris Lattner141e71f2008-03-09 01:54:53 +00001636 // Lex the token after the identifier.
1637 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Chris Lattner141e71f2008-03-09 01:54:53 +00001639 switch (Tok.getKind()) {
1640 default: // #define X(A B
1641 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1642 return true;
1643 case tok::r_paren: // #define X(A)
Chris Lattner685befe2009-02-20 22:46:43 +00001644 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001645 return false;
1646 case tok::comma: // #define X(A,
1647 break;
1648 case tok::ellipsis: // #define X(A... -> GCC extension
1649 // Diagnose extension.
1650 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Chris Lattner141e71f2008-03-09 01:54:53 +00001652 // Lex the token after the identifier.
1653 LexUnexpandedToken(Tok);
1654 if (Tok.isNot(tok::r_paren)) {
1655 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1656 return true;
1657 }
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Chris Lattner141e71f2008-03-09 01:54:53 +00001659 MI->setIsGNUVarargs();
Chris Lattner685befe2009-02-20 22:46:43 +00001660 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattner141e71f2008-03-09 01:54:53 +00001661 return false;
1662 }
1663 }
1664 }
1665}
1666
James Dennettdc201692012-06-22 05:46:07 +00001667/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattner141e71f2008-03-09 01:54:53 +00001668/// line then lets the caller lex the next real token.
1669void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1670 ++NumDefined;
1671
1672 Token MacroNameTok;
1673 ReadMacroName(MacroNameTok, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Chris Lattner141e71f2008-03-09 01:54:53 +00001675 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001676 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001677 return;
1678
Chris Lattner2451b522009-04-21 04:46:33 +00001679 Token LastTok = MacroNameTok;
1680
Chris Lattner141e71f2008-03-09 01:54:53 +00001681 // If we are supposed to keep comments in #defines, reenable comment saving
1682 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001683 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Chris Lattner141e71f2008-03-09 01:54:53 +00001685 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001686 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Chris Lattner141e71f2008-03-09 01:54:53 +00001688 Token Tok;
1689 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Chris Lattner141e71f2008-03-09 01:54:53 +00001691 // If this is a function-like macro definition, parse the argument list,
1692 // marking each of the identifiers as being used as macro arguments. Also,
1693 // check other constraints on the first token of the macro body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001694 if (Tok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001695 // If there is no body to this macro, we have no special handling here.
Chris Lattner6272bcf2009-04-18 02:23:25 +00001696 } else if (Tok.hasLeadingSpace()) {
1697 // This is a normal token with leading space. Clear the leading space
1698 // marker on the first token to get proper expansion.
1699 Tok.clearFlag(Token::LeadingSpace);
1700 } else if (Tok.is(tok::l_paren)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001701 // This is a function-like macro definition. Read the argument list.
1702 MI->setIsFunctionLike();
Abramo Bagnarae2e87682012-03-31 20:17:27 +00001703 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001704 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001705 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001706 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001707 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001708 DiscardUntilEndOfDirective();
1709 return;
1710 }
1711
Chris Lattner8fde5972009-04-19 18:26:34 +00001712 // If this is a definition of a variadic C99 function-like macro, not using
1713 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Chris Lattner8fde5972009-04-19 18:26:34 +00001715 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1716 // This gets unpoisoned where it is allowed.
1717 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1718 if (MI->isC99Varargs())
1719 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Chris Lattner141e71f2008-03-09 01:54:53 +00001721 // Read the first token after the arg list for down below.
1722 LexUnexpandedToken(Tok);
David Blaikie4e4d0842012-03-11 07:00:24 +00001723 } else if (LangOpts.C99 || LangOpts.CPlusPlus0x) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001724 // C99 requires whitespace between the macro definition and the body. Emit
1725 // a diagnostic for something like "#define X+".
Chris Lattner6272bcf2009-04-18 02:23:25 +00001726 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001727 } else {
Chris Lattner6272bcf2009-04-18 02:23:25 +00001728 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1729 // first character of a replacement list is not a character required by
1730 // subclause 5.2.1, then there shall be white-space separation between the
1731 // identifier and the replacement list.". 5.2.1 lists this set:
1732 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1733 // is irrelevant here.
1734 bool isInvalid = false;
1735 if (Tok.is(tok::at)) // @ is not in the list above.
1736 isInvalid = true;
1737 else if (Tok.is(tok::unknown)) {
1738 // If we have an unknown token, it is something strange like "`". Since
1739 // all of valid characters would have lexed into a single character
1740 // token of some sort, we know this is not a valid case.
1741 isInvalid = true;
1742 }
1743 if (isInvalid)
1744 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1745 else
1746 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattner141e71f2008-03-09 01:54:53 +00001747 }
Chris Lattner2451b522009-04-21 04:46:33 +00001748
Peter Collingbourne84021552011-02-28 02:37:51 +00001749 if (!Tok.is(tok::eod))
Chris Lattner2451b522009-04-21 04:46:33 +00001750 LastTok = Tok;
1751
Chris Lattner141e71f2008-03-09 01:54:53 +00001752 // Read the rest of the macro body.
1753 if (MI->isObjectLike()) {
1754 // Object-like macros are very simple, just read their body.
Peter Collingbourne84021552011-02-28 02:37:51 +00001755 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001756 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001757 MI->AddTokenToBody(Tok);
1758 // Get the next token of the macro.
1759 LexUnexpandedToken(Tok);
1760 }
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Chris Lattner141e71f2008-03-09 01:54:53 +00001762 } else {
Chris Lattner32404692009-05-25 17:16:10 +00001763 // Otherwise, read the body of a function-like macro. While we are at it,
1764 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1765 // parameters in function-like macro expansions.
Peter Collingbourne84021552011-02-28 02:37:51 +00001766 while (Tok.isNot(tok::eod)) {
Chris Lattner2451b522009-04-21 04:46:33 +00001767 LastTok = Tok;
Chris Lattner141e71f2008-03-09 01:54:53 +00001768
Chris Lattner141e71f2008-03-09 01:54:53 +00001769 if (Tok.isNot(tok::hash)) {
Chris Lattner32404692009-05-25 17:16:10 +00001770 MI->AddTokenToBody(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Chris Lattner141e71f2008-03-09 01:54:53 +00001772 // Get the next token of the macro.
1773 LexUnexpandedToken(Tok);
1774 continue;
1775 }
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Chris Lattner141e71f2008-03-09 01:54:53 +00001777 // Get the next token of the macro.
1778 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Chris Lattner32404692009-05-25 17:16:10 +00001780 // Check for a valid macro arg identifier.
1781 if (Tok.getIdentifierInfo() == 0 ||
1782 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1783
1784 // If this is assembler-with-cpp mode, we accept random gibberish after
1785 // the '#' because '#' is often a comment character. However, change
1786 // the kind of the token to tok::unknown so that the preprocessor isn't
1787 // confused.
David Blaikie4e4d0842012-03-11 07:00:24 +00001788 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner32404692009-05-25 17:16:10 +00001789 LastTok.setKind(tok::unknown);
1790 } else {
1791 Diag(Tok, diag::err_pp_stringize_not_parameter);
1792 ReleaseMacroInfo(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Chris Lattner32404692009-05-25 17:16:10 +00001794 // Disable __VA_ARGS__ again.
1795 Ident__VA_ARGS__->setIsPoisoned(true);
1796 return;
1797 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001798 }
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Chris Lattner32404692009-05-25 17:16:10 +00001800 // Things look ok, add the '#' and param name tokens to the macro.
1801 MI->AddTokenToBody(LastTok);
Chris Lattner141e71f2008-03-09 01:54:53 +00001802 MI->AddTokenToBody(Tok);
Chris Lattner32404692009-05-25 17:16:10 +00001803 LastTok = Tok;
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Chris Lattner141e71f2008-03-09 01:54:53 +00001805 // Get the next token of the macro.
1806 LexUnexpandedToken(Tok);
1807 }
1808 }
Mike Stump1eb44332009-09-09 15:08:12 +00001809
1810
Chris Lattner141e71f2008-03-09 01:54:53 +00001811 // Disable __VA_ARGS__ again.
1812 Ident__VA_ARGS__->setIsPoisoned(true);
1813
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001814 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattner141e71f2008-03-09 01:54:53 +00001815 // replacement list.
1816 unsigned NumTokens = MI->getNumTokens();
1817 if (NumTokens != 0) {
1818 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1819 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001820 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001821 return;
1822 }
1823 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1824 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001825 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001826 return;
1827 }
1828 }
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Chris Lattner2451b522009-04-21 04:46:33 +00001830 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Chris Lattner141e71f2008-03-09 01:54:53 +00001832 // Finally, if this identifier already had a macro defined for it, verify that
1833 // the macro bodies are identical and free the old definition.
1834 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001835 // It is very common for system headers to have tons of macro redefinitions
1836 // and for warnings to be disabled in system headers. If this is the case,
1837 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner7f549df2009-03-13 21:17:23 +00001838 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner41c3ae12009-01-16 19:50:11 +00001839 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001840 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner41c3ae12009-01-16 19:50:11 +00001841 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001842
Chris Lattnerf47724b2010-08-17 15:55:45 +00001843 // Macros must be identical. This means all tokens and whitespace
Chris Lattner41c3ae12009-01-16 19:50:11 +00001844 // separation must be the same. C99 6.10.3.2.
Chris Lattnerf47724b2010-08-17 15:55:45 +00001845 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedmana7e68452010-08-22 01:00:03 +00001846 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001847 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1848 << MacroNameTok.getIdentifierInfo();
1849 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1850 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001851 }
Argyrios Kyrtzidisa33e0502011-01-18 19:50:15 +00001852 if (OtherMI->isWarnIfUnused())
1853 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek0ea76722008-12-15 19:56:42 +00001854 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001855 }
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Chris Lattner141e71f2008-03-09 01:54:53 +00001857 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001859 assert(!MI->isUsed());
1860 // If we need warning for not using the macro, add its location in the
1861 // warn-because-unused-macro set. If it gets used it will be removed from set.
1862 if (isInPrimaryFile() && // don't warn for include'd macros.
1863 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikied6471f72011-09-25 23:23:43 +00001864 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001865 MI->setIsWarnIfUnused(true);
1866 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1867 }
1868
Chris Lattnerf4a72b02009-04-12 01:39:54 +00001869 // If the callbacks want to know, tell them about the macro definition.
1870 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001871 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001872}
1873
James Dennettdc201692012-06-22 05:46:07 +00001874/// HandleUndefDirective - Implements \#undef.
Chris Lattner141e71f2008-03-09 01:54:53 +00001875///
1876void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1877 ++NumUndefined;
1878
1879 Token MacroNameTok;
1880 ReadMacroName(MacroNameTok, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Chris Lattner141e71f2008-03-09 01:54:53 +00001882 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001883 if (MacroNameTok.is(tok::eod))
Chris Lattner141e71f2008-03-09 01:54:53 +00001884 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Chris Lattner141e71f2008-03-09 01:54:53 +00001886 // Check to see if this is the last token on the #undef line.
Chris Lattner35410d52009-04-14 05:07:49 +00001887 CheckEndOfDirective("undef");
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Chris Lattner141e71f2008-03-09 01:54:53 +00001889 // Okay, we finally have a valid identifier to undef.
1890 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Chris Lattner141e71f2008-03-09 01:54:53 +00001892 // If the macro is not defined, this is a noop undef, just return.
1893 if (MI == 0) return;
1894
Argyrios Kyrtzidis1f8dcfc2011-07-11 20:39:47 +00001895 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattner141e71f2008-03-09 01:54:53 +00001896 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner41c17472009-04-21 03:42:09 +00001897
1898 // If the callbacks want to know, tell them about the macro #undef.
1899 if (Callbacks)
Craig Silverstein2aa92672010-11-19 21:33:15 +00001900 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattner41c17472009-04-21 03:42:09 +00001901
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001902 if (MI->isWarnIfUnused())
1903 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1904
Chris Lattner141e71f2008-03-09 01:54:53 +00001905 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001906 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001907 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1908}
1909
1910
1911//===----------------------------------------------------------------------===//
1912// Preprocessor Conditional Directive Handling.
1913//===----------------------------------------------------------------------===//
1914
James Dennettdc201692012-06-22 05:46:07 +00001915/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
1916/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
1917/// true if any tokens have been returned or pp-directives activated before this
1918/// \#ifndef has been lexed.
Chris Lattner141e71f2008-03-09 01:54:53 +00001919///
1920void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1921 bool ReadAnyTokensBeforeDirective) {
1922 ++NumIf;
1923 Token DirectiveTok = Result;
1924
1925 Token MacroNameTok;
1926 ReadMacroName(MacroNameTok);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Chris Lattner141e71f2008-03-09 01:54:53 +00001928 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne84021552011-02-28 02:37:51 +00001929 if (MacroNameTok.is(tok::eod)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001930 // Skip code until we get to #endif. This helps with recovery by not
1931 // emitting an error when the #endif is reached.
1932 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1933 /*Foundnonskip*/false, /*FoundElse*/false);
1934 return;
1935 }
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Chris Lattner141e71f2008-03-09 01:54:53 +00001937 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner35410d52009-04-14 05:07:49 +00001938 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattner141e71f2008-03-09 01:54:53 +00001939
Chris Lattner13d283d2010-02-12 08:03:27 +00001940 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1941 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001942
Ted Kremenek60e45d42008-11-18 00:34:22 +00001943 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001944 // If the start of a top-level #ifdef and if the macro is not defined,
1945 // inform MIOpt that this might be the start of a proper include guard.
1946 // Otherwise it is some other form of unknown conditional which we can't
1947 // handle.
1948 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001949 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattner13d283d2010-02-12 08:03:27 +00001950 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattner141e71f2008-03-09 01:54:53 +00001951 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001952 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001953 }
1954
Chris Lattner141e71f2008-03-09 01:54:53 +00001955 // If there is a macro, process it.
1956 if (MI) // Mark it used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001957 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00001959 if (Callbacks) {
1960 if (isIfndef)
1961 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok);
1962 else
1963 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok);
1964 }
1965
Chris Lattner141e71f2008-03-09 01:54:53 +00001966 // Should we include the stuff contained by this directive?
1967 if (!MI == isIfndef) {
1968 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner1d9c54d2009-12-14 04:54:40 +00001969 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1970 /*wasskip*/false, /*foundnonskip*/true,
1971 /*foundelse*/false);
Chris Lattner141e71f2008-03-09 01:54:53 +00001972 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00001973 // No, skip the contents of this block.
Chris Lattner141e71f2008-03-09 01:54:53 +00001974 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001975 /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001976 /*FoundElse*/false);
1977 }
1978}
1979
James Dennettdc201692012-06-22 05:46:07 +00001980/// HandleIfDirective - Implements the \#if directive.
Chris Lattner141e71f2008-03-09 01:54:53 +00001981///
1982void Preprocessor::HandleIfDirective(Token &IfToken,
1983 bool ReadAnyTokensBeforeDirective) {
1984 ++NumIf;
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Craig Silverstein08985b92010-11-06 01:19:03 +00001986 // Parse and evaluate the conditional expression.
Chris Lattner141e71f2008-03-09 01:54:53 +00001987 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein08985b92010-11-06 01:19:03 +00001988 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1989 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1990 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes0049db62008-06-01 18:31:24 +00001991
1992 // If this condition is equivalent to #ifndef X, and if this is the first
1993 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001994 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner13d283d2010-02-12 08:03:27 +00001995 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001996 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001997 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001998 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001999 }
2000
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002001 if (Callbacks)
2002 Callbacks->If(IfToken.getLocation(),
2003 SourceRange(ConditionalBegin, ConditionalEnd));
2004
Chris Lattner141e71f2008-03-09 01:54:53 +00002005 // Should we include the stuff contained by this directive?
2006 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002007 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002008 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002009 /*foundnonskip*/true, /*foundelse*/false);
2010 } else {
Craig Silverstein08985b92010-11-06 01:19:03 +00002011 // No, skip the contents of this block.
Mike Stump1eb44332009-09-09 15:08:12 +00002012 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00002013 /*FoundElse*/false);
2014 }
2015}
2016
James Dennettdc201692012-06-22 05:46:07 +00002017/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattner141e71f2008-03-09 01:54:53 +00002018///
2019void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2020 ++NumEndif;
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Chris Lattner141e71f2008-03-09 01:54:53 +00002022 // Check that this is the whole directive.
Chris Lattner35410d52009-04-14 05:07:49 +00002023 CheckEndOfDirective("endif");
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Chris Lattner141e71f2008-03-09 01:54:53 +00002025 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00002026 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00002027 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00002028 Diag(EndifToken, diag::err_pp_endif_without_if);
2029 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00002030 }
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Chris Lattner141e71f2008-03-09 01:54:53 +00002032 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002033 if (CurPPLexer->getConditionalStackDepth() == 0)
2034 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Ted Kremenek60e45d42008-11-18 00:34:22 +00002036 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00002037 "This code should only be reachable in the non-skipping case!");
Craig Silverstein08985b92010-11-06 01:19:03 +00002038
2039 if (Callbacks)
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002040 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +00002041}
2042
James Dennettdc201692012-06-22 05:46:07 +00002043/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein08985b92010-11-06 01:19:03 +00002044///
Chris Lattner141e71f2008-03-09 01:54:53 +00002045void Preprocessor::HandleElseDirective(Token &Result) {
2046 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Chris Lattner141e71f2008-03-09 01:54:53 +00002048 // #else directive in a non-skipping conditional... start skipping.
Chris Lattner35410d52009-04-14 05:07:49 +00002049 CheckEndOfDirective("else");
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Chris Lattner141e71f2008-03-09 01:54:53 +00002051 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00002052 if (CurPPLexer->popConditionalLevel(CI)) {
2053 Diag(Result, diag::pp_err_else_without_if);
2054 return;
2055 }
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Chris Lattner141e71f2008-03-09 01:54:53 +00002057 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002058 if (CurPPLexer->getConditionalStackDepth() == 0)
2059 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00002060
2061 // If this is a #else with a #else before it, report the error.
2062 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002064 if (Callbacks)
2065 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2066
Craig Silverstein08985b92010-11-06 01:19:03 +00002067 // Finally, skip the rest of the contents of this block.
2068 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00002069 /*FoundElse*/true, Result.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00002070}
2071
James Dennettdc201692012-06-22 05:46:07 +00002072/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein08985b92010-11-06 01:19:03 +00002073///
Chris Lattner141e71f2008-03-09 01:54:53 +00002074void Preprocessor::HandleElifDirective(Token &ElifToken) {
2075 ++NumElse;
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Chris Lattner141e71f2008-03-09 01:54:53 +00002077 // #elif directive in a non-skipping conditional... start skipping.
2078 // We don't care what the condition is, because we will always skip it (since
2079 // the block immediately before it was included).
Craig Silverstein08985b92010-11-06 01:19:03 +00002080 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00002081 DiscardUntilEndOfDirective();
Craig Silverstein08985b92010-11-06 01:19:03 +00002082 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattner141e71f2008-03-09 01:54:53 +00002083
2084 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00002085 if (CurPPLexer->popConditionalLevel(CI)) {
2086 Diag(ElifToken, diag::pp_err_elif_without_if);
2087 return;
2088 }
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Chris Lattner141e71f2008-03-09 01:54:53 +00002090 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00002091 if (CurPPLexer->getConditionalStackDepth() == 0)
2092 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Chris Lattner141e71f2008-03-09 01:54:53 +00002094 // If this is a #elif with a #else before it, report the error.
2095 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisbb660662012-03-05 05:48:09 +00002096
2097 if (Callbacks)
2098 Callbacks->Elif(ElifToken.getLocation(),
2099 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattner141e71f2008-03-09 01:54:53 +00002100
Craig Silverstein08985b92010-11-06 01:19:03 +00002101 // Finally, skip the rest of the contents of this block.
2102 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis6b4ff042011-09-27 17:32:05 +00002103 /*FoundElse*/CI.FoundElse,
2104 ElifToken.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00002105}