blob: 050ade45e4435ea757e6a46961abfada85f1fb9c [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"
Daniel Jasper07e6c402013-08-05 20:26:17 +000020#include "clang/Lex/HeaderSearchOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/LexDiagnostic.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/ModuleLoader.h"
25#include "clang/Lex/Pragma.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000026#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000027#include "llvm/Support/ErrorHandling.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000028#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000029using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Utility Methods for Preprocessor Directive Handling.
33//===----------------------------------------------------------------------===//
34
Chris Lattnerc0a585d2010-08-17 15:55:45 +000035MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000036 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000037
Ted Kremenekc8456f82010-10-19 22:15:20 +000038 if (MICache) {
39 MIChain = MICache;
40 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000041 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000042 else {
43 MIChain = BP.Allocate<MacroInfoChain>();
44 }
45
46 MIChain->Next = MIChainHead;
47 MIChain->Prev = 0;
48 if (MIChainHead)
49 MIChainHead->Prev = MIChain;
50 MIChainHead = MIChain;
51
52 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000053}
54
55MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
56 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000057 new (MI) MacroInfo(L);
58 return MI;
59}
60
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000061MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
62 unsigned SubModuleID) {
Chandler Carruth06dde922014-03-02 13:02:01 +000063 static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
64 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000065 DeserializedMacroInfoChain *MIChain =
66 BP.Allocate<DeserializedMacroInfoChain>();
67 MIChain->Next = DeserialMIChainHead;
68 DeserialMIChainHead = MIChain;
69
70 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000071 new (MI) MacroInfo(L);
72 MI->FromASTFile = true;
73 MI->setOwningModuleID(SubModuleID);
74 return MI;
75}
76
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000077DefMacroDirective *
78Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc,
79 bool isImported) {
80 DefMacroDirective *MD = BP.Allocate<DefMacroDirective>();
81 new (MD) DefMacroDirective(MI, Loc, isImported);
82 return MD;
83}
84
85UndefMacroDirective *
86Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
87 UndefMacroDirective *MD = BP.Allocate<UndefMacroDirective>();
88 new (MD) UndefMacroDirective(UndefLoc);
89 return MD;
90}
91
92VisibilityMacroDirective *
93Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
94 bool isPublic) {
95 VisibilityMacroDirective *MD = BP.Allocate<VisibilityMacroDirective>();
96 new (MD) VisibilityMacroDirective(Loc, isPublic);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000097 return MD;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000098}
99
James Dennettf6333ac2012-06-22 05:46:07 +0000100/// \brief Release the specified MacroInfo to be reused for allocating
101/// new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +0000102void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +0000103 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
104 if (MacroInfoChain *Prev = MIChain->Prev) {
105 MacroInfoChain *Next = MIChain->Next;
106 Prev->Next = Next;
107 if (Next)
108 Next->Prev = Prev;
109 }
110 else {
111 assert(MIChainHead == MIChain);
112 MIChainHead = MIChain->Next;
113 MIChainHead->Prev = 0;
114 }
115 MIChain->Next = MICache;
116 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +0000117
Ted Kremenekc8456f82010-10-19 22:15:20 +0000118 MI->Destroy();
119}
Chris Lattner666f7a42009-02-20 22:19:20 +0000120
James Dennettf6333ac2012-06-22 05:46:07 +0000121/// \brief Read and discard all tokens remaining on the current line until
122/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000123void Preprocessor::DiscardUntilEndOfDirective() {
124 Token Tmp;
125 do {
126 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000127 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000128 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000129}
130
James Dennettf6333ac2012-06-22 05:46:07 +0000131/// \brief Lex and validate a macro name, which occurs after a
132/// \#define or \#undef.
133///
134/// This sets the token kind to eod and discards the rest
135/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
136/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
137/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000138void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
139 // Read the token, don't allow macro expansion on it.
140 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Douglas Gregor12785102010-08-24 20:21:13 +0000142 if (MacroNameTok.is(tok::code_completion)) {
143 if (CodeComplete)
144 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000145 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000146 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000147 }
148
Chris Lattnerf64b3522008-03-09 01:54:53 +0000149 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000150 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000151 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
152 return;
153 }
Mike Stump11289f42009-09-09 15:08:12 +0000154
Chris Lattnerf64b3522008-03-09 01:54:53 +0000155 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
156 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000157 bool Invalid = false;
158 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
159 if (Invalid)
160 return;
Nico Weber2e686202012-02-29 22:54:43 +0000161
Chris Lattner77c76ae2008-12-13 20:12:40 +0000162 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000163
164 // Allow #defining |and| and friends in microsoft mode.
Alp Tokerbfa39342014-01-14 12:51:41 +0000165 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MSVCCompat) {
Nico Weber2e686202012-02-29 22:54:43 +0000166 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
167 return;
168 }
169
Chris Lattner77c76ae2008-12-13 20:12:40 +0000170 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000171 // C++ 2.5p2: Alternative tokens behave the same as its primary token
172 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000173 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000174 else
175 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
176 // Fall through on error.
177 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Richard Smith7b242542013-03-06 00:46:00 +0000178 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000179 Diag(MacroNameTok, diag::err_defined_macro_name);
Richard Smith7b242542013-03-06 00:46:00 +0000180 } else if (isDefineUndef == 2 && II->hasMacroDefinition() &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000181 getMacroInfo(II)->isBuiltinMacro()) {
Richard Smith7b242542013-03-06 00:46:00 +0000182 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
183 // and C++ [cpp.predefined]p4], but allow it as an extension.
184 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
185 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000186 } else {
187 // Okay, we got a good identifier node. Return it.
188 return;
189 }
Mike Stump11289f42009-09-09 15:08:12 +0000190
Chris Lattnerf64b3522008-03-09 01:54:53 +0000191 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000192 // token kind to tok::eod.
193 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000194 return DiscardUntilEndOfDirective();
195}
196
James Dennettf6333ac2012-06-22 05:46:07 +0000197/// \brief Ensure that the next token is a tok::eod token.
198///
199/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000200/// true, then we consider macros that expand to zero tokens as being ok.
201void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000202 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000203 // Lex unexpanded tokens for most directives: macros might expand to zero
204 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
205 // #line) allow empty macros.
206 if (EnableMacros)
207 Lex(Tmp);
208 else
209 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattnerf64b3522008-03-09 01:54:53 +0000211 // There should be no tokens after the directive, but we allow them as an
212 // extension.
213 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
214 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000215
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000216 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000217 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000218 // or if this is a macro-style preprocessing directive, because it is more
219 // trouble than it is worth to insert /**/ and check that there is no /**/
220 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000221 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000222 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000223 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000224 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
225 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000226 DiscardUntilEndOfDirective();
227 }
228}
229
230
231
James Dennettf6333ac2012-06-22 05:46:07 +0000232/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
233/// decided that the subsequent tokens are in the \#if'd out portion of the
234/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000235/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000236/// this \#if directive, so \#else/\#elif blocks should never be entered.
237/// If ElseOk is true, then \#else directives are ok, if not, then we have
238/// already seen one so a \#else directive is a duplicate. When this returns,
239/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000240void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
241 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000242 bool FoundElse,
243 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000244 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000245 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000246
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000247 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000248 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000249
Ted Kremenek56572ab2008-12-12 18:34:08 +0000250 if (CurPTHLexer) {
251 PTHSkipExcludedConditionalBlock();
252 return;
253 }
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattnerf64b3522008-03-09 01:54:53 +0000255 // Enter raw mode to disable identifier lookup (and thus macro expansion),
256 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000257 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000258 Token Tok;
259 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000260 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000262 if (Tok.is(tok::code_completion)) {
263 if (CodeComplete)
264 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000265 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000266 continue;
267 }
268
Chris Lattnerf64b3522008-03-09 01:54:53 +0000269 // If this is the end of the buffer, we have an error.
270 if (Tok.is(tok::eof)) {
271 // Emit errors for each unterminated conditional on the stack, including
272 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000273 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000274 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000275 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
276 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000277 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000278 }
279
Chris Lattnerf64b3522008-03-09 01:54:53 +0000280 // Just return and let the caller lex after this #include.
281 break;
282 }
Mike Stump11289f42009-09-09 15:08:12 +0000283
Chris Lattnerf64b3522008-03-09 01:54:53 +0000284 // If this token is not a preprocessor directive, just skip it.
285 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
286 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000287
Chris Lattnerf64b3522008-03-09 01:54:53 +0000288 // We just parsed a # character at the start of a line, so we're in
289 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000290 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000291 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000292 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000293
Mike Stump11289f42009-09-09 15:08:12 +0000294
Chris Lattnerf64b3522008-03-09 01:54:53 +0000295 // Read the next token, the directive flavor.
296 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000297
Chris Lattnerf64b3522008-03-09 01:54:53 +0000298 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
299 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000300 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000301 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000302 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000303 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000304 continue;
305 }
306
307 // If the first letter isn't i or e, it isn't intesting to us. We know that
308 // this is safe in the face of spelling differences, because there is no way
309 // to spell an i/e in a strange way that is another letter. Skipping this
310 // allows us to avoid looking up the identifier info for #define/#undef and
311 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000312 const char *RawCharData = Tok.getRawIdentifierData();
313
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000315 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000316 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000317 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000318 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000319 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000320 continue;
321 }
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattnerf64b3522008-03-09 01:54:53 +0000323 // Get the identifier name without trigraphs or embedded newlines. Note
324 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
325 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000326 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000327 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000328 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000329 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000330 } else {
331 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000332 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000333 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000334 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000335 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000336 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000337 continue;
338 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000339 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000340 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000341 }
Mike Stump11289f42009-09-09 15:08:12 +0000342
Benjamin Kramer144884642009-12-31 13:32:38 +0000343 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000344 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000345 if (Sub.empty() || // "if"
346 Sub == "def" || // "ifdef"
347 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000348 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
349 // bother parsing the condition.
350 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000351 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000352 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000353 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000354 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000355 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000356 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000357 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000358 PPConditionalInfo CondInfo;
359 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000360 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000361 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000363
Chris Lattnerf64b3522008-03-09 01:54:53 +0000364 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000365 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000366 // Restore the value of LexingRawMode so that trailing comments
367 // are handled correctly, if we've reached the outermost block.
368 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000369 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000370 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000371 if (Callbacks)
372 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000373 break;
Richard Smithd0124572012-06-21 00:35:03 +0000374 } else {
375 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000376 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000377 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000378 // #else directive in a skipping conditional. If not in some other
379 // skipping conditional, and if #else hasn't already been seen, enter it
380 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000381 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattnerf64b3522008-03-09 01:54:53 +0000383 // If this is a #else with a #else before it, report the error.
384 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 // Note that we've seen a #else in this conditional.
387 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000388
Chris Lattnerf64b3522008-03-09 01:54:53 +0000389 // If the conditional is at the top level, and the #if block wasn't
390 // entered, enter the #else block now.
391 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
392 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000393 // Restore the value of LexingRawMode so that trailing comments
394 // are handled correctly.
395 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000396 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000397 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000398 if (Callbacks)
399 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000400 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000401 } else {
402 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000403 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000404 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000405 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000406
John Thompson17c35732013-12-04 20:19:30 +0000407 // If this is a #elif with a #else before it, report the error.
408 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
409
Chris Lattnerf64b3522008-03-09 01:54:53 +0000410 // If this is in a skipping block or if we're already handled this #if
411 // block, don't bother parsing the condition.
412 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
413 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000414 } else {
John Thompson17c35732013-12-04 20:19:30 +0000415 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000416 // Restore the value of LexingRawMode so that identifiers are
417 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000418 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
419 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000420 IdentifierInfo *IfNDefMacro = 0;
John Thompson17c35732013-12-04 20:19:30 +0000421 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000422 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000423 if (Callbacks) {
424 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000425 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000426 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000427 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000428 }
429 // If this condition is true, enter it!
430 if (CondValue) {
431 CondInfo.FoundNonSkip = true;
432 break;
433 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000434 }
435 }
436 }
Mike Stump11289f42009-09-09 15:08:12 +0000437
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000438 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000439 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000440 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000441 }
442
443 // Finally, if we are out of the conditional (saw an #endif or ran off the end
444 // of the file, just stop skipping and return to lexing whatever came after
445 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000446 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000447
448 if (Callbacks) {
449 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
450 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
451 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000452}
453
Ted Kremenek56572ab2008-12-12 18:34:08 +0000454void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000455
456 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000457 assert(CurPTHLexer);
458 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000459
Ted Kremenek56572ab2008-12-12 18:34:08 +0000460 // Skip to the next '#else', '#elif', or #endif.
461 if (CurPTHLexer->SkipBlock()) {
462 // We have reached an #endif. Both the '#' and 'endif' tokens
463 // have been consumed by the PTHLexer. Just pop off the condition level.
464 PPConditionalInfo CondInfo;
465 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000466 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000467 assert(!InCond && "Can't be skipping if not in a conditional!");
468 break;
469 }
Mike Stump11289f42009-09-09 15:08:12 +0000470
Ted Kremenek56572ab2008-12-12 18:34:08 +0000471 // We have reached a '#else' or '#elif'. Lex the next token to get
472 // the directive flavor.
473 Token Tok;
474 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000475
Ted Kremenek56572ab2008-12-12 18:34:08 +0000476 // We can actually look up the IdentifierInfo here since we aren't in
477 // raw mode.
478 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
479
480 if (K == tok::pp_else) {
481 // #else: Enter the else condition. We aren't in a nested condition
482 // since we skip those. We're always in the one matching the last
483 // blocked we skipped.
484 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
485 // Note that we've seen a #else in this conditional.
486 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000487
Ted Kremenek56572ab2008-12-12 18:34:08 +0000488 // If the #if block wasn't entered then enter the #else block now.
489 if (!CondInfo.FoundNonSkip) {
490 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000491
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000492 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000493 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000494 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000495 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000496
Ted Kremenek56572ab2008-12-12 18:34:08 +0000497 break;
498 }
Mike Stump11289f42009-09-09 15:08:12 +0000499
Ted Kremenek56572ab2008-12-12 18:34:08 +0000500 // Otherwise skip this block.
501 continue;
502 }
Mike Stump11289f42009-09-09 15:08:12 +0000503
Ted Kremenek56572ab2008-12-12 18:34:08 +0000504 assert(K == tok::pp_elif);
505 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
506
507 // If this is a #elif with a #else before it, report the error.
508 if (CondInfo.FoundElse)
509 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000510
Ted Kremenek56572ab2008-12-12 18:34:08 +0000511 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000512 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000513 if (CondInfo.FoundNonSkip)
514 continue;
515
516 // Evaluate the condition of the #elif.
517 IdentifierInfo *IfNDefMacro = 0;
518 CurPTHLexer->ParsingPreprocessorDirective = true;
519 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
520 CurPTHLexer->ParsingPreprocessorDirective = false;
521
522 // If this condition is true, enter it!
523 if (ShouldEnter) {
524 CondInfo.FoundNonSkip = true;
525 break;
526 }
527
528 // Otherwise, skip this block and go to the next one.
529 continue;
530 }
531}
532
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000533Module *Preprocessor::getModuleForLocation(SourceLocation FilenameLoc) {
534 ModuleMap &ModMap = HeaderInfo.getModuleMap();
535 if (SourceMgr.isInMainFile(FilenameLoc)) {
536 if (Module *CurMod = getCurrentModule())
537 return CurMod; // Compiling a module.
538 return HeaderInfo.getModuleMap().SourceModule; // Compiling a source.
539 }
540 // Try to determine the module of the include directive.
Daniel Jasper88d86952013-12-03 20:30:36 +0000541 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
542 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getSpellingLoc(FilenameLoc));
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000543 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
544 // The include comes from a file.
545 return ModMap.findModuleForHeader(EntryOfIncl).getModule();
546 } else {
547 // The include does not come from a file,
548 // so it is probably a module compilation.
549 return getCurrentModule();
550 }
551}
552
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000553const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000554 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000555 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000556 bool isAngled,
557 const DirectoryLookup *FromDir,
558 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000559 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000560 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000561 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000562 bool SkipCache) {
Will Wilson0fafd342013-12-27 19:46:16 +0000563 // If the header lookup mechanism may be relative to the current inclusion
564 // stack, record the parent #includes.
565 SmallVector<const FileEntry *, 16> Includers;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000566 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000567 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000568 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000569
Chris Lattner022923a2009-02-04 19:45:07 +0000570 // If there is no file entry associated with this file, it must be the
571 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000572 // it won't be scanned for preprocessor directives. If we have the
573 // predefines buffer, resolve #include references (which come from the
574 // -include command line argument) as if they came from the main file, this
575 // affects file lookup etc.
Will Wilson0fafd342013-12-27 19:46:16 +0000576 if (!FileEnt)
577 FileEnt = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
578
579 if (FileEnt)
580 Includers.push_back(FileEnt);
581
582 // MSVC searches the current include stack from top to bottom for
583 // headers included by quoted include directives.
584 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000585 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000586 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
587 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
588 if (IsFileLexer(ISEntry))
589 if ((FileEnt = SourceMgr.getFileEntryForID(
590 ISEntry.ThePPLexer->getFileID())))
591 Includers.push_back(FileEnt);
592 }
Chris Lattner022923a2009-02-04 19:45:07 +0000593 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000594 }
Mike Stump11289f42009-09-09 15:08:12 +0000595
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000596 // Do a standard file entry lookup.
597 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000598 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000599 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
600 RelativePath, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000601 if (FE) {
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000602 if (SuggestedModule)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000603 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
604 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000605 return FE;
606 }
Mike Stump11289f42009-09-09 15:08:12 +0000607
Will Wilson0fafd342013-12-27 19:46:16 +0000608 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000609 // Otherwise, see if this is a subframework header. If so, this is relative
610 // to one of the headers on the #include stack. Walk the list of the current
611 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000612 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000613 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000614 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000615 SearchPath, RelativePath,
616 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000617 return FE;
618 }
Mike Stump11289f42009-09-09 15:08:12 +0000619
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000620 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
621 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000622 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000623 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000624 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000625 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000626 Filename, CurFileEnt, SearchPath, RelativePath,
627 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000628 return FE;
629 }
630 }
Mike Stump11289f42009-09-09 15:08:12 +0000631
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000632 // Otherwise, we really couldn't find the file.
633 return 0;
634}
635
Chris Lattnerf64b3522008-03-09 01:54:53 +0000636
637//===----------------------------------------------------------------------===//
638// Preprocessor Directive Handling.
639//===----------------------------------------------------------------------===//
640
David Blaikied5321242012-06-06 18:52:13 +0000641class Preprocessor::ResetMacroExpansionHelper {
642public:
643 ResetMacroExpansionHelper(Preprocessor *pp)
644 : PP(pp), save(pp->DisableMacroExpansion) {
645 if (pp->MacroExpansionInDirectivesOverride)
646 pp->DisableMacroExpansion = false;
647 }
648 ~ResetMacroExpansionHelper() {
649 PP->DisableMacroExpansion = save;
650 }
651private:
652 Preprocessor *PP;
653 bool save;
654};
655
Chris Lattnerf64b3522008-03-09 01:54:53 +0000656/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000657/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000658/// lexer/preprocessor state, and advances the lexer(s) so that the next token
659/// read is the correct one.
660void Preprocessor::HandleDirective(Token &Result) {
661 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000662
Chris Lattnerf64b3522008-03-09 01:54:53 +0000663 // We just parsed a # character at the start of a line, so we're in directive
664 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000665 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000666 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000667 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000668
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000669 bool ImmediatelyAfterTopLevelIfndef =
670 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
671 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
672
Chris Lattnerf64b3522008-03-09 01:54:53 +0000673 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000674
Chris Lattnerf64b3522008-03-09 01:54:53 +0000675 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000676 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000677 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000678 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000679
Chris Lattner2d17ab72009-03-18 21:00:25 +0000680 // Save the '#' token in case we need to return it later.
681 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000682
Chris Lattnerf64b3522008-03-09 01:54:53 +0000683 // Read the next token, the directive flavor. This isn't expanded due to
684 // C99 6.10.3p8.
685 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000686
Chris Lattnerf64b3522008-03-09 01:54:53 +0000687 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
688 // #define A(x) #x
689 // A(abc
690 // #warning blah
691 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000692 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
693 // not support this for #include-like directives, since that can result in
694 // terrible diagnostics, and does not work in GCC.
695 if (InMacroArgs) {
696 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
697 switch (II->getPPKeywordID()) {
698 case tok::pp_include:
699 case tok::pp_import:
700 case tok::pp_include_next:
701 case tok::pp___include_macros:
702 Diag(Result, diag::err_embedded_include) << II->getName();
703 DiscardUntilEndOfDirective();
704 return;
705 default:
706 break;
707 }
708 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000709 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000710 }
Mike Stump11289f42009-09-09 15:08:12 +0000711
David Blaikied5321242012-06-06 18:52:13 +0000712 // Temporarily enable macro expansion if set so
713 // and reset to previous state when returning from this function.
714 ResetMacroExpansionHelper helper(this);
715
Chris Lattnerf64b3522008-03-09 01:54:53 +0000716 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000717 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000718 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000719 case tok::code_completion:
720 if (CodeComplete)
721 CodeComplete->CodeCompleteDirective(
722 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000723 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000724 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000725 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000726 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000727 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000728 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000729 default:
730 IdentifierInfo *II = Result.getIdentifierInfo();
731 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattnerf64b3522008-03-09 01:54:53 +0000733 // Ask what the preprocessor keyword ID is.
734 switch (II->getPPKeywordID()) {
735 default: break;
736 // C99 6.10.1 - Conditional Inclusion.
737 case tok::pp_if:
738 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
739 case tok::pp_ifdef:
740 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
741 case tok::pp_ifndef:
742 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
743 case tok::pp_elif:
744 return HandleElifDirective(Result);
745 case tok::pp_else:
746 return HandleElseDirective(Result);
747 case tok::pp_endif:
748 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000749
Chris Lattnerf64b3522008-03-09 01:54:53 +0000750 // C99 6.10.2 - Source File Inclusion.
751 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000752 // Handle #include.
753 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000754 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000755 // Handle -imacros.
756 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000757
Chris Lattnerf64b3522008-03-09 01:54:53 +0000758 // C99 6.10.3 - Macro Replacement.
759 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000760 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000761 case tok::pp_undef:
762 return HandleUndefDirective(Result);
763
764 // C99 6.10.4 - Line Control.
765 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000766 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000767
Chris Lattnerf64b3522008-03-09 01:54:53 +0000768 // C99 6.10.5 - Error Directive.
769 case tok::pp_error:
770 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000771
Chris Lattnerf64b3522008-03-09 01:54:53 +0000772 // C99 6.10.6 - Pragma Directive.
773 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000774 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000775
Chris Lattnerf64b3522008-03-09 01:54:53 +0000776 // GNU Extensions.
777 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000778 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000779 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000780 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000781
Chris Lattnerf64b3522008-03-09 01:54:53 +0000782 case tok::pp_warning:
783 Diag(Result, diag::ext_pp_warning_directive);
784 return HandleUserDiagnosticDirective(Result, true);
785 case tok::pp_ident:
786 return HandleIdentSCCSDirective(Result);
787 case tok::pp_sccs:
788 return HandleIdentSCCSDirective(Result);
789 case tok::pp_assert:
790 //isExtension = true; // FIXME: implement #assert
791 break;
792 case tok::pp_unassert:
793 //isExtension = true; // FIXME: implement #unassert
794 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000795
Douglas Gregor663b48f2012-01-03 19:48:16 +0000796 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000797 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000798 return HandleMacroPublicDirective(Result);
799 break;
800
Douglas Gregor663b48f2012-01-03 19:48:16 +0000801 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000802 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000803 return HandleMacroPrivateDirective(Result);
804 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000805 }
806 break;
807 }
Mike Stump11289f42009-09-09 15:08:12 +0000808
Chris Lattner2d17ab72009-03-18 21:00:25 +0000809 // If this is a .S file, treat unknown # directives as non-preprocessor
810 // directives. This is important because # may be a comment or introduce
811 // various pseudo-ops. Just return the # token and push back the following
812 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000813 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000814 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000815 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000816 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000817 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000818
819 // If the second token is a hashhash token, then we need to translate it to
820 // unknown so the token lexer doesn't try to perform token pasting.
821 if (Result.is(tok::hashhash))
822 Toks[1].setKind(tok::unknown);
823
Chris Lattner2d17ab72009-03-18 21:00:25 +0000824 // Enter this token stream so that we re-lex the tokens. Make sure to
825 // enable macro expansion, in case the token after the # is an identifier
826 // that is expanded.
827 EnterTokenStream(Toks, 2, false, true);
828 return;
829 }
Mike Stump11289f42009-09-09 15:08:12 +0000830
Chris Lattnerf64b3522008-03-09 01:54:53 +0000831 // If we reached here, the preprocessing token is not valid!
832 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000833
Chris Lattnerf64b3522008-03-09 01:54:53 +0000834 // Read the rest of the PP line.
835 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattnerf64b3522008-03-09 01:54:53 +0000837 // Okay, we're done parsing the directive.
838}
839
Chris Lattner76e68962009-01-26 06:19:46 +0000840/// GetLineValue - Convert a numeric token into an unsigned value, emitting
841/// Diagnostic DiagID if it is invalid, and returning the value in Val.
842static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000843 unsigned DiagID, Preprocessor &PP,
844 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000845 if (DigitTok.isNot(tok::numeric_constant)) {
846 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000847
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000848 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000849 PP.DiscardUntilEndOfDirective();
850 return true;
851 }
Mike Stump11289f42009-09-09 15:08:12 +0000852
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000853 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000854 IntegerBuffer.resize(DigitTok.getLength());
855 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000856 bool Invalid = false;
857 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
858 if (Invalid)
859 return true;
860
Chris Lattnerd66f1722009-04-18 18:35:15 +0000861 // Verify that we have a simple digit-sequence, and compute the value. This
862 // is always a simple digit string computed in decimal, so we do this manually
863 // here.
864 Val = 0;
865 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +0000866 // C++1y [lex.fcon]p1:
867 // Optional separating single quotes in a digit-sequence are ignored
868 if (DigitTokBegin[i] == '\'')
869 continue;
870
Jordan Rosea7d03842013-02-08 22:30:41 +0000871 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000872 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000873 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000874 PP.DiscardUntilEndOfDirective();
875 return true;
876 }
Mike Stump11289f42009-09-09 15:08:12 +0000877
Chris Lattnerd66f1722009-04-18 18:35:15 +0000878 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
879 if (NextVal < Val) { // overflow.
880 PP.Diag(DigitTok, DiagID);
881 PP.DiscardUntilEndOfDirective();
882 return true;
883 }
884 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000885 }
Mike Stump11289f42009-09-09 15:08:12 +0000886
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000887 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000888 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
889 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000890
Chris Lattner76e68962009-01-26 06:19:46 +0000891 return false;
892}
893
James Dennettf6333ac2012-06-22 05:46:07 +0000894/// \brief Handle a \#line directive: C99 6.10.4.
895///
896/// The two acceptable forms are:
897/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000898/// # line digit-sequence
899/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000900/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000901void Preprocessor::HandleLineDirective(Token &Tok) {
902 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
903 // expanded.
904 Token DigitTok;
905 Lex(DigitTok);
906
Chris Lattner100c65e2009-01-26 05:29:08 +0000907 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000908 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000909 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000910 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000911
912 if (LineNo == 0)
913 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000914
Chris Lattner76e68962009-01-26 06:19:46 +0000915 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
916 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000917 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000918 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000919 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000920 if (LineNo >= LineLimit)
921 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000922 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000923 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000925 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000926 Token StrTok;
927 Lex(StrTok);
928
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000929 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
930 // string followed by eod.
931 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000932 ; // ok
933 else if (StrTok.isNot(tok::string_literal)) {
934 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000935 return DiscardUntilEndOfDirective();
936 } else if (StrTok.hasUDSuffix()) {
937 Diag(StrTok, diag::err_invalid_string_udl);
938 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000939 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000940 // Parse and validate the string, converting it into a unique ID.
941 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000942 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000943 if (Literal.hadError)
944 return DiscardUntilEndOfDirective();
945 if (Literal.Pascal) {
946 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
947 return DiscardUntilEndOfDirective();
948 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000949 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000950
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000951 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000952 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
953 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000954 }
Mike Stump11289f42009-09-09 15:08:12 +0000955
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000956 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000957
Chris Lattner839150e2009-03-27 17:13:49 +0000958 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000959 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
960 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000961 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000962}
963
Chris Lattner76e68962009-01-26 06:19:46 +0000964/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
965/// marker directive.
966static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
967 bool &IsSystemHeader, bool &IsExternCHeader,
968 Preprocessor &PP) {
969 unsigned FlagVal;
970 Token FlagTok;
971 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000972 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000973 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
974 return true;
975
976 if (FlagVal == 1) {
977 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattner76e68962009-01-26 06:19:46 +0000979 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000980 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000981 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
982 return true;
983 } else if (FlagVal == 2) {
984 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattner1c967782009-02-04 06:25:26 +0000986 SourceManager &SM = PP.getSourceManager();
987 // If we are leaving the current presumed file, check to make sure the
988 // presumed include stack isn't empty!
989 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000990 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000991 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000992 if (PLoc.isInvalid())
993 return true;
994
Chris Lattner1c967782009-02-04 06:25:26 +0000995 // If there is no include loc (main file) or if the include loc is in a
996 // different physical file, then we aren't in a "1" line marker flag region.
997 SourceLocation IncLoc = PLoc.getIncludeLoc();
998 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000999 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001000 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1001 PP.DiscardUntilEndOfDirective();
1002 return true;
1003 }
Mike Stump11289f42009-09-09 15:08:12 +00001004
Chris Lattner76e68962009-01-26 06:19:46 +00001005 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001006 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001007 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1008 return true;
1009 }
1010
1011 // We must have 3 if there are still flags.
1012 if (FlagVal != 3) {
1013 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001014 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001015 return true;
1016 }
Mike Stump11289f42009-09-09 15:08:12 +00001017
Chris Lattner76e68962009-01-26 06:19:46 +00001018 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001019
Chris Lattner76e68962009-01-26 06:19:46 +00001020 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001021 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001022 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001023 return true;
1024
1025 // We must have 4 if there is yet another flag.
1026 if (FlagVal != 4) {
1027 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001028 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001029 return true;
1030 }
Mike Stump11289f42009-09-09 15:08:12 +00001031
Chris Lattner76e68962009-01-26 06:19:46 +00001032 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001033
Chris Lattner76e68962009-01-26 06:19:46 +00001034 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001035 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001036
1037 // There are no more valid flags here.
1038 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001039 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001040 return true;
1041}
1042
1043/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1044/// one of the following forms:
1045///
1046/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001047/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001048/// # 42 "file" ('1' | '2')? '3' '4'?
1049///
1050void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1051 // Validate the number and convert it to an unsigned. GNU does not have a
1052 // line # limit other than it fit in 32-bits.
1053 unsigned LineNo;
1054 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001055 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001056 return;
Mike Stump11289f42009-09-09 15:08:12 +00001057
Chris Lattner76e68962009-01-26 06:19:46 +00001058 Token StrTok;
1059 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001060
Chris Lattner76e68962009-01-26 06:19:46 +00001061 bool IsFileEntry = false, IsFileExit = false;
1062 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001063 int FilenameID = -1;
1064
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001065 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1066 // string followed by eod.
1067 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001068 ; // ok
1069 else if (StrTok.isNot(tok::string_literal)) {
1070 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001071 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001072 } else if (StrTok.hasUDSuffix()) {
1073 Diag(StrTok, diag::err_invalid_string_udl);
1074 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001075 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001076 // Parse and validate the string, converting it into a unique ID.
1077 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001078 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001079 if (Literal.hadError)
1080 return DiscardUntilEndOfDirective();
1081 if (Literal.Pascal) {
1082 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1083 return DiscardUntilEndOfDirective();
1084 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001085 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001086
Chris Lattner76e68962009-01-26 06:19:46 +00001087 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001088 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001089 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001090 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001091 }
Mike Stump11289f42009-09-09 15:08:12 +00001092
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001093 // Create a line note with this information.
1094 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001095 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001096 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001097
Chris Lattner839150e2009-03-27 17:13:49 +00001098 // If the preprocessor has callbacks installed, notify them of the #line
1099 // change. This is used so that the line marker comes out in -E mode for
1100 // example.
1101 if (Callbacks) {
1102 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1103 if (IsFileEntry)
1104 Reason = PPCallbacks::EnterFile;
1105 else if (IsFileExit)
1106 Reason = PPCallbacks::ExitFile;
1107 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1108 if (IsExternCHeader)
1109 FileKind = SrcMgr::C_ExternCSystem;
1110 else if (IsSystemHeader)
1111 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001112
Chris Lattnerc745cec2010-04-14 04:28:50 +00001113 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001114 }
Chris Lattner76e68962009-01-26 06:19:46 +00001115}
1116
1117
Chris Lattner38d7fd22009-01-26 05:30:54 +00001118/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1119///
Mike Stump11289f42009-09-09 15:08:12 +00001120void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001121 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001122 // PTH doesn't emit #warning or #error directives.
1123 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001124 return CurPTHLexer->DiscardToEndOfLine();
1125
Chris Lattnerf64b3522008-03-09 01:54:53 +00001126 // Read the rest of the line raw. We do this because we don't want macros
1127 // to be expanded and we don't require that the tokens be valid preprocessing
1128 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1129 // collapse multiple consequtive white space between tokens, but this isn't
1130 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001131 SmallString<128> Message;
1132 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001133
1134 // Find the first non-whitespace character, so that we can make the
1135 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001136 StringRef Msg = Message.str().ltrim(" ");
1137
Chris Lattner100c65e2009-01-26 05:29:08 +00001138 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001139 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001140 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001141 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001142}
1143
1144/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1145///
1146void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1147 // Yes, this directive is an extension.
1148 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001149
Chris Lattnerf64b3522008-03-09 01:54:53 +00001150 // Read the string argument.
1151 Token StrTok;
1152 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001153
Chris Lattnerf64b3522008-03-09 01:54:53 +00001154 // If the token kind isn't a string, it's a malformed directive.
1155 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001156 StrTok.isNot(tok::wide_string_literal)) {
1157 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001158 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001159 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001160 return;
1161 }
Mike Stump11289f42009-09-09 15:08:12 +00001162
Richard Smithd67aea22012-03-06 03:21:47 +00001163 if (StrTok.hasUDSuffix()) {
1164 Diag(StrTok, diag::err_invalid_string_udl);
1165 return DiscardUntilEndOfDirective();
1166 }
1167
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001168 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001169 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001170
Douglas Gregordc970f02010-03-16 22:30:13 +00001171 if (Callbacks) {
1172 bool Invalid = false;
1173 std::string Str = getSpelling(StrTok, &Invalid);
1174 if (!Invalid)
1175 Callbacks->Ident(Tok.getLocation(), Str);
1176 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001177}
1178
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001179/// \brief Handle a #public directive.
1180void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001181 Token MacroNameTok;
1182 ReadMacroName(MacroNameTok, 2);
1183
1184 // Error reading macro name? If so, diagnostic already issued.
1185 if (MacroNameTok.is(tok::eod))
1186 return;
1187
Douglas Gregor663b48f2012-01-03 19:48:16 +00001188 // Check to see if this is the last token on the #__public_macro line.
1189 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001190
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001191 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001192 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001193 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001194
1195 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001196 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001197 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001198 return;
1199 }
1200
1201 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001202 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1203 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001204}
1205
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001206/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001207void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1208 Token MacroNameTok;
1209 ReadMacroName(MacroNameTok, 2);
1210
1211 // Error reading macro name? If so, diagnostic already issued.
1212 if (MacroNameTok.is(tok::eod))
1213 return;
1214
Douglas Gregor663b48f2012-01-03 19:48:16 +00001215 // Check to see if this is the last token on the #__private_macro line.
1216 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001217
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001218 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001219 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001220 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001221
1222 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001223 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001224 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001225 return;
1226 }
1227
1228 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001229 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1230 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001231}
1232
Chris Lattnerf64b3522008-03-09 01:54:53 +00001233//===----------------------------------------------------------------------===//
1234// Preprocessor Include Directive Handling.
1235//===----------------------------------------------------------------------===//
1236
1237/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001238/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001239/// true if the input filename was in <>'s or false if it were in ""'s. The
1240/// caller is expected to provide a buffer that is large enough to hold the
1241/// spelling of the filename, but is also expected to handle the case when
1242/// this method decides to use a different buffer.
1243bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001244 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001245 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001246 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001247
Chris Lattnerf64b3522008-03-09 01:54:53 +00001248 // Make sure the filename is <x> or "x".
1249 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001250 if (Buffer[0] == '<') {
1251 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001252 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001253 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001254 return true;
1255 }
1256 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001257 } else if (Buffer[0] == '"') {
1258 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001259 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001260 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001261 return true;
1262 }
1263 isAngled = false;
1264 } else {
1265 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001266 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001267 return true;
1268 }
Mike Stump11289f42009-09-09 15:08:12 +00001269
Chris Lattnerf64b3522008-03-09 01:54:53 +00001270 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001271 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001272 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001273 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001274 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Chris Lattnerf64b3522008-03-09 01:54:53 +00001277 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001278 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001279 return isAngled;
1280}
1281
James Dennett4a4f72d2013-11-27 01:27:40 +00001282// \brief Handle cases where the \#include name is expanded from a macro
1283// as multiple tokens, which need to be glued together.
1284//
1285// This occurs for code like:
1286// \code
1287// \#define FOO <a/b.h>
1288// \#include FOO
1289// \endcode
1290// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1291//
1292// This code concatenates and consumes tokens up to the '>' token. It returns
1293// false if the > was found, otherwise it returns true if it finds and consumes
1294// the EOD marker.
1295bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001296 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001297 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001298
John Thompsonb5353522009-10-30 13:49:06 +00001299 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001300 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001301 End = CurTok.getLocation();
1302
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001303 // FIXME: Provide code completion for #includes.
1304 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001305 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001306 Lex(CurTok);
1307 continue;
1308 }
1309
Chris Lattnerf64b3522008-03-09 01:54:53 +00001310 // Append the spelling of this token to the buffer. If there was a space
1311 // before it, add it now.
1312 if (CurTok.hasLeadingSpace())
1313 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001314
Chris Lattnerf64b3522008-03-09 01:54:53 +00001315 // Get the spelling of the token, directly into FilenameBuffer if possible.
1316 unsigned PreAppendSize = FilenameBuffer.size();
1317 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001318
Chris Lattnerf64b3522008-03-09 01:54:53 +00001319 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001320 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001321
Chris Lattnerf64b3522008-03-09 01:54:53 +00001322 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1323 if (BufPtr != &FilenameBuffer[PreAppendSize])
1324 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001325
Chris Lattnerf64b3522008-03-09 01:54:53 +00001326 // Resize FilenameBuffer to the correct size.
1327 if (CurTok.getLength() != ActualLen)
1328 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001329
Chris Lattnerf64b3522008-03-09 01:54:53 +00001330 // If we found the '>' marker, return success.
1331 if (CurTok.is(tok::greater))
1332 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001333
John Thompsonb5353522009-10-30 13:49:06 +00001334 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001335 }
1336
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001337 // If we hit the eod marker, emit an error and return true so that the caller
1338 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001339 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001340 return true;
1341}
1342
Richard Smith34f30512013-11-23 04:06:09 +00001343/// \brief Push a token onto the token stream containing an annotation.
1344static void EnterAnnotationToken(Preprocessor &PP,
1345 SourceLocation Begin, SourceLocation End,
1346 tok::TokenKind Kind, void *AnnotationVal) {
1347 Token *Tok = new Token[1];
1348 Tok[0].startToken();
1349 Tok[0].setKind(Kind);
1350 Tok[0].setLocation(Begin);
1351 Tok[0].setAnnotationEndLoc(End);
1352 Tok[0].setAnnotationValue(AnnotationVal);
1353 PP.EnterTokenStream(Tok, 1, true, true);
1354}
1355
James Dennettf6333ac2012-06-22 05:46:07 +00001356/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1357/// the file to be included from the lexer, then include it! This is a common
1358/// routine with functionality shared between \#include, \#include_next and
1359/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001360/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001361void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1362 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001363 const DirectoryLookup *LookupFrom,
1364 bool isImport) {
1365
1366 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001367 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattnerf64b3522008-03-09 01:54:53 +00001369 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001370 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001371 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001372 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001373 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001374
Chris Lattnerf64b3522008-03-09 01:54:53 +00001375 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001376 case tok::eod:
1377 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001378 return;
Mike Stump11289f42009-09-09 15:08:12 +00001379
Chris Lattnerf64b3522008-03-09 01:54:53 +00001380 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001381 case tok::string_literal:
1382 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001383 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001384 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001385 break;
Mike Stump11289f42009-09-09 15:08:12 +00001386
Chris Lattnerf64b3522008-03-09 01:54:53 +00001387 case tok::less:
1388 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1389 // case, glue the tokens together into FilenameBuffer and interpret those.
1390 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001391 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001392 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001393 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001394 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001395 break;
1396 default:
1397 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1398 DiscardUntilEndOfDirective();
1399 return;
1400 }
Mike Stump11289f42009-09-09 15:08:12 +00001401
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001402 CharSourceRange FilenameRange
1403 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001404 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001405 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001406 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001407 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1408 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001409 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001410 DiscardUntilEndOfDirective();
1411 return;
1412 }
Mike Stump11289f42009-09-09 15:08:12 +00001413
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001414 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001415 // we allow macros that expand to nothing after the filename, because this
1416 // falls into the category of "#include pp-tokens new-line" specified in
1417 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001418 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001419
1420 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001421 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1422 Diag(FilenameTok, diag::err_pp_include_too_deep);
1423 return;
1424 }
Mike Stump11289f42009-09-09 15:08:12 +00001425
John McCall32f5fe12011-09-30 05:12:12 +00001426 // Complain about attempts to #include files in an audit pragma.
1427 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1428 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1429 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1430
1431 // Immediately leave the pragma.
1432 PragmaARCCFCodeAuditedLoc = SourceLocation();
1433 }
1434
Aaron Ballman611306e2012-03-02 22:51:54 +00001435 if (HeaderInfo.HasIncludeAliasMap()) {
1436 // Map the filename with the brackets still attached. If the name doesn't
1437 // map to anything, fall back on the filename we've already gotten the
1438 // spelling for.
1439 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1440 if (!NewName.empty())
1441 Filename = NewName;
1442 }
1443
Chris Lattnerf64b3522008-03-09 01:54:53 +00001444 // Search include directories.
1445 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001446 SmallString<1024> SearchPath;
1447 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001448 // We get the raw path only if we have 'Callbacks' to which we later pass
1449 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001450 ModuleMap::KnownHeader SuggestedModule;
1451 SourceLocation FilenameLoc = FilenameTok.getLocation();
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001452 const FileEntry *File = LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001453 FilenameLoc, Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001454 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
Daniel Jasper07e6c402013-08-05 20:26:17 +00001455 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001456
Douglas Gregor11729f02011-11-30 18:12:06 +00001457 if (Callbacks) {
1458 if (!File) {
1459 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001460 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001461 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1462 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1463 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001464 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001465 HeaderInfo.AddSearchPath(DL, isAngled);
1466
1467 // Try the lookup again, skipping the cache.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001468 File = LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, CurDir,
Daniel Jasper07e6c402013-08-05 20:26:17 +00001469 0, 0, HeaderInfo.getHeaderSearchOpts().ModuleMaps
1470 ? &SuggestedModule
1471 : 0,
1472 /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001473 }
1474 }
1475 }
1476
Daniel Jasper07e6c402013-08-05 20:26:17 +00001477 if (!SuggestedModule || !getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001478 // Notify the callback object that we've seen an inclusion directive.
1479 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1480 FilenameRange, File,
1481 SearchPath, RelativePath,
1482 /*ImportedModule=*/0);
1483 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001484 }
1485
1486 if (File == 0) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001487 if (!SuppressIncludeNotFoundError) {
1488 // If the file could not be located and it was included via angle
1489 // brackets, we can attempt a lookup as though it were a quoted path to
1490 // provide the user with a possible fixit.
1491 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001492 File = LookupFile(
1493 FilenameLoc, Filename, false, LookupFrom, CurDir,
1494 Callbacks ? &SearchPath : 0, Callbacks ? &RelativePath : 0,
1495 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : 0);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001496 if (File) {
1497 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1498 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1499 Filename <<
1500 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1501 }
1502 }
1503 // If the file is still not found, just go with the vanilla diagnostic
1504 if (!File)
1505 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1506 }
1507 if (!File)
1508 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001509 }
1510
Douglas Gregor97eec242011-09-15 22:00:41 +00001511 // If we are supposed to import a module rather than including the header,
1512 // do so now.
Daniel Jasper07e6c402013-08-05 20:26:17 +00001513 if (SuggestedModule && getLangOpts().Modules) {
Douglas Gregor71944202011-11-30 00:36:36 +00001514 // Compute the module access path corresponding to this module.
1515 // FIXME: Should we have a second loadModule() overload to avoid this
1516 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001517 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001518 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001519 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1520 FilenameTok.getLocation()));
1521 std::reverse(Path.begin(), Path.end());
1522
Douglas Gregor41e115a2011-11-30 18:02:36 +00001523 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001524 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001525 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1526 if (I)
1527 PathString += '.';
1528 PathString += Path[I].first->getName();
1529 }
1530 int IncludeKind = 0;
1531
1532 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1533 case tok::pp_include:
1534 IncludeKind = 0;
1535 break;
1536
1537 case tok::pp_import:
1538 IncludeKind = 1;
1539 break;
1540
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001541 case tok::pp_include_next:
1542 IncludeKind = 2;
1543 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001544
1545 case tok::pp___include_macros:
1546 IncludeKind = 3;
1547 break;
1548
1549 default:
1550 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001551 }
1552
Douglas Gregor2537a362011-12-08 17:01:29 +00001553 // Determine whether we are actually building the module that this
1554 // include directive maps to.
1555 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001556 = Path[0].first->getName() == getLangOpts().CurrentModule;
Richard Smith34f30512013-11-23 04:06:09 +00001557
David Blaikiebbafb8a2012-03-11 07:00:24 +00001558 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001559 // If we're not building the imported module, warn that we're going
1560 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001561 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001562 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1563 /*IsTokenRange=*/false);
1564 Diag(HashLoc, diag::warn_auto_module_import)
1565 << IncludeKind << PathString
1566 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001567 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001568 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001569
Richard Smithce587f52013-11-15 04:24:58 +00001570 // Load the module. Only make macros visible. We'll make the declarations
1571 // visible when the parser gets here.
1572 Module::NameVisibilityKind Visibility = Module::MacrosVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001573 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001574 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1575 /*IsIncludeDirective=*/true);
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001576 assert((Imported == 0 || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001577 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001578
1579 if (!Imported && hadModuleLoaderFatalFailure()) {
1580 // With a fatal failure in the module loader, we abort parsing.
1581 Token &Result = IncludeTok;
1582 if (CurLexer) {
1583 Result.startToken();
1584 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1585 CurLexer->cutOffLexing();
1586 } else {
1587 assert(CurPTHLexer && "#include but no current lexer set!");
1588 CurPTHLexer->getEOF(Result);
1589 }
1590 return;
1591 }
Richard Smithce587f52013-11-15 04:24:58 +00001592
Douglas Gregor2537a362011-12-08 17:01:29 +00001593 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001594 if (!BuildingImportedModule && Imported) {
1595 if (Callbacks) {
1596 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1597 FilenameRange, File,
1598 SearchPath, RelativePath, Imported);
1599 }
Richard Smithce587f52013-11-15 04:24:58 +00001600
1601 if (IncludeKind != 3) {
1602 // Let the parser know that we hit a module import, and it should
1603 // make the module visible.
1604 // FIXME: Produce this as the current token directly, rather than
1605 // allocating a new token for it.
Richard Smith34f30512013-11-23 04:06:09 +00001606 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include,
1607 Imported);
Richard Smithce587f52013-11-15 04:24:58 +00001608 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001609 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001610 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001611
1612 // If we failed to find a submodule that we expected to find, we can
1613 // continue. Otherwise, there's an error in the included file, so we
1614 // don't want to include it.
1615 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1616 return;
1617 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001618 }
1619
1620 if (Callbacks && SuggestedModule) {
1621 // We didn't notify the callback object that we've seen an inclusion
1622 // directive before. Now that we are parsing the include normally and not
1623 // turning it to a module import, notify the callback object.
1624 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1625 FilenameRange, File,
1626 SearchPath, RelativePath,
1627 /*ImportedModule=*/0);
Douglas Gregor97eec242011-09-15 22:00:41 +00001628 }
1629
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001630 // The #included file will be considered to be a system header if either it is
1631 // in a system include directory, or if the #includer is a system include
1632 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001633 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001634 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001635 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001636
Chris Lattner72286d62010-04-19 20:44:31 +00001637 // Ask HeaderInfo if we should enter this #include file. If not, #including
1638 // this file will have no effect.
1639 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001640 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001641 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001642 return;
1643 }
1644
Chris Lattnerf64b3522008-03-09 01:54:53 +00001645 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001646 SourceLocation IncludePos = End;
1647 // If the filename string was the result of macro expansions, set the include
1648 // position on the file where it will be included and after the expansions.
1649 if (IncludePos.isMacroID())
1650 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1651 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001652 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001653
Richard Smith34f30512013-11-23 04:06:09 +00001654 // Determine if we're switching to building a new submodule, and which one.
1655 ModuleMap::KnownHeader BuildingModule;
1656 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) {
1657 Module *RequestingModule = getModuleForLocation(FilenameLoc);
1658 BuildingModule =
1659 HeaderInfo.getModuleMap().findModuleForHeader(File, RequestingModule);
1660 }
1661
1662 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00001663 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
1664 return;
Richard Smith34f30512013-11-23 04:06:09 +00001665
1666 // If we're walking into another part of the same module, let the parser
1667 // know that any future declarations are within that other submodule.
Richard Smith67294e22014-01-31 20:47:44 +00001668 if (BuildingModule) {
1669 assert(!CurSubmodule && "should not have marked this as a module yet");
1670 CurSubmodule = BuildingModule.getModule();
1671
Richard Smith34f30512013-11-23 04:06:09 +00001672 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin,
Richard Smith67294e22014-01-31 20:47:44 +00001673 CurSubmodule);
1674 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001675}
1676
James Dennettf6333ac2012-06-22 05:46:07 +00001677/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001678///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001679void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1680 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001681 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001682
Chris Lattnerf64b3522008-03-09 01:54:53 +00001683 // #include_next is like #include, except that we start searching after
1684 // the current found directory. If we can't do this, issue a
1685 // diagnostic.
1686 const DirectoryLookup *Lookup = CurDirLookup;
1687 if (isInPrimaryFile()) {
1688 Lookup = 0;
1689 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1690 } else if (Lookup == 0) {
1691 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1692 } else {
1693 // Start looking up in the next directory.
1694 ++Lookup;
1695 }
Mike Stump11289f42009-09-09 15:08:12 +00001696
Douglas Gregor796d76a2010-10-20 22:00:55 +00001697 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001698}
1699
James Dennettf6333ac2012-06-22 05:46:07 +00001700/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001701void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1702 // The Microsoft #import directive takes a type library and generates header
1703 // files from it, and includes those. This is beyond the scope of what clang
1704 // does, so we ignore it and error out. However, #import can optionally have
1705 // trailing attributes that span multiple lines. We're going to eat those
1706 // so we can continue processing from there.
1707 Diag(Tok, diag::err_pp_import_directive_ms );
1708
1709 // Read tokens until we get to the end of the directive. Note that the
1710 // directive can be split over multiple lines using the backslash character.
1711 DiscardUntilEndOfDirective();
1712}
1713
James Dennettf6333ac2012-06-22 05:46:07 +00001714/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001715///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001716void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1717 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001718 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00001719 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00001720 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001721 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001722 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001723 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001724}
1725
Chris Lattner58a1eb02009-04-08 18:46:40 +00001726/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1727/// pseudo directive in the predefines buffer. This handles it by sucking all
1728/// tokens through the preprocessor and discarding them (only keeping the side
1729/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001730void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1731 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001732 // This directive should only occur in the predefines buffer. If not, emit an
1733 // error and reject it.
1734 SourceLocation Loc = IncludeMacrosTok.getLocation();
1735 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1736 Diag(IncludeMacrosTok.getLocation(),
1737 diag::pp_include_macros_out_of_predefines);
1738 DiscardUntilEndOfDirective();
1739 return;
1740 }
Mike Stump11289f42009-09-09 15:08:12 +00001741
Chris Lattnere01d82b2009-04-08 20:53:24 +00001742 // Treat this as a normal #include for checking purposes. If this is
1743 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001744 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001745
Chris Lattnere01d82b2009-04-08 20:53:24 +00001746 Token TmpTok;
1747 do {
1748 Lex(TmpTok);
1749 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1750 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001751}
1752
Chris Lattnerf64b3522008-03-09 01:54:53 +00001753//===----------------------------------------------------------------------===//
1754// Preprocessor Macro Directive Handling.
1755//===----------------------------------------------------------------------===//
1756
1757/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1758/// definition has just been read. Lex the rest of the arguments and the
1759/// closing ), updating MI with what we learn. Return true if an error occurs
1760/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001761bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001762 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001763
Chris Lattnerf64b3522008-03-09 01:54:53 +00001764 while (1) {
1765 LexUnexpandedToken(Tok);
1766 switch (Tok.getKind()) {
1767 case tok::r_paren:
1768 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001769 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001770 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001771 // Otherwise we have #define FOO(A,)
1772 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1773 return true;
1774 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001775 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001776 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001777 diag::warn_cxx98_compat_variadic_macro :
1778 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001779
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001780 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1781 if (LangOpts.OpenCL) {
1782 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1783 return true;
1784 }
1785
Chris Lattnerf64b3522008-03-09 01:54:53 +00001786 // Lex the token after the identifier.
1787 LexUnexpandedToken(Tok);
1788 if (Tok.isNot(tok::r_paren)) {
1789 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1790 return true;
1791 }
1792 // Add the __VA_ARGS__ identifier as an argument.
1793 Arguments.push_back(Ident__VA_ARGS__);
1794 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001795 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001796 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001797 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001798 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1799 return true;
1800 default:
1801 // Handle keywords and identifiers here to accept things like
1802 // #define Foo(for) for.
1803 IdentifierInfo *II = Tok.getIdentifierInfo();
1804 if (II == 0) {
1805 // #define X(1
1806 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1807 return true;
1808 }
1809
1810 // If this is already used as an argument, it is used multiple times (e.g.
1811 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001812 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001813 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001814 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001815 return true;
1816 }
Mike Stump11289f42009-09-09 15:08:12 +00001817
Chris Lattnerf64b3522008-03-09 01:54:53 +00001818 // Add the argument to the macro info.
1819 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001820
Chris Lattnerf64b3522008-03-09 01:54:53 +00001821 // Lex the token after the identifier.
1822 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001823
Chris Lattnerf64b3522008-03-09 01:54:53 +00001824 switch (Tok.getKind()) {
1825 default: // #define X(A B
1826 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1827 return true;
1828 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001829 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001830 return false;
1831 case tok::comma: // #define X(A,
1832 break;
1833 case tok::ellipsis: // #define X(A... -> GCC extension
1834 // Diagnose extension.
1835 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001836
Chris Lattnerf64b3522008-03-09 01:54:53 +00001837 // Lex the token after the identifier.
1838 LexUnexpandedToken(Tok);
1839 if (Tok.isNot(tok::r_paren)) {
1840 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1841 return true;
1842 }
Mike Stump11289f42009-09-09 15:08:12 +00001843
Chris Lattnerf64b3522008-03-09 01:54:53 +00001844 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001845 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001846 return false;
1847 }
1848 }
1849 }
1850}
1851
James Dennettf6333ac2012-06-22 05:46:07 +00001852/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001853/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001854void Preprocessor::HandleDefineDirective(Token &DefineTok,
1855 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001856 ++NumDefined;
1857
1858 Token MacroNameTok;
1859 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001860
Chris Lattnerf64b3522008-03-09 01:54:53 +00001861 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001862 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001863 return;
1864
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001865 Token LastTok = MacroNameTok;
1866
Chris Lattnerf64b3522008-03-09 01:54:53 +00001867 // If we are supposed to keep comments in #defines, reenable comment saving
1868 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001869 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001870
Chris Lattnerf64b3522008-03-09 01:54:53 +00001871 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001872 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001873
Chris Lattnerf64b3522008-03-09 01:54:53 +00001874 Token Tok;
1875 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001876
Chris Lattnerf64b3522008-03-09 01:54:53 +00001877 // If this is a function-like macro definition, parse the argument list,
1878 // marking each of the identifiers as being used as macro arguments. Also,
1879 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001880 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001881 if (ImmediatelyAfterHeaderGuard) {
1882 // Save this macro information since it may part of a header guard.
1883 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
1884 MacroNameTok.getLocation());
1885 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001886 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001887 } else if (Tok.hasLeadingSpace()) {
1888 // This is a normal token with leading space. Clear the leading space
1889 // marker on the first token to get proper expansion.
1890 Tok.clearFlag(Token::LeadingSpace);
1891 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001892 // This is a function-like macro definition. Read the argument list.
1893 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001894 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001895 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001896 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001897 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001898 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001899 DiscardUntilEndOfDirective();
1900 return;
1901 }
1902
Chris Lattner249c38b2009-04-19 18:26:34 +00001903 // If this is a definition of a variadic C99 function-like macro, not using
1904 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001905
Chris Lattner249c38b2009-04-19 18:26:34 +00001906 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1907 // This gets unpoisoned where it is allowed.
1908 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1909 if (MI->isC99Varargs())
1910 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001911
Chris Lattnerf64b3522008-03-09 01:54:53 +00001912 // Read the first token after the arg list for down below.
1913 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001914 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001915 // C99 requires whitespace between the macro definition and the body. Emit
1916 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001917 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001918 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001919 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1920 // first character of a replacement list is not a character required by
1921 // subclause 5.2.1, then there shall be white-space separation between the
1922 // identifier and the replacement list.". 5.2.1 lists this set:
1923 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1924 // is irrelevant here.
1925 bool isInvalid = false;
1926 if (Tok.is(tok::at)) // @ is not in the list above.
1927 isInvalid = true;
1928 else if (Tok.is(tok::unknown)) {
1929 // If we have an unknown token, it is something strange like "`". Since
1930 // all of valid characters would have lexed into a single character
1931 // token of some sort, we know this is not a valid case.
1932 isInvalid = true;
1933 }
1934 if (isInvalid)
1935 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1936 else
1937 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001938 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001939
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001940 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001941 LastTok = Tok;
1942
Chris Lattnerf64b3522008-03-09 01:54:53 +00001943 // Read the rest of the macro body.
1944 if (MI->isObjectLike()) {
1945 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001946 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001947 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001948 MI->AddTokenToBody(Tok);
1949 // Get the next token of the macro.
1950 LexUnexpandedToken(Tok);
1951 }
Mike Stump11289f42009-09-09 15:08:12 +00001952
Chris Lattnerf64b3522008-03-09 01:54:53 +00001953 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001954 // Otherwise, read the body of a function-like macro. While we are at it,
1955 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1956 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001957 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001958 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001959
Eli Friedman14d3c792012-11-14 02:18:46 +00001960 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001961 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001962
Chris Lattnerf64b3522008-03-09 01:54:53 +00001963 // Get the next token of the macro.
1964 LexUnexpandedToken(Tok);
1965 continue;
1966 }
Mike Stump11289f42009-09-09 15:08:12 +00001967
Richard Smith701a3522013-07-09 01:00:29 +00001968 // If we're in -traditional mode, then we should ignore stringification
1969 // and token pasting. Mark the tokens as unknown so as not to confuse
1970 // things.
1971 if (getLangOpts().TraditionalCPP) {
1972 Tok.setKind(tok::unknown);
1973 MI->AddTokenToBody(Tok);
1974
1975 // Get the next token of the macro.
1976 LexUnexpandedToken(Tok);
1977 continue;
1978 }
1979
Eli Friedman14d3c792012-11-14 02:18:46 +00001980 if (Tok.is(tok::hashhash)) {
1981
1982 // If we see token pasting, check if it looks like the gcc comma
1983 // pasting extension. We'll use this information to suppress
1984 // diagnostics later on.
1985
1986 // Get the next token of the macro.
1987 LexUnexpandedToken(Tok);
1988
1989 if (Tok.is(tok::eod)) {
1990 MI->AddTokenToBody(LastTok);
1991 break;
1992 }
1993
1994 unsigned NumTokens = MI->getNumTokens();
1995 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1996 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1997 MI->setHasCommaPasting();
1998
David Majnemer76faf1f2013-11-05 09:30:17 +00001999 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002000 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002001 continue;
2002 }
2003
Chris Lattnerf64b3522008-03-09 01:54:53 +00002004 // Get the next token of the macro.
2005 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002006
Chris Lattner83bd8282009-05-25 17:16:10 +00002007 // Check for a valid macro arg identifier.
2008 if (Tok.getIdentifierInfo() == 0 ||
2009 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2010
2011 // If this is assembler-with-cpp mode, we accept random gibberish after
2012 // the '#' because '#' is often a comment character. However, change
2013 // the kind of the token to tok::unknown so that the preprocessor isn't
2014 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002015 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002016 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002017 MI->AddTokenToBody(LastTok);
2018 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002019 } else {
2020 Diag(Tok, diag::err_pp_stringize_not_parameter);
2021 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002022
Chris Lattner83bd8282009-05-25 17:16:10 +00002023 // Disable __VA_ARGS__ again.
2024 Ident__VA_ARGS__->setIsPoisoned(true);
2025 return;
2026 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002027 }
Mike Stump11289f42009-09-09 15:08:12 +00002028
Chris Lattner83bd8282009-05-25 17:16:10 +00002029 // Things look ok, add the '#' and param name tokens to the macro.
2030 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002031 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002032 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002033
Chris Lattnerf64b3522008-03-09 01:54:53 +00002034 // Get the next token of the macro.
2035 LexUnexpandedToken(Tok);
2036 }
2037 }
Mike Stump11289f42009-09-09 15:08:12 +00002038
2039
Chris Lattnerf64b3522008-03-09 01:54:53 +00002040 // Disable __VA_ARGS__ again.
2041 Ident__VA_ARGS__->setIsPoisoned(true);
2042
Chris Lattner57540c52011-04-15 05:22:18 +00002043 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002044 // replacement list.
2045 unsigned NumTokens = MI->getNumTokens();
2046 if (NumTokens != 0) {
2047 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2048 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002049 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002050 return;
2051 }
2052 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2053 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002054 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002055 return;
2056 }
2057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002059 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002060
Chris Lattnerf64b3522008-03-09 01:54:53 +00002061 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002062 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002063 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00002064 // It is very common for system headers to have tons of macro redefinitions
2065 // and for warnings to be disabled in system headers. If this is the case,
2066 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002067 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002068 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002069 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002070 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002071
Richard Smith7b242542013-03-06 00:46:00 +00002072 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2073 // C++ [cpp.predefined]p4, but allow it as an extension.
2074 if (OtherMI->isBuiltinMacro())
2075 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002076 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002077 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002078 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002079 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002080 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2081 << MacroNameTok.getIdentifierInfo();
2082 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2083 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002084 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002085 if (OtherMI->isWarnIfUnused())
2086 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002087 }
Mike Stump11289f42009-09-09 15:08:12 +00002088
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002089 DefMacroDirective *MD =
2090 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002091
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002092 assert(!MI->isUsed());
2093 // If we need warning for not using the macro, add its location in the
2094 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002095 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002096 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00002097 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002098 MI->setIsWarnIfUnused(true);
2099 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2100 }
2101
Chris Lattner928e9092009-04-12 01:39:54 +00002102 // If the callbacks want to know, tell them about the macro definition.
2103 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002104 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002105}
2106
James Dennettf6333ac2012-06-22 05:46:07 +00002107/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002108///
2109void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2110 ++NumUndefined;
2111
2112 Token MacroNameTok;
2113 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00002114
Chris Lattnerf64b3522008-03-09 01:54:53 +00002115 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002116 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002117 return;
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattnerf64b3522008-03-09 01:54:53 +00002119 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002120 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002121
Chris Lattnerf64b3522008-03-09 01:54:53 +00002122 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002123 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002124 const MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Mike Stump11289f42009-09-09 15:08:12 +00002125
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002126 // If the callbacks want to know, tell them about the macro #undef.
2127 // Note: no matter if the macro was defined or not.
2128 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002129 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002130
Chris Lattnerf64b3522008-03-09 01:54:53 +00002131 // If the macro is not defined, this is a noop undef, just return.
2132 if (MI == 0) return;
2133
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002134 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002135 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002136
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002137 if (MI->isWarnIfUnused())
2138 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2139
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002140 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2141 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002142}
2143
2144
2145//===----------------------------------------------------------------------===//
2146// Preprocessor Conditional Directive Handling.
2147//===----------------------------------------------------------------------===//
2148
James Dennettf6333ac2012-06-22 05:46:07 +00002149/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2150/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2151/// true if any tokens have been returned or pp-directives activated before this
2152/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002153///
2154void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2155 bool ReadAnyTokensBeforeDirective) {
2156 ++NumIf;
2157 Token DirectiveTok = Result;
2158
2159 Token MacroNameTok;
2160 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002161
Chris Lattnerf64b3522008-03-09 01:54:53 +00002162 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002163 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002164 // Skip code until we get to #endif. This helps with recovery by not
2165 // emitting an error when the #endif is reached.
2166 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2167 /*Foundnonskip*/false, /*FoundElse*/false);
2168 return;
2169 }
Mike Stump11289f42009-09-09 15:08:12 +00002170
Chris Lattnerf64b3522008-03-09 01:54:53 +00002171 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002172 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002173
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002174 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002175 MacroDirective *MD = getMacroDirective(MII);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002176 MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002177
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002178 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002179 // If the start of a top-level #ifdef and if the macro is not defined,
2180 // inform MIOpt that this might be the start of a proper include guard.
2181 // Otherwise it is some other form of unknown conditional which we can't
2182 // handle.
2183 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002184 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002185 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002186 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002187 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002188 }
2189
Chris Lattnerf64b3522008-03-09 01:54:53 +00002190 // If there is a macro, process it.
2191 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002192 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002193
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002194 if (Callbacks) {
2195 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002196 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002197 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002198 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002199 }
2200
Chris Lattnerf64b3522008-03-09 01:54:53 +00002201 // Should we include the stuff contained by this directive?
2202 if (!MI == isIfndef) {
2203 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002204 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2205 /*wasskip*/false, /*foundnonskip*/true,
2206 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002207 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002208 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002209 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002210 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002211 /*FoundElse*/false);
2212 }
2213}
2214
James Dennettf6333ac2012-06-22 05:46:07 +00002215/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002216///
2217void Preprocessor::HandleIfDirective(Token &IfToken,
2218 bool ReadAnyTokensBeforeDirective) {
2219 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002220
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002221 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002222 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002223 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2224 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2225 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002226
2227 // If this condition is equivalent to #ifndef X, and if this is the first
2228 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002229 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002230 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002231 // FIXME: Pass in the location of the macro name, not the 'if' token.
2232 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002233 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002234 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002235 }
2236
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002237 if (Callbacks)
2238 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002239 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002240 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002241
Chris Lattnerf64b3522008-03-09 01:54:53 +00002242 // Should we include the stuff contained by this directive?
2243 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002244 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002245 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002246 /*foundnonskip*/true, /*foundelse*/false);
2247 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002248 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002249 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002250 /*FoundElse*/false);
2251 }
2252}
2253
James Dennettf6333ac2012-06-22 05:46:07 +00002254/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002255///
2256void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2257 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002258
Chris Lattnerf64b3522008-03-09 01:54:53 +00002259 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002260 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002261
Chris Lattnerf64b3522008-03-09 01:54:53 +00002262 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002263 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002264 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002265 Diag(EndifToken, diag::err_pp_endif_without_if);
2266 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002267 }
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattnerf64b3522008-03-09 01:54:53 +00002269 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002270 if (CurPPLexer->getConditionalStackDepth() == 0)
2271 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002272
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002273 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002274 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002275
2276 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002277 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002278}
2279
James Dennettf6333ac2012-06-22 05:46:07 +00002280/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002281///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002282void Preprocessor::HandleElseDirective(Token &Result) {
2283 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002284
Chris Lattnerf64b3522008-03-09 01:54:53 +00002285 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002286 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002287
Chris Lattnerf64b3522008-03-09 01:54:53 +00002288 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002289 if (CurPPLexer->popConditionalLevel(CI)) {
2290 Diag(Result, diag::pp_err_else_without_if);
2291 return;
2292 }
Mike Stump11289f42009-09-09 15:08:12 +00002293
Chris Lattnerf64b3522008-03-09 01:54:53 +00002294 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002295 if (CurPPLexer->getConditionalStackDepth() == 0)
2296 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002297
2298 // If this is a #else with a #else before it, report the error.
2299 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002300
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002301 if (Callbacks)
2302 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2303
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002304 // Finally, skip the rest of the contents of this block.
2305 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002306 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002307}
2308
James Dennettf6333ac2012-06-22 05:46:07 +00002309/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002310///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002311void Preprocessor::HandleElifDirective(Token &ElifToken) {
2312 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002313
Chris Lattnerf64b3522008-03-09 01:54:53 +00002314 // #elif directive in a non-skipping conditional... start skipping.
2315 // We don't care what the condition is, because we will always skip it (since
2316 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002317 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002318 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002319 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002320
2321 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002322 if (CurPPLexer->popConditionalLevel(CI)) {
2323 Diag(ElifToken, diag::pp_err_elif_without_if);
2324 return;
2325 }
Mike Stump11289f42009-09-09 15:08:12 +00002326
Chris Lattnerf64b3522008-03-09 01:54:53 +00002327 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002328 if (CurPPLexer->getConditionalStackDepth() == 0)
2329 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002330
Chris Lattnerf64b3522008-03-09 01:54:53 +00002331 // If this is a #elif with a #else before it, report the error.
2332 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002333
2334 if (Callbacks)
2335 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002336 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002337 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002338
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002339 // Finally, skip the rest of the contents of this block.
2340 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002341 /*FoundElse*/CI.FoundElse,
2342 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002343}