blob: 74376e47acbb86bcb4d3b9a5ac4cc4f57d822a17 [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattnerf64b3522008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner710bb872009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/LexDiagnostic.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/ModuleLoader.h"
24#include "clang/Lex/Pragma.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000025#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000026#include "llvm/Support/ErrorHandling.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000027#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000028using namespace clang;
29
30//===----------------------------------------------------------------------===//
31// Utility Methods for Preprocessor Directive Handling.
32//===----------------------------------------------------------------------===//
33
Chris Lattnerc0a585d2010-08-17 15:55:45 +000034MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000035 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000036
Ted Kremenekc8456f82010-10-19 22:15:20 +000037 if (MICache) {
38 MIChain = MICache;
39 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000040 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000041 else {
42 MIChain = BP.Allocate<MacroInfoChain>();
43 }
44
45 MIChain->Next = MIChainHead;
46 MIChain->Prev = 0;
47 if (MIChainHead)
48 MIChainHead->Prev = MIChain;
49 MIChainHead = MIChain;
50
51 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000052}
53
54MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
55 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000056 new (MI) MacroInfo(L);
57 return MI;
58}
59
Chris Lattnerc0a585d2010-08-17 15:55:45 +000060MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
61 MacroInfo *MI = AllocateMacroInfo();
62 new (MI) MacroInfo(MacroToClone, BP);
63 return MI;
64}
65
James Dennettf6333ac2012-06-22 05:46:07 +000066/// \brief Release the specified MacroInfo to be reused for allocating
67/// new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +000068void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +000069 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
70 if (MacroInfoChain *Prev = MIChain->Prev) {
71 MacroInfoChain *Next = MIChain->Next;
72 Prev->Next = Next;
73 if (Next)
74 Next->Prev = Prev;
75 }
76 else {
77 assert(MIChainHead == MIChain);
78 MIChainHead = MIChain->Next;
79 MIChainHead->Prev = 0;
80 }
81 MIChain->Next = MICache;
82 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +000083
Ted Kremenekc8456f82010-10-19 22:15:20 +000084 MI->Destroy();
85}
Chris Lattner666f7a42009-02-20 22:19:20 +000086
James Dennettf6333ac2012-06-22 05:46:07 +000087/// \brief Read and discard all tokens remaining on the current line until
88/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000089void Preprocessor::DiscardUntilEndOfDirective() {
90 Token Tmp;
91 do {
92 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000093 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000094 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000095}
96
James Dennettf6333ac2012-06-22 05:46:07 +000097/// \brief Lex and validate a macro name, which occurs after a
98/// \#define or \#undef.
99///
100/// This sets the token kind to eod and discards the rest
101/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
102/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
103/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000104void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
105 // Read the token, don't allow macro expansion on it.
106 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000107
Douglas Gregor12785102010-08-24 20:21:13 +0000108 if (MacroNameTok.is(tok::code_completion)) {
109 if (CodeComplete)
110 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000111 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000112 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000113 }
114
Chris Lattnerf64b3522008-03-09 01:54:53 +0000115 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000116 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000117 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
118 return;
119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Chris Lattnerf64b3522008-03-09 01:54:53 +0000121 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
122 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000123 bool Invalid = false;
124 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
125 if (Invalid)
126 return;
Nico Weber2e686202012-02-29 22:54:43 +0000127
Chris Lattner77c76ae2008-12-13 20:12:40 +0000128 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000129
130 // Allow #defining |and| and friends in microsoft mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000131 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weber2e686202012-02-29 22:54:43 +0000132 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
133 return;
134 }
135
Chris Lattner77c76ae2008-12-13 20:12:40 +0000136 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000137 // C++ 2.5p2: Alternative tokens behave the same as its primary token
138 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000139 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000140 else
141 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
142 // Fall through on error.
143 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
144 // Error if defining "defined": C99 6.10.8.4.
145 Diag(MacroNameTok, diag::err_defined_macro_name);
146 } else if (isDefineUndef && II->hasMacroDefinition() &&
147 getMacroInfo(II)->isBuiltinMacro()) {
148 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
149 if (isDefineUndef == 1)
150 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
151 else
152 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
153 } else {
154 // Okay, we got a good identifier node. Return it.
155 return;
156 }
Mike Stump11289f42009-09-09 15:08:12 +0000157
Chris Lattnerf64b3522008-03-09 01:54:53 +0000158 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000159 // token kind to tok::eod.
160 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000161 return DiscardUntilEndOfDirective();
162}
163
James Dennettf6333ac2012-06-22 05:46:07 +0000164/// \brief Ensure that the next token is a tok::eod token.
165///
166/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000167/// true, then we consider macros that expand to zero tokens as being ok.
168void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000169 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000170 // Lex unexpanded tokens for most directives: macros might expand to zero
171 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
172 // #line) allow empty macros.
173 if (EnableMacros)
174 Lex(Tmp);
175 else
176 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000177
Chris Lattnerf64b3522008-03-09 01:54:53 +0000178 // There should be no tokens after the directive, but we allow them as an
179 // extension.
180 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
181 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000182
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000183 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000184 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000185 // or if this is a macro-style preprocessing directive, because it is more
186 // trouble than it is worth to insert /**/ and check that there is no /**/
187 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000188 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000189 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000190 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000191 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
192 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000193 DiscardUntilEndOfDirective();
194 }
195}
196
197
198
James Dennettf6333ac2012-06-22 05:46:07 +0000199/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
200/// decided that the subsequent tokens are in the \#if'd out portion of the
201/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000202/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000203/// this \#if directive, so \#else/\#elif blocks should never be entered.
204/// If ElseOk is true, then \#else directives are ok, if not, then we have
205/// already seen one so a \#else directive is a duplicate. When this returns,
206/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000207void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
208 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000209 bool FoundElse,
210 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000211 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000212 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000213
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000214 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000215 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000216
Ted Kremenek56572ab2008-12-12 18:34:08 +0000217 if (CurPTHLexer) {
218 PTHSkipExcludedConditionalBlock();
219 return;
220 }
Mike Stump11289f42009-09-09 15:08:12 +0000221
Chris Lattnerf64b3522008-03-09 01:54:53 +0000222 // Enter raw mode to disable identifier lookup (and thus macro expansion),
223 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000224 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000225 Token Tok;
226 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000227 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000228
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000229 if (Tok.is(tok::code_completion)) {
230 if (CodeComplete)
231 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000232 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000233 continue;
234 }
235
Chris Lattnerf64b3522008-03-09 01:54:53 +0000236 // If this is the end of the buffer, we have an error.
237 if (Tok.is(tok::eof)) {
238 // Emit errors for each unterminated conditional on the stack, including
239 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000240 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000241 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000242 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
243 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000244 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000245 }
246
Chris Lattnerf64b3522008-03-09 01:54:53 +0000247 // Just return and let the caller lex after this #include.
248 break;
249 }
Mike Stump11289f42009-09-09 15:08:12 +0000250
Chris Lattnerf64b3522008-03-09 01:54:53 +0000251 // If this token is not a preprocessor directive, just skip it.
252 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
253 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattnerf64b3522008-03-09 01:54:53 +0000255 // We just parsed a # character at the start of a line, so we're in
256 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000257 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000258 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000259 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000260
Mike Stump11289f42009-09-09 15:08:12 +0000261
Chris Lattnerf64b3522008-03-09 01:54:53 +0000262 // Read the next token, the directive flavor.
263 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000264
Chris Lattnerf64b3522008-03-09 01:54:53 +0000265 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
266 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000267 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000268 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000269 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000270 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000271 continue;
272 }
273
274 // If the first letter isn't i or e, it isn't intesting to us. We know that
275 // this is safe in the face of spelling differences, because there is no way
276 // to spell an i/e in a strange way that is another letter. Skipping this
277 // allows us to avoid looking up the identifier info for #define/#undef and
278 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000279 const char *RawCharData = Tok.getRawIdentifierData();
280
Chris Lattnerf64b3522008-03-09 01:54:53 +0000281 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000282 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000283 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000284 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000285 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000286 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000287 continue;
288 }
Mike Stump11289f42009-09-09 15:08:12 +0000289
Chris Lattnerf64b3522008-03-09 01:54:53 +0000290 // Get the identifier name without trigraphs or embedded newlines. Note
291 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
292 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000293 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000294 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000295 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000296 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000297 } else {
298 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000299 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000300 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000301 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000302 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000303 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000304 continue;
305 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000306 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000307 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000308 }
Mike Stump11289f42009-09-09 15:08:12 +0000309
Benjamin Kramer144884642009-12-31 13:32:38 +0000310 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000311 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000312 if (Sub.empty() || // "if"
313 Sub == "def" || // "ifdef"
314 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000315 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
316 // bother parsing the condition.
317 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000318 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000319 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000320 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000321 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000322 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000323 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000324 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000325 PPConditionalInfo CondInfo;
326 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000327 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000328 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000330
Chris Lattnerf64b3522008-03-09 01:54:53 +0000331 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000332 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000333 // Restore the value of LexingRawMode so that trailing comments
334 // are handled correctly, if we've reached the outermost block.
335 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000336 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000337 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000338 if (Callbacks)
339 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000340 break;
Richard Smithd0124572012-06-21 00:35:03 +0000341 } else {
342 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000343 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000344 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000345 // #else directive in a skipping conditional. If not in some other
346 // skipping conditional, and if #else hasn't already been seen, enter it
347 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000348 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000349
Chris Lattnerf64b3522008-03-09 01:54:53 +0000350 // If this is a #else with a #else before it, report the error.
351 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000352
Chris Lattnerf64b3522008-03-09 01:54:53 +0000353 // Note that we've seen a #else in this conditional.
354 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000355
Chris Lattnerf64b3522008-03-09 01:54:53 +0000356 // If the conditional is at the top level, and the #if block wasn't
357 // entered, enter the #else block now.
358 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
359 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000360 // Restore the value of LexingRawMode so that trailing comments
361 // are handled correctly.
362 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000363 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000364 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000365 if (Callbacks)
366 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000367 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000368 } else {
369 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000370 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000371 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000372 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000373
374 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000375 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000376 // If this is in a skipping block or if we're already handled this #if
377 // block, don't bother parsing the condition.
378 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
379 DiscardUntilEndOfDirective();
380 ShouldEnter = false;
381 } else {
382 // Restore the value of LexingRawMode so that identifiers are
383 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000384 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
385 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 IdentifierInfo *IfNDefMacro = 0;
387 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000388 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000389 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000390 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000391
Chris Lattnerf64b3522008-03-09 01:54:53 +0000392 // If this is a #elif with a #else before it, report the error.
393 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattnerf64b3522008-03-09 01:54:53 +0000395 // If this condition is true, enter it!
396 if (ShouldEnter) {
397 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000398 if (Callbacks)
399 Callbacks->Elif(Tok.getLocation(),
400 SourceRange(ConditionalBegin, ConditionalEnd),
401 CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000402 break;
403 }
404 }
405 }
Mike Stump11289f42009-09-09 15:08:12 +0000406
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000407 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000408 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000409 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000410 }
411
412 // Finally, if we are out of the conditional (saw an #endif or ran off the end
413 // of the file, just stop skipping and return to lexing whatever came after
414 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000415 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000416
417 if (Callbacks) {
418 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
419 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
420 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000421}
422
Ted Kremenek56572ab2008-12-12 18:34:08 +0000423void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000424
425 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000426 assert(CurPTHLexer);
427 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000428
Ted Kremenek56572ab2008-12-12 18:34:08 +0000429 // Skip to the next '#else', '#elif', or #endif.
430 if (CurPTHLexer->SkipBlock()) {
431 // We have reached an #endif. Both the '#' and 'endif' tokens
432 // have been consumed by the PTHLexer. Just pop off the condition level.
433 PPConditionalInfo CondInfo;
434 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000435 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000436 assert(!InCond && "Can't be skipping if not in a conditional!");
437 break;
438 }
Mike Stump11289f42009-09-09 15:08:12 +0000439
Ted Kremenek56572ab2008-12-12 18:34:08 +0000440 // We have reached a '#else' or '#elif'. Lex the next token to get
441 // the directive flavor.
442 Token Tok;
443 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000444
Ted Kremenek56572ab2008-12-12 18:34:08 +0000445 // We can actually look up the IdentifierInfo here since we aren't in
446 // raw mode.
447 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
448
449 if (K == tok::pp_else) {
450 // #else: Enter the else condition. We aren't in a nested condition
451 // since we skip those. We're always in the one matching the last
452 // blocked we skipped.
453 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
454 // Note that we've seen a #else in this conditional.
455 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000456
Ted Kremenek56572ab2008-12-12 18:34:08 +0000457 // If the #if block wasn't entered then enter the #else block now.
458 if (!CondInfo.FoundNonSkip) {
459 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000460
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000461 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000462 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000463 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000464 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000465
Ted Kremenek56572ab2008-12-12 18:34:08 +0000466 break;
467 }
Mike Stump11289f42009-09-09 15:08:12 +0000468
Ted Kremenek56572ab2008-12-12 18:34:08 +0000469 // Otherwise skip this block.
470 continue;
471 }
Mike Stump11289f42009-09-09 15:08:12 +0000472
Ted Kremenek56572ab2008-12-12 18:34:08 +0000473 assert(K == tok::pp_elif);
474 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
475
476 // If this is a #elif with a #else before it, report the error.
477 if (CondInfo.FoundElse)
478 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000479
Ted Kremenek56572ab2008-12-12 18:34:08 +0000480 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000481 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000482 if (CondInfo.FoundNonSkip)
483 continue;
484
485 // Evaluate the condition of the #elif.
486 IdentifierInfo *IfNDefMacro = 0;
487 CurPTHLexer->ParsingPreprocessorDirective = true;
488 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
489 CurPTHLexer->ParsingPreprocessorDirective = false;
490
491 // If this condition is true, enter it!
492 if (ShouldEnter) {
493 CondInfo.FoundNonSkip = true;
494 break;
495 }
496
497 // Otherwise, skip this block and go to the next one.
498 continue;
499 }
500}
501
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000502const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000503 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000504 bool isAngled,
505 const DirectoryLookup *FromDir,
506 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000507 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000508 SmallVectorImpl<char> *RelativePath,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000509 Module **SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000510 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000511 // If the header lookup mechanism may be relative to the current file, pass in
512 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000513 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000514 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000515 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000516 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000517
Chris Lattner022923a2009-02-04 19:45:07 +0000518 // If there is no file entry associated with this file, it must be the
519 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000520 // it won't be scanned for preprocessor directives. If we have the
521 // predefines buffer, resolve #include references (which come from the
522 // -include command line argument) as if they came from the main file, this
523 // affects file lookup etc.
524 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000525 FID = SourceMgr.getMainFileID();
526 CurFileEnt = SourceMgr.getFileEntryForID(FID);
527 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000528 }
Mike Stump11289f42009-09-09 15:08:12 +0000529
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000530 // Do a standard file entry lookup.
531 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000532 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000533 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000534 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerfde85352010-01-22 00:14:44 +0000535 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000536
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000537 // Otherwise, see if this is a subframework header. If so, this is relative
538 // to one of the headers on the #include stack. Walk the list of the current
539 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregor97eec242011-09-15 22:00:41 +0000540 // FIXME: SuggestedModule!
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000541 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000542 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000543 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000544 SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000545 return FE;
546 }
Mike Stump11289f42009-09-09 15:08:12 +0000547
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000548 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
549 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000550 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000551 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000552 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000553 if ((FE = HeaderInfo.LookupSubframeworkHeader(
554 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000555 return FE;
556 }
557 }
Mike Stump11289f42009-09-09 15:08:12 +0000558
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000559 // Otherwise, we really couldn't find the file.
560 return 0;
561}
562
Chris Lattnerf64b3522008-03-09 01:54:53 +0000563
564//===----------------------------------------------------------------------===//
565// Preprocessor Directive Handling.
566//===----------------------------------------------------------------------===//
567
David Blaikied5321242012-06-06 18:52:13 +0000568class Preprocessor::ResetMacroExpansionHelper {
569public:
570 ResetMacroExpansionHelper(Preprocessor *pp)
571 : PP(pp), save(pp->DisableMacroExpansion) {
572 if (pp->MacroExpansionInDirectivesOverride)
573 pp->DisableMacroExpansion = false;
574 }
575 ~ResetMacroExpansionHelper() {
576 PP->DisableMacroExpansion = save;
577 }
578private:
579 Preprocessor *PP;
580 bool save;
581};
582
Chris Lattnerf64b3522008-03-09 01:54:53 +0000583/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000584/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000585/// lexer/preprocessor state, and advances the lexer(s) so that the next token
586/// read is the correct one.
587void Preprocessor::HandleDirective(Token &Result) {
588 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000589
Chris Lattnerf64b3522008-03-09 01:54:53 +0000590 // We just parsed a # character at the start of a line, so we're in directive
591 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000592 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000593 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000594
Chris Lattnerf64b3522008-03-09 01:54:53 +0000595 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000596
Chris Lattnerf64b3522008-03-09 01:54:53 +0000597 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000598 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000599 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000600 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000601
Chris Lattner2d17ab72009-03-18 21:00:25 +0000602 // Save the '#' token in case we need to return it later.
603 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000604
Chris Lattnerf64b3522008-03-09 01:54:53 +0000605 // Read the next token, the directive flavor. This isn't expanded due to
606 // C99 6.10.3p8.
607 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000608
Chris Lattnerf64b3522008-03-09 01:54:53 +0000609 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
610 // #define A(x) #x
611 // A(abc
612 // #warning blah
613 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000614 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
615 // not support this for #include-like directives, since that can result in
616 // terrible diagnostics, and does not work in GCC.
617 if (InMacroArgs) {
618 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
619 switch (II->getPPKeywordID()) {
620 case tok::pp_include:
621 case tok::pp_import:
622 case tok::pp_include_next:
623 case tok::pp___include_macros:
624 Diag(Result, diag::err_embedded_include) << II->getName();
625 DiscardUntilEndOfDirective();
626 return;
627 default:
628 break;
629 }
630 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000631 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000632 }
Mike Stump11289f42009-09-09 15:08:12 +0000633
David Blaikied5321242012-06-06 18:52:13 +0000634 // Temporarily enable macro expansion if set so
635 // and reset to previous state when returning from this function.
636 ResetMacroExpansionHelper helper(this);
637
Chris Lattnerf64b3522008-03-09 01:54:53 +0000638TryAgain:
639 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000640 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000641 return; // null directive.
642 case tok::comment:
643 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
644 LexUnexpandedToken(Result);
645 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000646 case tok::code_completion:
647 if (CodeComplete)
648 CodeComplete->CodeCompleteDirective(
649 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000650 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000651 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000652 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000653 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000654 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000655 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000656 default:
657 IdentifierInfo *II = Result.getIdentifierInfo();
658 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000659
Chris Lattnerf64b3522008-03-09 01:54:53 +0000660 // Ask what the preprocessor keyword ID is.
661 switch (II->getPPKeywordID()) {
662 default: break;
663 // C99 6.10.1 - Conditional Inclusion.
664 case tok::pp_if:
665 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
666 case tok::pp_ifdef:
667 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
668 case tok::pp_ifndef:
669 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
670 case tok::pp_elif:
671 return HandleElifDirective(Result);
672 case tok::pp_else:
673 return HandleElseDirective(Result);
674 case tok::pp_endif:
675 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000676
Chris Lattnerf64b3522008-03-09 01:54:53 +0000677 // C99 6.10.2 - Source File Inclusion.
678 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000679 // Handle #include.
680 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000681 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000682 // Handle -imacros.
683 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000684
Chris Lattnerf64b3522008-03-09 01:54:53 +0000685 // C99 6.10.3 - Macro Replacement.
686 case tok::pp_define:
687 return HandleDefineDirective(Result);
688 case tok::pp_undef:
689 return HandleUndefDirective(Result);
690
691 // C99 6.10.4 - Line Control.
692 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000693 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattnerf64b3522008-03-09 01:54:53 +0000695 // C99 6.10.5 - Error Directive.
696 case tok::pp_error:
697 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000698
Chris Lattnerf64b3522008-03-09 01:54:53 +0000699 // C99 6.10.6 - Pragma Directive.
700 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000701 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000702
Chris Lattnerf64b3522008-03-09 01:54:53 +0000703 // GNU Extensions.
704 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000705 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000706 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000707 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000708
Chris Lattnerf64b3522008-03-09 01:54:53 +0000709 case tok::pp_warning:
710 Diag(Result, diag::ext_pp_warning_directive);
711 return HandleUserDiagnosticDirective(Result, true);
712 case tok::pp_ident:
713 return HandleIdentSCCSDirective(Result);
714 case tok::pp_sccs:
715 return HandleIdentSCCSDirective(Result);
716 case tok::pp_assert:
717 //isExtension = true; // FIXME: implement #assert
718 break;
719 case tok::pp_unassert:
720 //isExtension = true; // FIXME: implement #unassert
721 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000722
Douglas Gregor663b48f2012-01-03 19:48:16 +0000723 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000724 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000725 return HandleMacroPublicDirective(Result);
726 break;
727
Douglas Gregor663b48f2012-01-03 19:48:16 +0000728 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000729 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000730 return HandleMacroPrivateDirective(Result);
731 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000732 }
733 break;
734 }
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattner2d17ab72009-03-18 21:00:25 +0000736 // If this is a .S file, treat unknown # directives as non-preprocessor
737 // directives. This is important because # may be a comment or introduce
738 // various pseudo-ops. Just return the # token and push back the following
739 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000740 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000741 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000742 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000743 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000744 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000745
746 // If the second token is a hashhash token, then we need to translate it to
747 // unknown so the token lexer doesn't try to perform token pasting.
748 if (Result.is(tok::hashhash))
749 Toks[1].setKind(tok::unknown);
750
Chris Lattner2d17ab72009-03-18 21:00:25 +0000751 // Enter this token stream so that we re-lex the tokens. Make sure to
752 // enable macro expansion, in case the token after the # is an identifier
753 // that is expanded.
754 EnterTokenStream(Toks, 2, false, true);
755 return;
756 }
Mike Stump11289f42009-09-09 15:08:12 +0000757
Chris Lattnerf64b3522008-03-09 01:54:53 +0000758 // If we reached here, the preprocessing token is not valid!
759 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000760
Chris Lattnerf64b3522008-03-09 01:54:53 +0000761 // Read the rest of the PP line.
762 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000763
Chris Lattnerf64b3522008-03-09 01:54:53 +0000764 // Okay, we're done parsing the directive.
765}
766
Chris Lattner76e68962009-01-26 06:19:46 +0000767/// GetLineValue - Convert a numeric token into an unsigned value, emitting
768/// Diagnostic DiagID if it is invalid, and returning the value in Val.
769static bool GetLineValue(Token &DigitTok, unsigned &Val,
770 unsigned DiagID, Preprocessor &PP) {
771 if (DigitTok.isNot(tok::numeric_constant)) {
772 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000773
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000774 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000775 PP.DiscardUntilEndOfDirective();
776 return true;
777 }
Mike Stump11289f42009-09-09 15:08:12 +0000778
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000779 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000780 IntegerBuffer.resize(DigitTok.getLength());
781 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000782 bool Invalid = false;
783 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
784 if (Invalid)
785 return true;
786
Chris Lattnerd66f1722009-04-18 18:35:15 +0000787 // Verify that we have a simple digit-sequence, and compute the value. This
788 // is always a simple digit string computed in decimal, so we do this manually
789 // here.
790 Val = 0;
791 for (unsigned i = 0; i != ActualLength; ++i) {
792 if (!isdigit(DigitTokBegin[i])) {
793 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
794 diag::err_pp_line_digit_sequence);
795 PP.DiscardUntilEndOfDirective();
796 return true;
797 }
Mike Stump11289f42009-09-09 15:08:12 +0000798
Chris Lattnerd66f1722009-04-18 18:35:15 +0000799 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
800 if (NextVal < Val) { // overflow.
801 PP.Diag(DigitTok, DiagID);
802 PP.DiscardUntilEndOfDirective();
803 return true;
804 }
805 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000808 if (DigitTokBegin[0] == '0' && Val)
Chris Lattnerd66f1722009-04-18 18:35:15 +0000809 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000810
Chris Lattner76e68962009-01-26 06:19:46 +0000811 return false;
812}
813
James Dennettf6333ac2012-06-22 05:46:07 +0000814/// \brief Handle a \#line directive: C99 6.10.4.
815///
816/// The two acceptable forms are:
817/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000818/// # line digit-sequence
819/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000820/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000821void Preprocessor::HandleLineDirective(Token &Tok) {
822 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
823 // expanded.
824 Token DigitTok;
825 Lex(DigitTok);
826
Chris Lattner100c65e2009-01-26 05:29:08 +0000827 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000828 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000829 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000830 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000831
832 if (LineNo == 0)
833 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000834
Chris Lattner76e68962009-01-26 06:19:46 +0000835 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
836 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000837 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000838 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000839 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000840 if (LineNo >= LineLimit)
841 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000842 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000843 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000844
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000845 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000846 Token StrTok;
847 Lex(StrTok);
848
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000849 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
850 // string followed by eod.
851 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000852 ; // ok
853 else if (StrTok.isNot(tok::string_literal)) {
854 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000855 return DiscardUntilEndOfDirective();
856 } else if (StrTok.hasUDSuffix()) {
857 Diag(StrTok, diag::err_invalid_string_udl);
858 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000859 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000860 // Parse and validate the string, converting it into a unique ID.
861 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000862 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000863 if (Literal.hadError)
864 return DiscardUntilEndOfDirective();
865 if (Literal.Pascal) {
866 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
867 return DiscardUntilEndOfDirective();
868 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000869 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000870
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000871 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000872 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
873 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000874 }
Mike Stump11289f42009-09-09 15:08:12 +0000875
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000876 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000877
Chris Lattner839150e2009-03-27 17:13:49 +0000878 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000879 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
880 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000881 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000882}
883
Chris Lattner76e68962009-01-26 06:19:46 +0000884/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
885/// marker directive.
886static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
887 bool &IsSystemHeader, bool &IsExternCHeader,
888 Preprocessor &PP) {
889 unsigned FlagVal;
890 Token FlagTok;
891 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000892 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000893 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
894 return true;
895
896 if (FlagVal == 1) {
897 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000898
Chris Lattner76e68962009-01-26 06:19:46 +0000899 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000900 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000901 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
902 return true;
903 } else if (FlagVal == 2) {
904 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000905
Chris Lattner1c967782009-02-04 06:25:26 +0000906 SourceManager &SM = PP.getSourceManager();
907 // If we are leaving the current presumed file, check to make sure the
908 // presumed include stack isn't empty!
909 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000910 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000911 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000912 if (PLoc.isInvalid())
913 return true;
914
Chris Lattner1c967782009-02-04 06:25:26 +0000915 // If there is no include loc (main file) or if the include loc is in a
916 // different physical file, then we aren't in a "1" line marker flag region.
917 SourceLocation IncLoc = PLoc.getIncludeLoc();
918 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000919 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000920 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
921 PP.DiscardUntilEndOfDirective();
922 return true;
923 }
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattner76e68962009-01-26 06:19:46 +0000925 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000926 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000927 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
928 return true;
929 }
930
931 // We must have 3 if there are still flags.
932 if (FlagVal != 3) {
933 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000934 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000935 return true;
936 }
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner76e68962009-01-26 06:19:46 +0000938 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000939
Chris Lattner76e68962009-01-26 06:19:46 +0000940 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000941 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000942 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000943 return true;
944
945 // We must have 4 if there is yet another flag.
946 if (FlagVal != 4) {
947 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000948 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000949 return true;
950 }
Mike Stump11289f42009-09-09 15:08:12 +0000951
Chris Lattner76e68962009-01-26 06:19:46 +0000952 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000953
Chris Lattner76e68962009-01-26 06:19:46 +0000954 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000955 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000956
957 // There are no more valid flags here.
958 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000959 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000960 return true;
961}
962
963/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
964/// one of the following forms:
965///
966/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000967/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000968/// # 42 "file" ('1' | '2')? '3' '4'?
969///
970void Preprocessor::HandleDigitDirective(Token &DigitTok) {
971 // Validate the number and convert it to an unsigned. GNU does not have a
972 // line # limit other than it fit in 32-bits.
973 unsigned LineNo;
974 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
975 *this))
976 return;
Mike Stump11289f42009-09-09 15:08:12 +0000977
Chris Lattner76e68962009-01-26 06:19:46 +0000978 Token StrTok;
979 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000980
Chris Lattner76e68962009-01-26 06:19:46 +0000981 bool IsFileEntry = false, IsFileExit = false;
982 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000983 int FilenameID = -1;
984
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000985 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
986 // string followed by eod.
987 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000988 ; // ok
989 else if (StrTok.isNot(tok::string_literal)) {
990 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000991 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +0000992 } else if (StrTok.hasUDSuffix()) {
993 Diag(StrTok, diag::err_invalid_string_udl);
994 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000995 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000996 // Parse and validate the string, converting it into a unique ID.
997 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000998 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000999 if (Literal.hadError)
1000 return DiscardUntilEndOfDirective();
1001 if (Literal.Pascal) {
1002 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1003 return DiscardUntilEndOfDirective();
1004 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001005 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001006
Chris Lattner76e68962009-01-26 06:19:46 +00001007 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001008 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001009 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001010 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001011 }
Mike Stump11289f42009-09-09 15:08:12 +00001012
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001013 // Create a line note with this information.
1014 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001015 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001016 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001017
Chris Lattner839150e2009-03-27 17:13:49 +00001018 // If the preprocessor has callbacks installed, notify them of the #line
1019 // change. This is used so that the line marker comes out in -E mode for
1020 // example.
1021 if (Callbacks) {
1022 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1023 if (IsFileEntry)
1024 Reason = PPCallbacks::EnterFile;
1025 else if (IsFileExit)
1026 Reason = PPCallbacks::ExitFile;
1027 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1028 if (IsExternCHeader)
1029 FileKind = SrcMgr::C_ExternCSystem;
1030 else if (IsSystemHeader)
1031 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001032
Chris Lattnerc745cec2010-04-14 04:28:50 +00001033 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001034 }
Chris Lattner76e68962009-01-26 06:19:46 +00001035}
1036
1037
Chris Lattner38d7fd22009-01-26 05:30:54 +00001038/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1039///
Mike Stump11289f42009-09-09 15:08:12 +00001040void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001041 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001042 // PTH doesn't emit #warning or #error directives.
1043 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001044 return CurPTHLexer->DiscardToEndOfLine();
1045
Chris Lattnerf64b3522008-03-09 01:54:53 +00001046 // Read the rest of the line raw. We do this because we don't want macros
1047 // to be expanded and we don't require that the tokens be valid preprocessing
1048 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1049 // collapse multiple consequtive white space between tokens, but this isn't
1050 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001051 SmallString<128> Message;
1052 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001053
1054 // Find the first non-whitespace character, so that we can make the
1055 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001056 StringRef Msg = Message.str().ltrim(" ");
1057
Chris Lattner100c65e2009-01-26 05:29:08 +00001058 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001059 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001060 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001061 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001062}
1063
1064/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1065///
1066void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1067 // Yes, this directive is an extension.
1068 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001069
Chris Lattnerf64b3522008-03-09 01:54:53 +00001070 // Read the string argument.
1071 Token StrTok;
1072 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001073
Chris Lattnerf64b3522008-03-09 01:54:53 +00001074 // If the token kind isn't a string, it's a malformed directive.
1075 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001076 StrTok.isNot(tok::wide_string_literal)) {
1077 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001078 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001079 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001080 return;
1081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082
Richard Smithd67aea22012-03-06 03:21:47 +00001083 if (StrTok.hasUDSuffix()) {
1084 Diag(StrTok, diag::err_invalid_string_udl);
1085 return DiscardUntilEndOfDirective();
1086 }
1087
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001088 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001089 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001090
Douglas Gregordc970f02010-03-16 22:30:13 +00001091 if (Callbacks) {
1092 bool Invalid = false;
1093 std::string Str = getSpelling(StrTok, &Invalid);
1094 if (!Invalid)
1095 Callbacks->Ident(Tok.getLocation(), Str);
1096 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001097}
1098
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001099/// \brief Handle a #public directive.
1100void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001101 Token MacroNameTok;
1102 ReadMacroName(MacroNameTok, 2);
1103
1104 // Error reading macro name? If so, diagnostic already issued.
1105 if (MacroNameTok.is(tok::eod))
1106 return;
1107
Douglas Gregor663b48f2012-01-03 19:48:16 +00001108 // Check to see if this is the last token on the #__public_macro line.
1109 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001110
1111 // Okay, we finally have a valid identifier to undef.
1112 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1113
1114 // If the macro is not defined, this is an error.
1115 if (MI == 0) {
Douglas Gregorebf00492011-10-17 15:32:29 +00001116 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001117 << MacroNameTok.getIdentifierInfo();
1118 return;
1119 }
1120
1121 // Note that this macro has now been exported.
Douglas Gregorebf00492011-10-17 15:32:29 +00001122 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1123
1124 // If this macro definition came from a PCH file, mark it
1125 // as having changed since serialization.
1126 if (MI->isFromAST())
1127 MI->setChangedAfterLoad();
1128}
1129
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001130/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001131void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1132 Token MacroNameTok;
1133 ReadMacroName(MacroNameTok, 2);
1134
1135 // Error reading macro name? If so, diagnostic already issued.
1136 if (MacroNameTok.is(tok::eod))
1137 return;
1138
Douglas Gregor663b48f2012-01-03 19:48:16 +00001139 // Check to see if this is the last token on the #__private_macro line.
1140 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001141
1142 // Okay, we finally have a valid identifier to undef.
1143 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1144
1145 // If the macro is not defined, this is an error.
1146 if (MI == 0) {
1147 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1148 << MacroNameTok.getIdentifierInfo();
1149 return;
1150 }
1151
1152 // Note that this macro has now been marked private.
1153 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001154
1155 // If this macro definition came from a PCH file, mark it
1156 // as having changed since serialization.
1157 if (MI->isFromAST())
1158 MI->setChangedAfterLoad();
1159}
1160
Chris Lattnerf64b3522008-03-09 01:54:53 +00001161//===----------------------------------------------------------------------===//
1162// Preprocessor Include Directive Handling.
1163//===----------------------------------------------------------------------===//
1164
1165/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001166/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001167/// true if the input filename was in <>'s or false if it were in ""'s. The
1168/// caller is expected to provide a buffer that is large enough to hold the
1169/// spelling of the filename, but is also expected to handle the case when
1170/// this method decides to use a different buffer.
1171bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001172 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001173 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001174 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001175
Chris Lattnerf64b3522008-03-09 01:54:53 +00001176 // Make sure the filename is <x> or "x".
1177 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001178 if (Buffer[0] == '<') {
1179 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001180 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001181 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001182 return true;
1183 }
1184 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001185 } else if (Buffer[0] == '"') {
1186 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001187 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001188 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001189 return true;
1190 }
1191 isAngled = false;
1192 } else {
1193 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001194 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001195 return true;
1196 }
Mike Stump11289f42009-09-09 15:08:12 +00001197
Chris Lattnerf64b3522008-03-09 01:54:53 +00001198 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001199 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001200 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001201 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001202 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001203 }
Mike Stump11289f42009-09-09 15:08:12 +00001204
Chris Lattnerf64b3522008-03-09 01:54:53 +00001205 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001206 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001207 return isAngled;
1208}
1209
James Dennettf6333ac2012-06-22 05:46:07 +00001210/// \brief Handle cases where the \#include name is expanded from a macro
1211/// as multiple tokens, which need to be glued together.
1212///
1213/// This occurs for code like:
1214/// \code
1215/// \#define FOO <a/b.h>
1216/// \#include FOO
1217/// \endcode
Chris Lattnerf64b3522008-03-09 01:54:53 +00001218/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1219///
1220/// This code concatenates and consumes tokens up to the '>' token. It returns
1221/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001222/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001223bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001224 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001225 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001226 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001227
John Thompsonb5353522009-10-30 13:49:06 +00001228 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001229 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001230 End = CurTok.getLocation();
1231
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001232 // FIXME: Provide code completion for #includes.
1233 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001234 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001235 Lex(CurTok);
1236 continue;
1237 }
1238
Chris Lattnerf64b3522008-03-09 01:54:53 +00001239 // Append the spelling of this token to the buffer. If there was a space
1240 // before it, add it now.
1241 if (CurTok.hasLeadingSpace())
1242 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001243
Chris Lattnerf64b3522008-03-09 01:54:53 +00001244 // Get the spelling of the token, directly into FilenameBuffer if possible.
1245 unsigned PreAppendSize = FilenameBuffer.size();
1246 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001247
Chris Lattnerf64b3522008-03-09 01:54:53 +00001248 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001249 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001250
Chris Lattnerf64b3522008-03-09 01:54:53 +00001251 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1252 if (BufPtr != &FilenameBuffer[PreAppendSize])
1253 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001254
Chris Lattnerf64b3522008-03-09 01:54:53 +00001255 // Resize FilenameBuffer to the correct size.
1256 if (CurTok.getLength() != ActualLen)
1257 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001258
Chris Lattnerf64b3522008-03-09 01:54:53 +00001259 // If we found the '>' marker, return success.
1260 if (CurTok.is(tok::greater))
1261 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001262
John Thompsonb5353522009-10-30 13:49:06 +00001263 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001264 }
1265
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001266 // If we hit the eod marker, emit an error and return true so that the caller
1267 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001268 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001269 return true;
1270}
1271
James Dennettf6333ac2012-06-22 05:46:07 +00001272/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1273/// the file to be included from the lexer, then include it! This is a common
1274/// routine with functionality shared between \#include, \#include_next and
1275/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001276/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001277void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1278 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001279 const DirectoryLookup *LookupFrom,
1280 bool isImport) {
1281
1282 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001283 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001284
Chris Lattnerf64b3522008-03-09 01:54:53 +00001285 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001286 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001287 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001288 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001289 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001290
Chris Lattnerf64b3522008-03-09 01:54:53 +00001291 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001292 case tok::eod:
1293 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001294 return;
Mike Stump11289f42009-09-09 15:08:12 +00001295
Chris Lattnerf64b3522008-03-09 01:54:53 +00001296 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001297 case tok::string_literal:
1298 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001299 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001300 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001301 break;
Mike Stump11289f42009-09-09 15:08:12 +00001302
Chris Lattnerf64b3522008-03-09 01:54:53 +00001303 case tok::less:
1304 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1305 // case, glue the tokens together into FilenameBuffer and interpret those.
1306 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001307 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001308 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001309 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001310 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001311 break;
1312 default:
1313 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1314 DiscardUntilEndOfDirective();
1315 return;
1316 }
Mike Stump11289f42009-09-09 15:08:12 +00001317
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001318 CharSourceRange FilenameRange
1319 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001320 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001321 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001322 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001323 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1324 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001325 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001326 DiscardUntilEndOfDirective();
1327 return;
1328 }
Mike Stump11289f42009-09-09 15:08:12 +00001329
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001330 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001331 // we allow macros that expand to nothing after the filename, because this
1332 // falls into the category of "#include pp-tokens new-line" specified in
1333 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001334 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001335
1336 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001337 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1338 Diag(FilenameTok, diag::err_pp_include_too_deep);
1339 return;
1340 }
Mike Stump11289f42009-09-09 15:08:12 +00001341
John McCall32f5fe12011-09-30 05:12:12 +00001342 // Complain about attempts to #include files in an audit pragma.
1343 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1344 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1345 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1346
1347 // Immediately leave the pragma.
1348 PragmaARCCFCodeAuditedLoc = SourceLocation();
1349 }
1350
Aaron Ballman611306e2012-03-02 22:51:54 +00001351 if (HeaderInfo.HasIncludeAliasMap()) {
1352 // Map the filename with the brackets still attached. If the name doesn't
1353 // map to anything, fall back on the filename we've already gotten the
1354 // spelling for.
1355 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1356 if (!NewName.empty())
1357 Filename = NewName;
1358 }
1359
Chris Lattnerf64b3522008-03-09 01:54:53 +00001360 // Search include directories.
1361 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001362 SmallString<1024> SearchPath;
1363 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001364 // We get the raw path only if we have 'Callbacks' to which we later pass
1365 // the path.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001366 Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001367 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001368 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001369 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001370 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001371
Douglas Gregor11729f02011-11-30 18:12:06 +00001372 if (Callbacks) {
1373 if (!File) {
1374 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001375 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001376 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1377 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1378 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001379 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001380 HeaderInfo.AddSearchPath(DL, isAngled);
1381
1382 // Try the lookup again, skipping the cache.
1383 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001384 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001385 /*SkipCache*/true);
1386 }
1387 }
1388 }
1389
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001390 if (!SuggestedModule) {
1391 // Notify the callback object that we've seen an inclusion directive.
1392 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1393 FilenameRange, File,
1394 SearchPath, RelativePath,
1395 /*ImportedModule=*/0);
1396 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001397 }
1398
1399 if (File == 0) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001400 if (!SuppressIncludeNotFoundError) {
1401 // If the file could not be located and it was included via angle
1402 // brackets, we can attempt a lookup as though it were a quoted path to
1403 // provide the user with a possible fixit.
1404 if (isAngled) {
1405 File = LookupFile(Filename, false, LookupFrom, CurDir,
1406 Callbacks ? &SearchPath : 0,
1407 Callbacks ? &RelativePath : 0,
1408 getLangOpts().Modules ? &SuggestedModule : 0);
1409 if (File) {
1410 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1411 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1412 Filename <<
1413 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1414 }
1415 }
1416 // If the file is still not found, just go with the vanilla diagnostic
1417 if (!File)
1418 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1419 }
1420 if (!File)
1421 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001422 }
1423
Douglas Gregor97eec242011-09-15 22:00:41 +00001424 // If we are supposed to import a module rather than including the header,
1425 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001426 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001427 // Compute the module access path corresponding to this module.
1428 // FIXME: Should we have a second loadModule() overload to avoid this
1429 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001430 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregorde3ef502011-11-30 23:21:26 +00001431 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001432 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1433 FilenameTok.getLocation()));
1434 std::reverse(Path.begin(), Path.end());
1435
Douglas Gregor41e115a2011-11-30 18:02:36 +00001436 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001437 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001438 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1439 if (I)
1440 PathString += '.';
1441 PathString += Path[I].first->getName();
1442 }
1443 int IncludeKind = 0;
1444
1445 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1446 case tok::pp_include:
1447 IncludeKind = 0;
1448 break;
1449
1450 case tok::pp_import:
1451 IncludeKind = 1;
1452 break;
1453
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001454 case tok::pp_include_next:
1455 IncludeKind = 2;
1456 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001457
1458 case tok::pp___include_macros:
1459 IncludeKind = 3;
1460 break;
1461
1462 default:
1463 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001464 }
1465
Douglas Gregor2537a362011-12-08 17:01:29 +00001466 // Determine whether we are actually building the module that this
1467 // include directive maps to.
1468 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001469 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001470
David Blaikiebbafb8a2012-03-11 07:00:24 +00001471 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001472 // If we're not building the imported module, warn that we're going
1473 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001474 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001475 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1476 /*IsTokenRange=*/false);
1477 Diag(HashLoc, diag::warn_auto_module_import)
1478 << IncludeKind << PathString
1479 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001480 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001481 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001482
Douglas Gregor71944202011-11-30 00:36:36 +00001483 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001484 // If this was an #__include_macros directive, only make macros visible.
1485 Module::NameVisibilityKind Visibility
1486 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001487 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001488 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1489 /*IsIncludeDirective=*/true);
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001490 assert((Imported == 0 || Imported == SuggestedModule) &&
1491 "the imported module is different than the suggested one");
Douglas Gregor2537a362011-12-08 17:01:29 +00001492
1493 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001494 if (!BuildingImportedModule && Imported) {
1495 if (Callbacks) {
1496 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1497 FilenameRange, File,
1498 SearchPath, RelativePath, Imported);
1499 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001500 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001501 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001502
1503 // If we failed to find a submodule that we expected to find, we can
1504 // continue. Otherwise, there's an error in the included file, so we
1505 // don't want to include it.
1506 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1507 return;
1508 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001509 }
1510
1511 if (Callbacks && SuggestedModule) {
1512 // We didn't notify the callback object that we've seen an inclusion
1513 // directive before. Now that we are parsing the include normally and not
1514 // turning it to a module import, notify the callback object.
1515 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1516 FilenameRange, File,
1517 SearchPath, RelativePath,
1518 /*ImportedModule=*/0);
Douglas Gregor97eec242011-09-15 22:00:41 +00001519 }
1520
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001521 // The #included file will be considered to be a system header if either it is
1522 // in a system include directory, or if the #includer is a system include
1523 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001524 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001525 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001526 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001527
Chris Lattner72286d62010-04-19 20:44:31 +00001528 // Ask HeaderInfo if we should enter this #include file. If not, #including
1529 // this file will have no effect.
1530 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001531 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001532 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001533 return;
1534 }
1535
Chris Lattnerf64b3522008-03-09 01:54:53 +00001536 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001537 SourceLocation IncludePos = End;
1538 // If the filename string was the result of macro expansions, set the include
1539 // position on the file where it will be included and after the expansions.
1540 if (IncludePos.isMacroID())
1541 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1542 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001543 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001544
1545 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001546 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001547}
1548
James Dennettf6333ac2012-06-22 05:46:07 +00001549/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001550///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001551void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1552 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001553 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001554
Chris Lattnerf64b3522008-03-09 01:54:53 +00001555 // #include_next is like #include, except that we start searching after
1556 // the current found directory. If we can't do this, issue a
1557 // diagnostic.
1558 const DirectoryLookup *Lookup = CurDirLookup;
1559 if (isInPrimaryFile()) {
1560 Lookup = 0;
1561 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1562 } else if (Lookup == 0) {
1563 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1564 } else {
1565 // Start looking up in the next directory.
1566 ++Lookup;
1567 }
Mike Stump11289f42009-09-09 15:08:12 +00001568
Douglas Gregor796d76a2010-10-20 22:00:55 +00001569 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001570}
1571
James Dennettf6333ac2012-06-22 05:46:07 +00001572/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001573void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1574 // The Microsoft #import directive takes a type library and generates header
1575 // files from it, and includes those. This is beyond the scope of what clang
1576 // does, so we ignore it and error out. However, #import can optionally have
1577 // trailing attributes that span multiple lines. We're going to eat those
1578 // so we can continue processing from there.
1579 Diag(Tok, diag::err_pp_import_directive_ms );
1580
1581 // Read tokens until we get to the end of the directive. Note that the
1582 // directive can be split over multiple lines using the backslash character.
1583 DiscardUntilEndOfDirective();
1584}
1585
James Dennettf6333ac2012-06-22 05:46:07 +00001586/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001587///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001588void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1589 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001590 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1591 if (LangOpts.MicrosoftMode)
1592 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001593 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001594 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001595 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001596}
1597
Chris Lattner58a1eb02009-04-08 18:46:40 +00001598/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1599/// pseudo directive in the predefines buffer. This handles it by sucking all
1600/// tokens through the preprocessor and discarding them (only keeping the side
1601/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001602void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1603 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001604 // This directive should only occur in the predefines buffer. If not, emit an
1605 // error and reject it.
1606 SourceLocation Loc = IncludeMacrosTok.getLocation();
1607 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1608 Diag(IncludeMacrosTok.getLocation(),
1609 diag::pp_include_macros_out_of_predefines);
1610 DiscardUntilEndOfDirective();
1611 return;
1612 }
Mike Stump11289f42009-09-09 15:08:12 +00001613
Chris Lattnere01d82b2009-04-08 20:53:24 +00001614 // Treat this as a normal #include for checking purposes. If this is
1615 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001616 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001617
Chris Lattnere01d82b2009-04-08 20:53:24 +00001618 Token TmpTok;
1619 do {
1620 Lex(TmpTok);
1621 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1622 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001623}
1624
Chris Lattnerf64b3522008-03-09 01:54:53 +00001625//===----------------------------------------------------------------------===//
1626// Preprocessor Macro Directive Handling.
1627//===----------------------------------------------------------------------===//
1628
1629/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1630/// definition has just been read. Lex the rest of the arguments and the
1631/// closing ), updating MI with what we learn. Return true if an error occurs
1632/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001633bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001634 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001635
Chris Lattnerf64b3522008-03-09 01:54:53 +00001636 while (1) {
1637 LexUnexpandedToken(Tok);
1638 switch (Tok.getKind()) {
1639 case tok::r_paren:
1640 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001641 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001642 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001643 // Otherwise we have #define FOO(A,)
1644 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1645 return true;
1646 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001647 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001648 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001649 diag::warn_cxx98_compat_variadic_macro :
1650 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001651
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001652 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1653 if (LangOpts.OpenCL) {
1654 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1655 return true;
1656 }
1657
Chris Lattnerf64b3522008-03-09 01:54:53 +00001658 // Lex the token after the identifier.
1659 LexUnexpandedToken(Tok);
1660 if (Tok.isNot(tok::r_paren)) {
1661 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1662 return true;
1663 }
1664 // Add the __VA_ARGS__ identifier as an argument.
1665 Arguments.push_back(Ident__VA_ARGS__);
1666 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001667 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001668 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001669 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001670 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1671 return true;
1672 default:
1673 // Handle keywords and identifiers here to accept things like
1674 // #define Foo(for) for.
1675 IdentifierInfo *II = Tok.getIdentifierInfo();
1676 if (II == 0) {
1677 // #define X(1
1678 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1679 return true;
1680 }
1681
1682 // If this is already used as an argument, it is used multiple times (e.g.
1683 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001684 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001685 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001686 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001687 return true;
1688 }
Mike Stump11289f42009-09-09 15:08:12 +00001689
Chris Lattnerf64b3522008-03-09 01:54:53 +00001690 // Add the argument to the macro info.
1691 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001692
Chris Lattnerf64b3522008-03-09 01:54:53 +00001693 // Lex the token after the identifier.
1694 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001695
Chris Lattnerf64b3522008-03-09 01:54:53 +00001696 switch (Tok.getKind()) {
1697 default: // #define X(A B
1698 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1699 return true;
1700 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001701 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001702 return false;
1703 case tok::comma: // #define X(A,
1704 break;
1705 case tok::ellipsis: // #define X(A... -> GCC extension
1706 // Diagnose extension.
1707 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001708
Chris Lattnerf64b3522008-03-09 01:54:53 +00001709 // Lex the token after the identifier.
1710 LexUnexpandedToken(Tok);
1711 if (Tok.isNot(tok::r_paren)) {
1712 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1713 return true;
1714 }
Mike Stump11289f42009-09-09 15:08:12 +00001715
Chris Lattnerf64b3522008-03-09 01:54:53 +00001716 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001717 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001718 return false;
1719 }
1720 }
1721 }
1722}
1723
James Dennettf6333ac2012-06-22 05:46:07 +00001724/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001725/// line then lets the caller lex the next real token.
1726void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1727 ++NumDefined;
1728
1729 Token MacroNameTok;
1730 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001731
Chris Lattnerf64b3522008-03-09 01:54:53 +00001732 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001733 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001734 return;
1735
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001736 Token LastTok = MacroNameTok;
1737
Chris Lattnerf64b3522008-03-09 01:54:53 +00001738 // If we are supposed to keep comments in #defines, reenable comment saving
1739 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001740 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001741
Chris Lattnerf64b3522008-03-09 01:54:53 +00001742 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001743 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001744
Chris Lattnerf64b3522008-03-09 01:54:53 +00001745 Token Tok;
1746 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001747
Chris Lattnerf64b3522008-03-09 01:54:53 +00001748 // If this is a function-like macro definition, parse the argument list,
1749 // marking each of the identifiers as being used as macro arguments. Also,
1750 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001751 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001752 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001753 } else if (Tok.hasLeadingSpace()) {
1754 // This is a normal token with leading space. Clear the leading space
1755 // marker on the first token to get proper expansion.
1756 Tok.clearFlag(Token::LeadingSpace);
1757 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001758 // This is a function-like macro definition. Read the argument list.
1759 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001760 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001761 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001762 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001763 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001764 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001765 DiscardUntilEndOfDirective();
1766 return;
1767 }
1768
Chris Lattner249c38b2009-04-19 18:26:34 +00001769 // If this is a definition of a variadic C99 function-like macro, not using
1770 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001771
Chris Lattner249c38b2009-04-19 18:26:34 +00001772 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1773 // This gets unpoisoned where it is allowed.
1774 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1775 if (MI->isC99Varargs())
1776 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001777
Chris Lattnerf64b3522008-03-09 01:54:53 +00001778 // Read the first token after the arg list for down below.
1779 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001780 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001781 // C99 requires whitespace between the macro definition and the body. Emit
1782 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001783 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001784 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001785 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1786 // first character of a replacement list is not a character required by
1787 // subclause 5.2.1, then there shall be white-space separation between the
1788 // identifier and the replacement list.". 5.2.1 lists this set:
1789 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1790 // is irrelevant here.
1791 bool isInvalid = false;
1792 if (Tok.is(tok::at)) // @ is not in the list above.
1793 isInvalid = true;
1794 else if (Tok.is(tok::unknown)) {
1795 // If we have an unknown token, it is something strange like "`". Since
1796 // all of valid characters would have lexed into a single character
1797 // token of some sort, we know this is not a valid case.
1798 isInvalid = true;
1799 }
1800 if (isInvalid)
1801 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1802 else
1803 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001804 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001805
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001806 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001807 LastTok = Tok;
1808
Chris Lattnerf64b3522008-03-09 01:54:53 +00001809 // Read the rest of the macro body.
1810 if (MI->isObjectLike()) {
1811 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001812 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001813 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001814 MI->AddTokenToBody(Tok);
1815 // Get the next token of the macro.
1816 LexUnexpandedToken(Tok);
1817 }
Mike Stump11289f42009-09-09 15:08:12 +00001818
Chris Lattnerf64b3522008-03-09 01:54:53 +00001819 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001820 // Otherwise, read the body of a function-like macro. While we are at it,
1821 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1822 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001823 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001824 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001825
Eli Friedman14d3c792012-11-14 02:18:46 +00001826 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001827 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001828
Chris Lattnerf64b3522008-03-09 01:54:53 +00001829 // Get the next token of the macro.
1830 LexUnexpandedToken(Tok);
1831 continue;
1832 }
Mike Stump11289f42009-09-09 15:08:12 +00001833
Eli Friedman14d3c792012-11-14 02:18:46 +00001834 if (Tok.is(tok::hashhash)) {
1835
1836 // If we see token pasting, check if it looks like the gcc comma
1837 // pasting extension. We'll use this information to suppress
1838 // diagnostics later on.
1839
1840 // Get the next token of the macro.
1841 LexUnexpandedToken(Tok);
1842
1843 if (Tok.is(tok::eod)) {
1844 MI->AddTokenToBody(LastTok);
1845 break;
1846 }
1847
1848 unsigned NumTokens = MI->getNumTokens();
1849 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1850 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1851 MI->setHasCommaPasting();
1852
1853 // Things look ok, add the '##' and param name tokens to the macro.
1854 MI->AddTokenToBody(LastTok);
1855 MI->AddTokenToBody(Tok);
1856 LastTok = Tok;
1857
1858 // Get the next token of the macro.
1859 LexUnexpandedToken(Tok);
1860 continue;
1861 }
1862
Chris Lattnerf64b3522008-03-09 01:54:53 +00001863 // Get the next token of the macro.
1864 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001865
Chris Lattner83bd8282009-05-25 17:16:10 +00001866 // Check for a valid macro arg identifier.
1867 if (Tok.getIdentifierInfo() == 0 ||
1868 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1869
1870 // If this is assembler-with-cpp mode, we accept random gibberish after
1871 // the '#' because '#' is often a comment character. However, change
1872 // the kind of the token to tok::unknown so that the preprocessor isn't
1873 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001874 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001875 LastTok.setKind(tok::unknown);
1876 } else {
1877 Diag(Tok, diag::err_pp_stringize_not_parameter);
1878 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001879
Chris Lattner83bd8282009-05-25 17:16:10 +00001880 // Disable __VA_ARGS__ again.
1881 Ident__VA_ARGS__->setIsPoisoned(true);
1882 return;
1883 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001884 }
Mike Stump11289f42009-09-09 15:08:12 +00001885
Chris Lattner83bd8282009-05-25 17:16:10 +00001886 // Things look ok, add the '#' and param name tokens to the macro.
1887 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001888 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001889 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001890
Chris Lattnerf64b3522008-03-09 01:54:53 +00001891 // Get the next token of the macro.
1892 LexUnexpandedToken(Tok);
1893 }
1894 }
Mike Stump11289f42009-09-09 15:08:12 +00001895
1896
Chris Lattnerf64b3522008-03-09 01:54:53 +00001897 // Disable __VA_ARGS__ again.
1898 Ident__VA_ARGS__->setIsPoisoned(true);
1899
Chris Lattner57540c52011-04-15 05:22:18 +00001900 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001901 // replacement list.
1902 unsigned NumTokens = MI->getNumTokens();
1903 if (NumTokens != 0) {
1904 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1905 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001906 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001907 return;
1908 }
1909 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1910 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001911 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001912 return;
1913 }
1914 }
Mike Stump11289f42009-09-09 15:08:12 +00001915
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001916 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001917
Chris Lattnerf64b3522008-03-09 01:54:53 +00001918 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00001919 // the macro bodies are identical, and issue diagnostics if they are not.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001920 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001921 // It is very common for system headers to have tons of macro redefinitions
1922 // and for warnings to be disabled in system headers. If this is the case,
1923 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001924 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001925 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001926 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001927 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001928
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001929 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001930 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001931 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001932 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001933 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1934 << MacroNameTok.getIdentifierInfo();
1935 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1936 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001937 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001938 if (OtherMI->isWarnIfUnused())
1939 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001940 }
Mike Stump11289f42009-09-09 15:08:12 +00001941
Chris Lattnerf64b3522008-03-09 01:54:53 +00001942 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001943
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001944 assert(!MI->isUsed());
1945 // If we need warning for not using the macro, add its location in the
1946 // warn-because-unused-macro set. If it gets used it will be removed from set.
1947 if (isInPrimaryFile() && // don't warn for include'd macros.
1948 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00001949 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001950 MI->setIsWarnIfUnused(true);
1951 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1952 }
1953
Chris Lattner928e9092009-04-12 01:39:54 +00001954 // If the callbacks want to know, tell them about the macro definition.
1955 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001956 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001957}
1958
James Dennettf6333ac2012-06-22 05:46:07 +00001959/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001960///
1961void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1962 ++NumUndefined;
1963
1964 Token MacroNameTok;
1965 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001966
Chris Lattnerf64b3522008-03-09 01:54:53 +00001967 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001968 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001969 return;
Mike Stump11289f42009-09-09 15:08:12 +00001970
Chris Lattnerf64b3522008-03-09 01:54:53 +00001971 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001972 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001973
Chris Lattnerf64b3522008-03-09 01:54:53 +00001974 // Okay, we finally have a valid identifier to undef.
1975 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001976
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00001977 // If the callbacks want to know, tell them about the macro #undef.
1978 // Note: no matter if the macro was defined or not.
1979 if (Callbacks)
1980 Callbacks->MacroUndefined(MacroNameTok, MI);
1981
Chris Lattnerf64b3522008-03-09 01:54:53 +00001982 // If the macro is not defined, this is a noop undef, just return.
1983 if (MI == 0) return;
1984
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00001985 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00001986 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001987
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001988 if (MI->isWarnIfUnused())
1989 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1990
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00001991 UndefineMacro(MacroNameTok.getIdentifierInfo(), MI,
1992 MacroNameTok.getLocation());
1993}
1994
1995void Preprocessor::UndefineMacro(IdentifierInfo *II, MacroInfo *MI,
1996 SourceLocation UndefLoc) {
1997 MI->setUndefLoc(UndefLoc);
1998 if (MI->isFromAST()) {
1999 MI->setChangedAfterLoad();
2000 if (Listener)
2001 Listener->UndefinedMacro(MI);
2002 }
2003
2004 clearMacroInfo(II);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002005}
2006
2007
2008//===----------------------------------------------------------------------===//
2009// Preprocessor Conditional Directive Handling.
2010//===----------------------------------------------------------------------===//
2011
James Dennettf6333ac2012-06-22 05:46:07 +00002012/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2013/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2014/// true if any tokens have been returned or pp-directives activated before this
2015/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002016///
2017void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2018 bool ReadAnyTokensBeforeDirective) {
2019 ++NumIf;
2020 Token DirectiveTok = Result;
2021
2022 Token MacroNameTok;
2023 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002024
Chris Lattnerf64b3522008-03-09 01:54:53 +00002025 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002026 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002027 // Skip code until we get to #endif. This helps with recovery by not
2028 // emitting an error when the #endif is reached.
2029 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2030 /*Foundnonskip*/false, /*FoundElse*/false);
2031 return;
2032 }
Mike Stump11289f42009-09-09 15:08:12 +00002033
Chris Lattnerf64b3522008-03-09 01:54:53 +00002034 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002035 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002036
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002037 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2038 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002039
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002040 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002041 // If the start of a top-level #ifdef and if the macro is not defined,
2042 // inform MIOpt that this might be the start of a proper include guard.
2043 // Otherwise it is some other form of unknown conditional which we can't
2044 // handle.
2045 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002046 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002047 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002048 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002049 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002050 }
2051
Chris Lattnerf64b3522008-03-09 01:54:53 +00002052 // If there is a macro, process it.
2053 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002054 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002055
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002056 if (Callbacks) {
2057 if (isIfndef)
Argyrios Kyrtzidis222a7bb2012-12-08 02:21:11 +00002058 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MI);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002059 else
Argyrios Kyrtzidis222a7bb2012-12-08 02:21:11 +00002060 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MI);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002061 }
2062
Chris Lattnerf64b3522008-03-09 01:54:53 +00002063 // Should we include the stuff contained by this directive?
2064 if (!MI == isIfndef) {
2065 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002066 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2067 /*wasskip*/false, /*foundnonskip*/true,
2068 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002069 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002070 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002071 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002072 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002073 /*FoundElse*/false);
2074 }
2075}
2076
James Dennettf6333ac2012-06-22 05:46:07 +00002077/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002078///
2079void Preprocessor::HandleIfDirective(Token &IfToken,
2080 bool ReadAnyTokensBeforeDirective) {
Aaron Ballman6ce00002013-01-16 19:32:21 +00002081 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002082 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002083
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002084 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002085 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002086 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2087 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2088 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002089
2090 // If this condition is equivalent to #ifndef X, and if this is the first
2091 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002092 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002093 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002094 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00002095 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002096 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002097 }
2098
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002099 if (Callbacks)
2100 Callbacks->If(IfToken.getLocation(),
2101 SourceRange(ConditionalBegin, ConditionalEnd));
2102
Chris Lattnerf64b3522008-03-09 01:54:53 +00002103 // Should we include the stuff contained by this directive?
2104 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002105 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002106 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002107 /*foundnonskip*/true, /*foundelse*/false);
2108 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002109 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002110 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002111 /*FoundElse*/false);
2112 }
2113}
2114
James Dennettf6333ac2012-06-22 05:46:07 +00002115/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002116///
2117void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2118 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002119
Chris Lattnerf64b3522008-03-09 01:54:53 +00002120 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002121 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002122
Chris Lattnerf64b3522008-03-09 01:54:53 +00002123 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002124 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002125 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002126 Diag(EndifToken, diag::err_pp_endif_without_if);
2127 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002128 }
Mike Stump11289f42009-09-09 15:08:12 +00002129
Chris Lattnerf64b3522008-03-09 01:54:53 +00002130 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002131 if (CurPPLexer->getConditionalStackDepth() == 0)
2132 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002133
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002134 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002135 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002136
2137 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002138 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002139}
2140
James Dennettf6333ac2012-06-22 05:46:07 +00002141/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002142///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002143void Preprocessor::HandleElseDirective(Token &Result) {
2144 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002145
Chris Lattnerf64b3522008-03-09 01:54:53 +00002146 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002147 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002148
Chris Lattnerf64b3522008-03-09 01:54:53 +00002149 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002150 if (CurPPLexer->popConditionalLevel(CI)) {
2151 Diag(Result, diag::pp_err_else_without_if);
2152 return;
2153 }
Mike Stump11289f42009-09-09 15:08:12 +00002154
Chris Lattnerf64b3522008-03-09 01:54:53 +00002155 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002156 if (CurPPLexer->getConditionalStackDepth() == 0)
2157 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002158
2159 // If this is a #else with a #else before it, report the error.
2160 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002161
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002162 if (Callbacks)
2163 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2164
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002165 // Finally, skip the rest of the contents of this block.
2166 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002167 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002168}
2169
James Dennettf6333ac2012-06-22 05:46:07 +00002170/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002171///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002172void Preprocessor::HandleElifDirective(Token &ElifToken) {
Aaron Ballman6ce00002013-01-16 19:32:21 +00002173 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002174 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002175
Chris Lattnerf64b3522008-03-09 01:54:53 +00002176 // #elif directive in a non-skipping conditional... start skipping.
2177 // We don't care what the condition is, because we will always skip it (since
2178 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002179 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002180 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002181 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002182
2183 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002184 if (CurPPLexer->popConditionalLevel(CI)) {
2185 Diag(ElifToken, diag::pp_err_elif_without_if);
2186 return;
2187 }
Mike Stump11289f42009-09-09 15:08:12 +00002188
Chris Lattnerf64b3522008-03-09 01:54:53 +00002189 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002190 if (CurPPLexer->getConditionalStackDepth() == 0)
2191 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002192
Chris Lattnerf64b3522008-03-09 01:54:53 +00002193 // If this is a #elif with a #else before it, report the error.
2194 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002195
2196 if (Callbacks)
2197 Callbacks->Elif(ElifToken.getLocation(),
2198 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002199
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002200 // Finally, skip the rest of the contents of this block.
2201 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002202 /*FoundElse*/CI.FoundElse,
2203 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002204}