blob: 7020da394033be6facd7dfa5b999ab910c7df2b1 [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattnerf64b3522008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner710bb872009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/LexDiagnostic.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/ModuleLoader.h"
24#include "clang/Lex/Pragma.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000025#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000026#include "llvm/Support/ErrorHandling.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000027#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000028using namespace clang;
29
30//===----------------------------------------------------------------------===//
31// Utility Methods for Preprocessor Directive Handling.
32//===----------------------------------------------------------------------===//
33
Chris Lattnerc0a585d2010-08-17 15:55:45 +000034MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000035 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000036
Ted Kremenekc8456f82010-10-19 22:15:20 +000037 if (MICache) {
38 MIChain = MICache;
39 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000040 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000041 else {
42 MIChain = BP.Allocate<MacroInfoChain>();
43 }
44
45 MIChain->Next = MIChainHead;
46 MIChain->Prev = 0;
47 if (MIChainHead)
48 MIChainHead->Prev = MIChain;
49 MIChainHead = MIChain;
50
51 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000052}
53
54MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
55 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000056 new (MI) MacroInfo(L);
57 return MI;
58}
59
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000060MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
61 unsigned SubModuleID) {
62 LLVM_STATIC_ASSERT(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
63 "alignment for MacroInfo is less than the ID");
64 MacroInfo *MI =
65 (MacroInfo*)BP.Allocate(sizeof(MacroInfo) + sizeof(SubModuleID),
66 llvm::AlignOf<MacroInfo>::Alignment);
67 new (MI) MacroInfo(L);
68 MI->FromASTFile = true;
69 MI->setOwningModuleID(SubModuleID);
70 return MI;
71}
72
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000073MacroDirective *Preprocessor::AllocateMacroDirective(MacroInfo *MI,
74 SourceLocation Loc,
75 bool isImported) {
76 MacroDirective *MD = BP.Allocate<MacroDirective>();
77 new (MD) MacroDirective(MI, Loc, isImported);
78 return MD;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000079}
80
James Dennettf6333ac2012-06-22 05:46:07 +000081/// \brief Release the specified MacroInfo to be reused for allocating
82/// new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +000083void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +000084 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
85 if (MacroInfoChain *Prev = MIChain->Prev) {
86 MacroInfoChain *Next = MIChain->Next;
87 Prev->Next = Next;
88 if (Next)
89 Next->Prev = Prev;
90 }
91 else {
92 assert(MIChainHead == MIChain);
93 MIChainHead = MIChain->Next;
94 MIChainHead->Prev = 0;
95 }
96 MIChain->Next = MICache;
97 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +000098
Ted Kremenekc8456f82010-10-19 22:15:20 +000099 MI->Destroy();
100}
Chris Lattner666f7a42009-02-20 22:19:20 +0000101
James Dennettf6333ac2012-06-22 05:46:07 +0000102/// \brief Read and discard all tokens remaining on the current line until
103/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000104void Preprocessor::DiscardUntilEndOfDirective() {
105 Token Tmp;
106 do {
107 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000108 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000109 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000110}
111
James Dennettf6333ac2012-06-22 05:46:07 +0000112/// \brief Lex and validate a macro name, which occurs after a
113/// \#define or \#undef.
114///
115/// This sets the token kind to eod and discards the rest
116/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
117/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
118/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000119void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
120 // Read the token, don't allow macro expansion on it.
121 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000122
Douglas Gregor12785102010-08-24 20:21:13 +0000123 if (MacroNameTok.is(tok::code_completion)) {
124 if (CodeComplete)
125 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000126 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000127 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000128 }
129
Chris Lattnerf64b3522008-03-09 01:54:53 +0000130 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000131 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000132 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
133 return;
134 }
Mike Stump11289f42009-09-09 15:08:12 +0000135
Chris Lattnerf64b3522008-03-09 01:54:53 +0000136 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
137 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000138 bool Invalid = false;
139 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
140 if (Invalid)
141 return;
Nico Weber2e686202012-02-29 22:54:43 +0000142
Chris Lattner77c76ae2008-12-13 20:12:40 +0000143 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000144
145 // Allow #defining |and| and friends in microsoft mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000146 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weber2e686202012-02-29 22:54:43 +0000147 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
148 return;
149 }
150
Chris Lattner77c76ae2008-12-13 20:12:40 +0000151 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000152 // C++ 2.5p2: Alternative tokens behave the same as its primary token
153 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000154 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000155 else
156 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
157 // Fall through on error.
158 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Richard Smith7b242542013-03-06 00:46:00 +0000159 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000160 Diag(MacroNameTok, diag::err_defined_macro_name);
Richard Smith7b242542013-03-06 00:46:00 +0000161 } else if (isDefineUndef == 2 && II->hasMacroDefinition() &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000162 getMacroInfo(II)->isBuiltinMacro()) {
Richard Smith7b242542013-03-06 00:46:00 +0000163 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
164 // and C++ [cpp.predefined]p4], but allow it as an extension.
165 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
166 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000167 } else {
168 // Okay, we got a good identifier node. Return it.
169 return;
170 }
Mike Stump11289f42009-09-09 15:08:12 +0000171
Chris Lattnerf64b3522008-03-09 01:54:53 +0000172 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000173 // token kind to tok::eod.
174 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000175 return DiscardUntilEndOfDirective();
176}
177
James Dennettf6333ac2012-06-22 05:46:07 +0000178/// \brief Ensure that the next token is a tok::eod token.
179///
180/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000181/// true, then we consider macros that expand to zero tokens as being ok.
182void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000183 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000184 // Lex unexpanded tokens for most directives: macros might expand to zero
185 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
186 // #line) allow empty macros.
187 if (EnableMacros)
188 Lex(Tmp);
189 else
190 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000191
Chris Lattnerf64b3522008-03-09 01:54:53 +0000192 // There should be no tokens after the directive, but we allow them as an
193 // extension.
194 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
195 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000196
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000197 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000198 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000199 // or if this is a macro-style preprocessing directive, because it is more
200 // trouble than it is worth to insert /**/ and check that there is no /**/
201 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000202 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000203 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000204 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000205 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
206 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000207 DiscardUntilEndOfDirective();
208 }
209}
210
211
212
James Dennettf6333ac2012-06-22 05:46:07 +0000213/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
214/// decided that the subsequent tokens are in the \#if'd out portion of the
215/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000216/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000217/// this \#if directive, so \#else/\#elif blocks should never be entered.
218/// If ElseOk is true, then \#else directives are ok, if not, then we have
219/// already seen one so a \#else directive is a duplicate. When this returns,
220/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000221void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
222 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000223 bool FoundElse,
224 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000225 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000226 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000227
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000228 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000229 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000230
Ted Kremenek56572ab2008-12-12 18:34:08 +0000231 if (CurPTHLexer) {
232 PTHSkipExcludedConditionalBlock();
233 return;
234 }
Mike Stump11289f42009-09-09 15:08:12 +0000235
Chris Lattnerf64b3522008-03-09 01:54:53 +0000236 // Enter raw mode to disable identifier lookup (and thus macro expansion),
237 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000238 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000239 Token Tok;
240 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000241 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000242
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000243 if (Tok.is(tok::code_completion)) {
244 if (CodeComplete)
245 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000246 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000247 continue;
248 }
249
Chris Lattnerf64b3522008-03-09 01:54:53 +0000250 // If this is the end of the buffer, we have an error.
251 if (Tok.is(tok::eof)) {
252 // Emit errors for each unterminated conditional on the stack, including
253 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000254 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000255 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000256 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
257 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000258 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000259 }
260
Chris Lattnerf64b3522008-03-09 01:54:53 +0000261 // Just return and let the caller lex after this #include.
262 break;
263 }
Mike Stump11289f42009-09-09 15:08:12 +0000264
Chris Lattnerf64b3522008-03-09 01:54:53 +0000265 // If this token is not a preprocessor directive, just skip it.
266 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
267 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000268
Chris Lattnerf64b3522008-03-09 01:54:53 +0000269 // We just parsed a # character at the start of a line, so we're in
270 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000271 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000272 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000273 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000274
Mike Stump11289f42009-09-09 15:08:12 +0000275
Chris Lattnerf64b3522008-03-09 01:54:53 +0000276 // Read the next token, the directive flavor.
277 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Chris Lattnerf64b3522008-03-09 01:54:53 +0000279 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
280 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000281 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000282 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000283 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000284 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000285 continue;
286 }
287
288 // If the first letter isn't i or e, it isn't intesting to us. We know that
289 // this is safe in the face of spelling differences, because there is no way
290 // to spell an i/e in a strange way that is another letter. Skipping this
291 // allows us to avoid looking up the identifier info for #define/#undef and
292 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000293 const char *RawCharData = Tok.getRawIdentifierData();
294
Chris Lattnerf64b3522008-03-09 01:54:53 +0000295 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000296 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000297 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000298 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000299 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000300 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000301 continue;
302 }
Mike Stump11289f42009-09-09 15:08:12 +0000303
Chris Lattnerf64b3522008-03-09 01:54:53 +0000304 // Get the identifier name without trigraphs or embedded newlines. Note
305 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
306 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000307 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000308 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000309 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000310 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000311 } else {
312 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000313 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000315 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000316 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000317 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000318 continue;
319 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000320 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000322 }
Mike Stump11289f42009-09-09 15:08:12 +0000323
Benjamin Kramer144884642009-12-31 13:32:38 +0000324 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000325 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000326 if (Sub.empty() || // "if"
327 Sub == "def" || // "ifdef"
328 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
330 // bother parsing the condition.
331 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000332 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000333 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000334 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000335 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000336 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000337 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000338 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000339 PPConditionalInfo CondInfo;
340 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000341 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000342 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000343 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000344
Chris Lattnerf64b3522008-03-09 01:54:53 +0000345 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000346 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000347 // Restore the value of LexingRawMode so that trailing comments
348 // are handled correctly, if we've reached the outermost block.
349 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000350 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000351 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000352 if (Callbacks)
353 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000354 break;
Richard Smithd0124572012-06-21 00:35:03 +0000355 } else {
356 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000357 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000358 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000359 // #else directive in a skipping conditional. If not in some other
360 // skipping conditional, and if #else hasn't already been seen, enter it
361 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000362 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000363
Chris Lattnerf64b3522008-03-09 01:54:53 +0000364 // If this is a #else with a #else before it, report the error.
365 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000366
Chris Lattnerf64b3522008-03-09 01:54:53 +0000367 // Note that we've seen a #else in this conditional.
368 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000369
Chris Lattnerf64b3522008-03-09 01:54:53 +0000370 // If the conditional is at the top level, and the #if block wasn't
371 // entered, enter the #else block now.
372 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
373 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000374 // Restore the value of LexingRawMode so that trailing comments
375 // are handled correctly.
376 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000377 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000378 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000379 if (Callbacks)
380 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000381 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000382 } else {
383 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000384 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000385 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000386 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000387
388 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000389 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000390 // If this is in a skipping block or if we're already handled this #if
391 // block, don't bother parsing the condition.
392 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
393 DiscardUntilEndOfDirective();
394 ShouldEnter = false;
395 } else {
396 // Restore the value of LexingRawMode so that identifiers are
397 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000398 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
399 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000400 IdentifierInfo *IfNDefMacro = 0;
401 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000402 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000403 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000404 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattnerf64b3522008-03-09 01:54:53 +0000406 // If this is a #elif with a #else before it, report the error.
407 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattnerf64b3522008-03-09 01:54:53 +0000409 // If this condition is true, enter it!
410 if (ShouldEnter) {
411 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000412 if (Callbacks)
413 Callbacks->Elif(Tok.getLocation(),
414 SourceRange(ConditionalBegin, ConditionalEnd),
415 CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000416 break;
417 }
418 }
419 }
Mike Stump11289f42009-09-09 15:08:12 +0000420
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000421 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000422 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000423 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000424 }
425
426 // Finally, if we are out of the conditional (saw an #endif or ran off the end
427 // of the file, just stop skipping and return to lexing whatever came after
428 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000429 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000430
431 if (Callbacks) {
432 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
433 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
434 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000435}
436
Ted Kremenek56572ab2008-12-12 18:34:08 +0000437void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000438
439 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000440 assert(CurPTHLexer);
441 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000442
Ted Kremenek56572ab2008-12-12 18:34:08 +0000443 // Skip to the next '#else', '#elif', or #endif.
444 if (CurPTHLexer->SkipBlock()) {
445 // We have reached an #endif. Both the '#' and 'endif' tokens
446 // have been consumed by the PTHLexer. Just pop off the condition level.
447 PPConditionalInfo CondInfo;
448 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000449 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000450 assert(!InCond && "Can't be skipping if not in a conditional!");
451 break;
452 }
Mike Stump11289f42009-09-09 15:08:12 +0000453
Ted Kremenek56572ab2008-12-12 18:34:08 +0000454 // We have reached a '#else' or '#elif'. Lex the next token to get
455 // the directive flavor.
456 Token Tok;
457 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000458
Ted Kremenek56572ab2008-12-12 18:34:08 +0000459 // We can actually look up the IdentifierInfo here since we aren't in
460 // raw mode.
461 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
462
463 if (K == tok::pp_else) {
464 // #else: Enter the else condition. We aren't in a nested condition
465 // since we skip those. We're always in the one matching the last
466 // blocked we skipped.
467 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
468 // Note that we've seen a #else in this conditional.
469 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000470
Ted Kremenek56572ab2008-12-12 18:34:08 +0000471 // If the #if block wasn't entered then enter the #else block now.
472 if (!CondInfo.FoundNonSkip) {
473 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000474
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000475 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000476 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000477 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000478 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000479
Ted Kremenek56572ab2008-12-12 18:34:08 +0000480 break;
481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Ted Kremenek56572ab2008-12-12 18:34:08 +0000483 // Otherwise skip this block.
484 continue;
485 }
Mike Stump11289f42009-09-09 15:08:12 +0000486
Ted Kremenek56572ab2008-12-12 18:34:08 +0000487 assert(K == tok::pp_elif);
488 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
489
490 // If this is a #elif with a #else before it, report the error.
491 if (CondInfo.FoundElse)
492 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000493
Ted Kremenek56572ab2008-12-12 18:34:08 +0000494 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000495 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000496 if (CondInfo.FoundNonSkip)
497 continue;
498
499 // Evaluate the condition of the #elif.
500 IdentifierInfo *IfNDefMacro = 0;
501 CurPTHLexer->ParsingPreprocessorDirective = true;
502 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
503 CurPTHLexer->ParsingPreprocessorDirective = false;
504
505 // If this condition is true, enter it!
506 if (ShouldEnter) {
507 CondInfo.FoundNonSkip = true;
508 break;
509 }
510
511 // Otherwise, skip this block and go to the next one.
512 continue;
513 }
514}
515
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000516const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000517 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000518 bool isAngled,
519 const DirectoryLookup *FromDir,
520 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000521 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000522 SmallVectorImpl<char> *RelativePath,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000523 Module **SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000524 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000525 // If the header lookup mechanism may be relative to the current file, pass in
526 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000527 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000528 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000529 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000530 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000531
Chris Lattner022923a2009-02-04 19:45:07 +0000532 // If there is no file entry associated with this file, it must be the
533 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000534 // it won't be scanned for preprocessor directives. If we have the
535 // predefines buffer, resolve #include references (which come from the
536 // -include command line argument) as if they came from the main file, this
537 // affects file lookup etc.
538 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000539 FID = SourceMgr.getMainFileID();
540 CurFileEnt = SourceMgr.getFileEntryForID(FID);
541 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000542 }
Mike Stump11289f42009-09-09 15:08:12 +0000543
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000544 // Do a standard file entry lookup.
545 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000546 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000547 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000548 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerfde85352010-01-22 00:14:44 +0000549 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000550
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000551 // Otherwise, see if this is a subframework header. If so, this is relative
552 // to one of the headers on the #include stack. Walk the list of the current
553 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000554 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000555 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000556 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000557 SearchPath, RelativePath,
558 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000559 return FE;
560 }
Mike Stump11289f42009-09-09 15:08:12 +0000561
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000562 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
563 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000564 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000565 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000566 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000567 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000568 Filename, CurFileEnt, SearchPath, RelativePath,
569 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000570 return FE;
571 }
572 }
Mike Stump11289f42009-09-09 15:08:12 +0000573
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000574 // Otherwise, we really couldn't find the file.
575 return 0;
576}
577
Chris Lattnerf64b3522008-03-09 01:54:53 +0000578
579//===----------------------------------------------------------------------===//
580// Preprocessor Directive Handling.
581//===----------------------------------------------------------------------===//
582
David Blaikied5321242012-06-06 18:52:13 +0000583class Preprocessor::ResetMacroExpansionHelper {
584public:
585 ResetMacroExpansionHelper(Preprocessor *pp)
586 : PP(pp), save(pp->DisableMacroExpansion) {
587 if (pp->MacroExpansionInDirectivesOverride)
588 pp->DisableMacroExpansion = false;
589 }
590 ~ResetMacroExpansionHelper() {
591 PP->DisableMacroExpansion = save;
592 }
593private:
594 Preprocessor *PP;
595 bool save;
596};
597
Chris Lattnerf64b3522008-03-09 01:54:53 +0000598/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000599/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000600/// lexer/preprocessor state, and advances the lexer(s) so that the next token
601/// read is the correct one.
602void Preprocessor::HandleDirective(Token &Result) {
603 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000604
Chris Lattnerf64b3522008-03-09 01:54:53 +0000605 // We just parsed a # character at the start of a line, so we're in directive
606 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000607 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000608 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000609 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000610
Chris Lattnerf64b3522008-03-09 01:54:53 +0000611 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000612
Chris Lattnerf64b3522008-03-09 01:54:53 +0000613 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000614 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000615 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000616 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000617
Chris Lattner2d17ab72009-03-18 21:00:25 +0000618 // Save the '#' token in case we need to return it later.
619 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000620
Chris Lattnerf64b3522008-03-09 01:54:53 +0000621 // Read the next token, the directive flavor. This isn't expanded due to
622 // C99 6.10.3p8.
623 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000624
Chris Lattnerf64b3522008-03-09 01:54:53 +0000625 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
626 // #define A(x) #x
627 // A(abc
628 // #warning blah
629 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000630 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
631 // not support this for #include-like directives, since that can result in
632 // terrible diagnostics, and does not work in GCC.
633 if (InMacroArgs) {
634 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
635 switch (II->getPPKeywordID()) {
636 case tok::pp_include:
637 case tok::pp_import:
638 case tok::pp_include_next:
639 case tok::pp___include_macros:
640 Diag(Result, diag::err_embedded_include) << II->getName();
641 DiscardUntilEndOfDirective();
642 return;
643 default:
644 break;
645 }
646 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000647 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000648 }
Mike Stump11289f42009-09-09 15:08:12 +0000649
David Blaikied5321242012-06-06 18:52:13 +0000650 // Temporarily enable macro expansion if set so
651 // and reset to previous state when returning from this function.
652 ResetMacroExpansionHelper helper(this);
653
Chris Lattnerf64b3522008-03-09 01:54:53 +0000654 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000655 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000656 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000657 case tok::code_completion:
658 if (CodeComplete)
659 CodeComplete->CodeCompleteDirective(
660 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000661 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000662 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000663 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000664 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000665 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000666 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000667 default:
668 IdentifierInfo *II = Result.getIdentifierInfo();
669 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000670
Chris Lattnerf64b3522008-03-09 01:54:53 +0000671 // Ask what the preprocessor keyword ID is.
672 switch (II->getPPKeywordID()) {
673 default: break;
674 // C99 6.10.1 - Conditional Inclusion.
675 case tok::pp_if:
676 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
677 case tok::pp_ifdef:
678 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
679 case tok::pp_ifndef:
680 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
681 case tok::pp_elif:
682 return HandleElifDirective(Result);
683 case tok::pp_else:
684 return HandleElseDirective(Result);
685 case tok::pp_endif:
686 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000687
Chris Lattnerf64b3522008-03-09 01:54:53 +0000688 // C99 6.10.2 - Source File Inclusion.
689 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000690 // Handle #include.
691 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000692 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000693 // Handle -imacros.
694 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000695
Chris Lattnerf64b3522008-03-09 01:54:53 +0000696 // C99 6.10.3 - Macro Replacement.
697 case tok::pp_define:
698 return HandleDefineDirective(Result);
699 case tok::pp_undef:
700 return HandleUndefDirective(Result);
701
702 // C99 6.10.4 - Line Control.
703 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000704 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000705
Chris Lattnerf64b3522008-03-09 01:54:53 +0000706 // C99 6.10.5 - Error Directive.
707 case tok::pp_error:
708 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000709
Chris Lattnerf64b3522008-03-09 01:54:53 +0000710 // C99 6.10.6 - Pragma Directive.
711 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000712 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000713
Chris Lattnerf64b3522008-03-09 01:54:53 +0000714 // GNU Extensions.
715 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000716 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000717 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000718 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000719
Chris Lattnerf64b3522008-03-09 01:54:53 +0000720 case tok::pp_warning:
721 Diag(Result, diag::ext_pp_warning_directive);
722 return HandleUserDiagnosticDirective(Result, true);
723 case tok::pp_ident:
724 return HandleIdentSCCSDirective(Result);
725 case tok::pp_sccs:
726 return HandleIdentSCCSDirective(Result);
727 case tok::pp_assert:
728 //isExtension = true; // FIXME: implement #assert
729 break;
730 case tok::pp_unassert:
731 //isExtension = true; // FIXME: implement #unassert
732 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000733
Douglas Gregor663b48f2012-01-03 19:48:16 +0000734 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000735 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000736 return HandleMacroPublicDirective(Result);
737 break;
738
Douglas Gregor663b48f2012-01-03 19:48:16 +0000739 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000740 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000741 return HandleMacroPrivateDirective(Result);
742 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000743 }
744 break;
745 }
Mike Stump11289f42009-09-09 15:08:12 +0000746
Chris Lattner2d17ab72009-03-18 21:00:25 +0000747 // If this is a .S file, treat unknown # directives as non-preprocessor
748 // directives. This is important because # may be a comment or introduce
749 // various pseudo-ops. Just return the # token and push back the following
750 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000751 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000752 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000753 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000754 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000755 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000756
757 // If the second token is a hashhash token, then we need to translate it to
758 // unknown so the token lexer doesn't try to perform token pasting.
759 if (Result.is(tok::hashhash))
760 Toks[1].setKind(tok::unknown);
761
Chris Lattner2d17ab72009-03-18 21:00:25 +0000762 // Enter this token stream so that we re-lex the tokens. Make sure to
763 // enable macro expansion, in case the token after the # is an identifier
764 // that is expanded.
765 EnterTokenStream(Toks, 2, false, true);
766 return;
767 }
Mike Stump11289f42009-09-09 15:08:12 +0000768
Chris Lattnerf64b3522008-03-09 01:54:53 +0000769 // If we reached here, the preprocessing token is not valid!
770 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000771
Chris Lattnerf64b3522008-03-09 01:54:53 +0000772 // Read the rest of the PP line.
773 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000774
Chris Lattnerf64b3522008-03-09 01:54:53 +0000775 // Okay, we're done parsing the directive.
776}
777
Chris Lattner76e68962009-01-26 06:19:46 +0000778/// GetLineValue - Convert a numeric token into an unsigned value, emitting
779/// Diagnostic DiagID if it is invalid, and returning the value in Val.
780static bool GetLineValue(Token &DigitTok, unsigned &Val,
781 unsigned DiagID, Preprocessor &PP) {
782 if (DigitTok.isNot(tok::numeric_constant)) {
783 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000784
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000785 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000786 PP.DiscardUntilEndOfDirective();
787 return true;
788 }
Mike Stump11289f42009-09-09 15:08:12 +0000789
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000790 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000791 IntegerBuffer.resize(DigitTok.getLength());
792 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000793 bool Invalid = false;
794 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
795 if (Invalid)
796 return true;
797
Chris Lattnerd66f1722009-04-18 18:35:15 +0000798 // Verify that we have a simple digit-sequence, and compute the value. This
799 // is always a simple digit string computed in decimal, so we do this manually
800 // here.
801 Val = 0;
802 for (unsigned i = 0; i != ActualLength; ++i) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000803 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000804 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
805 diag::err_pp_line_digit_sequence);
806 PP.DiscardUntilEndOfDirective();
807 return true;
808 }
Mike Stump11289f42009-09-09 15:08:12 +0000809
Chris Lattnerd66f1722009-04-18 18:35:15 +0000810 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
811 if (NextVal < Val) { // overflow.
812 PP.Diag(DigitTok, DiagID);
813 PP.DiscardUntilEndOfDirective();
814 return true;
815 }
816 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000817 }
Mike Stump11289f42009-09-09 15:08:12 +0000818
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000819 if (DigitTokBegin[0] == '0' && Val)
Chris Lattnerd66f1722009-04-18 18:35:15 +0000820 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000821
Chris Lattner76e68962009-01-26 06:19:46 +0000822 return false;
823}
824
James Dennettf6333ac2012-06-22 05:46:07 +0000825/// \brief Handle a \#line directive: C99 6.10.4.
826///
827/// The two acceptable forms are:
828/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000829/// # line digit-sequence
830/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000831/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000832void Preprocessor::HandleLineDirective(Token &Tok) {
833 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
834 // expanded.
835 Token DigitTok;
836 Lex(DigitTok);
837
Chris Lattner100c65e2009-01-26 05:29:08 +0000838 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000839 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000840 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000841 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000842
843 if (LineNo == 0)
844 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000845
Chris Lattner76e68962009-01-26 06:19:46 +0000846 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
847 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000848 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000849 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000850 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000851 if (LineNo >= LineLimit)
852 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000853 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000854 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000855
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000856 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000857 Token StrTok;
858 Lex(StrTok);
859
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000860 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
861 // string followed by eod.
862 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000863 ; // ok
864 else if (StrTok.isNot(tok::string_literal)) {
865 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000866 return DiscardUntilEndOfDirective();
867 } else if (StrTok.hasUDSuffix()) {
868 Diag(StrTok, diag::err_invalid_string_udl);
869 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000870 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000871 // Parse and validate the string, converting it into a unique ID.
872 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000873 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000874 if (Literal.hadError)
875 return DiscardUntilEndOfDirective();
876 if (Literal.Pascal) {
877 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
878 return DiscardUntilEndOfDirective();
879 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000880 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000881
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000882 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000883 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
884 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000885 }
Mike Stump11289f42009-09-09 15:08:12 +0000886
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000887 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000888
Chris Lattner839150e2009-03-27 17:13:49 +0000889 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000890 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
891 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000892 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000893}
894
Chris Lattner76e68962009-01-26 06:19:46 +0000895/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
896/// marker directive.
897static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
898 bool &IsSystemHeader, bool &IsExternCHeader,
899 Preprocessor &PP) {
900 unsigned FlagVal;
901 Token FlagTok;
902 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000903 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000904 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
905 return true;
906
907 if (FlagVal == 1) {
908 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000909
Chris Lattner76e68962009-01-26 06:19:46 +0000910 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000911 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000912 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
913 return true;
914 } else if (FlagVal == 2) {
915 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000916
Chris Lattner1c967782009-02-04 06:25:26 +0000917 SourceManager &SM = PP.getSourceManager();
918 // If we are leaving the current presumed file, check to make sure the
919 // presumed include stack isn't empty!
920 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000921 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000922 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000923 if (PLoc.isInvalid())
924 return true;
925
Chris Lattner1c967782009-02-04 06:25:26 +0000926 // If there is no include loc (main file) or if the include loc is in a
927 // different physical file, then we aren't in a "1" line marker flag region.
928 SourceLocation IncLoc = PLoc.getIncludeLoc();
929 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000930 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000931 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
932 PP.DiscardUntilEndOfDirective();
933 return true;
934 }
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner76e68962009-01-26 06:19:46 +0000936 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000937 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000938 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
939 return true;
940 }
941
942 // We must have 3 if there are still flags.
943 if (FlagVal != 3) {
944 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000945 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000946 return true;
947 }
Mike Stump11289f42009-09-09 15:08:12 +0000948
Chris Lattner76e68962009-01-26 06:19:46 +0000949 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000950
Chris Lattner76e68962009-01-26 06:19:46 +0000951 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000952 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000953 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000954 return true;
955
956 // We must have 4 if there is yet another flag.
957 if (FlagVal != 4) {
958 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000959 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000960 return true;
961 }
Mike Stump11289f42009-09-09 15:08:12 +0000962
Chris Lattner76e68962009-01-26 06:19:46 +0000963 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000964
Chris Lattner76e68962009-01-26 06:19:46 +0000965 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000966 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000967
968 // There are no more valid flags here.
969 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000970 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000971 return true;
972}
973
974/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
975/// one of the following forms:
976///
977/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000978/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000979/// # 42 "file" ('1' | '2')? '3' '4'?
980///
981void Preprocessor::HandleDigitDirective(Token &DigitTok) {
982 // Validate the number and convert it to an unsigned. GNU does not have a
983 // line # limit other than it fit in 32-bits.
984 unsigned LineNo;
985 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
986 *this))
987 return;
Mike Stump11289f42009-09-09 15:08:12 +0000988
Chris Lattner76e68962009-01-26 06:19:46 +0000989 Token StrTok;
990 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Chris Lattner76e68962009-01-26 06:19:46 +0000992 bool IsFileEntry = false, IsFileExit = false;
993 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000994 int FilenameID = -1;
995
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000996 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
997 // string followed by eod.
998 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000999 ; // ok
1000 else if (StrTok.isNot(tok::string_literal)) {
1001 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001002 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001003 } else if (StrTok.hasUDSuffix()) {
1004 Diag(StrTok, diag::err_invalid_string_udl);
1005 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001006 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001007 // Parse and validate the string, converting it into a unique ID.
1008 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001009 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001010 if (Literal.hadError)
1011 return DiscardUntilEndOfDirective();
1012 if (Literal.Pascal) {
1013 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1014 return DiscardUntilEndOfDirective();
1015 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001016 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001017
Chris Lattner76e68962009-01-26 06:19:46 +00001018 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001019 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001020 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001021 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001022 }
Mike Stump11289f42009-09-09 15:08:12 +00001023
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001024 // Create a line note with this information.
1025 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001026 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001027 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001028
Chris Lattner839150e2009-03-27 17:13:49 +00001029 // If the preprocessor has callbacks installed, notify them of the #line
1030 // change. This is used so that the line marker comes out in -E mode for
1031 // example.
1032 if (Callbacks) {
1033 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1034 if (IsFileEntry)
1035 Reason = PPCallbacks::EnterFile;
1036 else if (IsFileExit)
1037 Reason = PPCallbacks::ExitFile;
1038 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1039 if (IsExternCHeader)
1040 FileKind = SrcMgr::C_ExternCSystem;
1041 else if (IsSystemHeader)
1042 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001043
Chris Lattnerc745cec2010-04-14 04:28:50 +00001044 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001045 }
Chris Lattner76e68962009-01-26 06:19:46 +00001046}
1047
1048
Chris Lattner38d7fd22009-01-26 05:30:54 +00001049/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1050///
Mike Stump11289f42009-09-09 15:08:12 +00001051void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001052 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001053 // PTH doesn't emit #warning or #error directives.
1054 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001055 return CurPTHLexer->DiscardToEndOfLine();
1056
Chris Lattnerf64b3522008-03-09 01:54:53 +00001057 // Read the rest of the line raw. We do this because we don't want macros
1058 // to be expanded and we don't require that the tokens be valid preprocessing
1059 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1060 // collapse multiple consequtive white space between tokens, but this isn't
1061 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001062 SmallString<128> Message;
1063 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001064
1065 // Find the first non-whitespace character, so that we can make the
1066 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001067 StringRef Msg = Message.str().ltrim(" ");
1068
Chris Lattner100c65e2009-01-26 05:29:08 +00001069 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001070 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001071 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001072 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001073}
1074
1075/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1076///
1077void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1078 // Yes, this directive is an extension.
1079 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattnerf64b3522008-03-09 01:54:53 +00001081 // Read the string argument.
1082 Token StrTok;
1083 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001084
Chris Lattnerf64b3522008-03-09 01:54:53 +00001085 // If the token kind isn't a string, it's a malformed directive.
1086 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001087 StrTok.isNot(tok::wide_string_literal)) {
1088 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001089 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001090 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001091 return;
1092 }
Mike Stump11289f42009-09-09 15:08:12 +00001093
Richard Smithd67aea22012-03-06 03:21:47 +00001094 if (StrTok.hasUDSuffix()) {
1095 Diag(StrTok, diag::err_invalid_string_udl);
1096 return DiscardUntilEndOfDirective();
1097 }
1098
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001099 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001100 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001101
Douglas Gregordc970f02010-03-16 22:30:13 +00001102 if (Callbacks) {
1103 bool Invalid = false;
1104 std::string Str = getSpelling(StrTok, &Invalid);
1105 if (!Invalid)
1106 Callbacks->Ident(Tok.getLocation(), Str);
1107 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001108}
1109
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001110/// \brief Handle a #public directive.
1111void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001112 Token MacroNameTok;
1113 ReadMacroName(MacroNameTok, 2);
1114
1115 // Error reading macro name? If so, diagnostic already issued.
1116 if (MacroNameTok.is(tok::eod))
1117 return;
1118
Douglas Gregor663b48f2012-01-03 19:48:16 +00001119 // Check to see if this is the last token on the #__public_macro line.
1120 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001121
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001122 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001123 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001124 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001125
1126 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001127 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001128 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001129 return;
1130 }
1131
1132 // Note that this macro has now been exported.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001133 MD->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1134
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001135 // If this macro directive came from a PCH file, mark it as having changed
1136 // since serialization.
1137 if (MD->isFromPCH()) {
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001138 MD->setChangedAfterLoad();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001139 assert(II->isFromAST());
1140 II->setChangedSinceDeserialization();
1141 }
Douglas Gregorebf00492011-10-17 15:32:29 +00001142}
1143
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001144/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001145void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1146 Token MacroNameTok;
1147 ReadMacroName(MacroNameTok, 2);
1148
1149 // Error reading macro name? If so, diagnostic already issued.
1150 if (MacroNameTok.is(tok::eod))
1151 return;
1152
Douglas Gregor663b48f2012-01-03 19:48:16 +00001153 // Check to see if this is the last token on the #__private_macro line.
1154 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001155
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001156 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001157 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001158 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001159
1160 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001161 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001162 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001163 return;
1164 }
1165
1166 // Note that this macro has now been marked private.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001167 MD->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
1168
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001169 // If this macro directive came from a PCH file, mark it as having changed
1170 // since serialization.
1171 if (MD->isFromPCH()) {
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001172 MD->setChangedAfterLoad();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001173 assert(II->isFromAST());
1174 II->setChangedSinceDeserialization();
1175 }
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001176}
1177
Chris Lattnerf64b3522008-03-09 01:54:53 +00001178//===----------------------------------------------------------------------===//
1179// Preprocessor Include Directive Handling.
1180//===----------------------------------------------------------------------===//
1181
1182/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001183/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001184/// true if the input filename was in <>'s or false if it were in ""'s. The
1185/// caller is expected to provide a buffer that is large enough to hold the
1186/// spelling of the filename, but is also expected to handle the case when
1187/// this method decides to use a different buffer.
1188bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001189 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001190 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001191 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001192
Chris Lattnerf64b3522008-03-09 01:54:53 +00001193 // Make sure the filename is <x> or "x".
1194 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001195 if (Buffer[0] == '<') {
1196 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001197 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001198 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001199 return true;
1200 }
1201 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001202 } else if (Buffer[0] == '"') {
1203 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001204 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001205 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001206 return true;
1207 }
1208 isAngled = false;
1209 } else {
1210 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001211 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001212 return true;
1213 }
Mike Stump11289f42009-09-09 15:08:12 +00001214
Chris Lattnerf64b3522008-03-09 01:54:53 +00001215 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001216 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001217 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001218 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001219 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001220 }
Mike Stump11289f42009-09-09 15:08:12 +00001221
Chris Lattnerf64b3522008-03-09 01:54:53 +00001222 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001223 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001224 return isAngled;
1225}
1226
James Dennettf6333ac2012-06-22 05:46:07 +00001227/// \brief Handle cases where the \#include name is expanded from a macro
1228/// as multiple tokens, which need to be glued together.
1229///
1230/// This occurs for code like:
1231/// \code
1232/// \#define FOO <a/b.h>
1233/// \#include FOO
1234/// \endcode
Chris Lattnerf64b3522008-03-09 01:54:53 +00001235/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1236///
1237/// This code concatenates and consumes tokens up to the '>' token. It returns
1238/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001239/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001240bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001241 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001242 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001243 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001244
John Thompsonb5353522009-10-30 13:49:06 +00001245 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001246 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001247 End = CurTok.getLocation();
1248
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001249 // FIXME: Provide code completion for #includes.
1250 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001251 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001252 Lex(CurTok);
1253 continue;
1254 }
1255
Chris Lattnerf64b3522008-03-09 01:54:53 +00001256 // Append the spelling of this token to the buffer. If there was a space
1257 // before it, add it now.
1258 if (CurTok.hasLeadingSpace())
1259 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001260
Chris Lattnerf64b3522008-03-09 01:54:53 +00001261 // Get the spelling of the token, directly into FilenameBuffer if possible.
1262 unsigned PreAppendSize = FilenameBuffer.size();
1263 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001264
Chris Lattnerf64b3522008-03-09 01:54:53 +00001265 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001266 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001267
Chris Lattnerf64b3522008-03-09 01:54:53 +00001268 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1269 if (BufPtr != &FilenameBuffer[PreAppendSize])
1270 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001271
Chris Lattnerf64b3522008-03-09 01:54:53 +00001272 // Resize FilenameBuffer to the correct size.
1273 if (CurTok.getLength() != ActualLen)
1274 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001275
Chris Lattnerf64b3522008-03-09 01:54:53 +00001276 // If we found the '>' marker, return success.
1277 if (CurTok.is(tok::greater))
1278 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001279
John Thompsonb5353522009-10-30 13:49:06 +00001280 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001281 }
1282
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001283 // If we hit the eod marker, emit an error and return true so that the caller
1284 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001285 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001286 return true;
1287}
1288
James Dennettf6333ac2012-06-22 05:46:07 +00001289/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1290/// the file to be included from the lexer, then include it! This is a common
1291/// routine with functionality shared between \#include, \#include_next and
1292/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001293/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001294void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1295 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001296 const DirectoryLookup *LookupFrom,
1297 bool isImport) {
1298
1299 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001300 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001301
Chris Lattnerf64b3522008-03-09 01:54:53 +00001302 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001303 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001304 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001305 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001306 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001307
Chris Lattnerf64b3522008-03-09 01:54:53 +00001308 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001309 case tok::eod:
1310 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001311 return;
Mike Stump11289f42009-09-09 15:08:12 +00001312
Chris Lattnerf64b3522008-03-09 01:54:53 +00001313 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001314 case tok::string_literal:
1315 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001316 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001317 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001318 break;
Mike Stump11289f42009-09-09 15:08:12 +00001319
Chris Lattnerf64b3522008-03-09 01:54:53 +00001320 case tok::less:
1321 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1322 // case, glue the tokens together into FilenameBuffer and interpret those.
1323 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001324 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001325 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001326 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001327 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001328 break;
1329 default:
1330 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1331 DiscardUntilEndOfDirective();
1332 return;
1333 }
Mike Stump11289f42009-09-09 15:08:12 +00001334
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001335 CharSourceRange FilenameRange
1336 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001337 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001338 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001339 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001340 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1341 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001342 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001343 DiscardUntilEndOfDirective();
1344 return;
1345 }
Mike Stump11289f42009-09-09 15:08:12 +00001346
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001347 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001348 // we allow macros that expand to nothing after the filename, because this
1349 // falls into the category of "#include pp-tokens new-line" specified in
1350 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001351 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001352
1353 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001354 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1355 Diag(FilenameTok, diag::err_pp_include_too_deep);
1356 return;
1357 }
Mike Stump11289f42009-09-09 15:08:12 +00001358
John McCall32f5fe12011-09-30 05:12:12 +00001359 // Complain about attempts to #include files in an audit pragma.
1360 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1361 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1362 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1363
1364 // Immediately leave the pragma.
1365 PragmaARCCFCodeAuditedLoc = SourceLocation();
1366 }
1367
Aaron Ballman611306e2012-03-02 22:51:54 +00001368 if (HeaderInfo.HasIncludeAliasMap()) {
1369 // Map the filename with the brackets still attached. If the name doesn't
1370 // map to anything, fall back on the filename we've already gotten the
1371 // spelling for.
1372 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1373 if (!NewName.empty())
1374 Filename = NewName;
1375 }
1376
Chris Lattnerf64b3522008-03-09 01:54:53 +00001377 // Search include directories.
1378 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001379 SmallString<1024> SearchPath;
1380 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001381 // We get the raw path only if we have 'Callbacks' to which we later pass
1382 // the path.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001383 Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001384 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001385 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001386 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001387 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001388
Douglas Gregor11729f02011-11-30 18:12:06 +00001389 if (Callbacks) {
1390 if (!File) {
1391 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001392 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001393 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1394 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1395 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001396 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001397 HeaderInfo.AddSearchPath(DL, isAngled);
1398
1399 // Try the lookup again, skipping the cache.
1400 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001401 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001402 /*SkipCache*/true);
1403 }
1404 }
1405 }
1406
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001407 if (!SuggestedModule) {
1408 // Notify the callback object that we've seen an inclusion directive.
1409 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1410 FilenameRange, File,
1411 SearchPath, RelativePath,
1412 /*ImportedModule=*/0);
1413 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001414 }
1415
1416 if (File == 0) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001417 if (!SuppressIncludeNotFoundError) {
1418 // If the file could not be located and it was included via angle
1419 // brackets, we can attempt a lookup as though it were a quoted path to
1420 // provide the user with a possible fixit.
1421 if (isAngled) {
1422 File = LookupFile(Filename, false, LookupFrom, CurDir,
1423 Callbacks ? &SearchPath : 0,
1424 Callbacks ? &RelativePath : 0,
1425 getLangOpts().Modules ? &SuggestedModule : 0);
1426 if (File) {
1427 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1428 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1429 Filename <<
1430 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1431 }
1432 }
1433 // If the file is still not found, just go with the vanilla diagnostic
1434 if (!File)
1435 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1436 }
1437 if (!File)
1438 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001439 }
1440
Douglas Gregor97eec242011-09-15 22:00:41 +00001441 // If we are supposed to import a module rather than including the header,
1442 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001443 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001444 // Compute the module access path corresponding to this module.
1445 // FIXME: Should we have a second loadModule() overload to avoid this
1446 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001447 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregorde3ef502011-11-30 23:21:26 +00001448 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001449 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1450 FilenameTok.getLocation()));
1451 std::reverse(Path.begin(), Path.end());
1452
Douglas Gregor41e115a2011-11-30 18:02:36 +00001453 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001454 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001455 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1456 if (I)
1457 PathString += '.';
1458 PathString += Path[I].first->getName();
1459 }
1460 int IncludeKind = 0;
1461
1462 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1463 case tok::pp_include:
1464 IncludeKind = 0;
1465 break;
1466
1467 case tok::pp_import:
1468 IncludeKind = 1;
1469 break;
1470
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001471 case tok::pp_include_next:
1472 IncludeKind = 2;
1473 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001474
1475 case tok::pp___include_macros:
1476 IncludeKind = 3;
1477 break;
1478
1479 default:
1480 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001481 }
1482
Douglas Gregor2537a362011-12-08 17:01:29 +00001483 // Determine whether we are actually building the module that this
1484 // include directive maps to.
1485 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001486 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001487
David Blaikiebbafb8a2012-03-11 07:00:24 +00001488 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001489 // If we're not building the imported module, warn that we're going
1490 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001491 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001492 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1493 /*IsTokenRange=*/false);
1494 Diag(HashLoc, diag::warn_auto_module_import)
1495 << IncludeKind << PathString
1496 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001497 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001498 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001499
Douglas Gregor71944202011-11-30 00:36:36 +00001500 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001501 // If this was an #__include_macros directive, only make macros visible.
1502 Module::NameVisibilityKind Visibility
1503 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001504 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001505 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1506 /*IsIncludeDirective=*/true);
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001507 assert((Imported == 0 || Imported == SuggestedModule) &&
1508 "the imported module is different than the suggested one");
Douglas Gregor2537a362011-12-08 17:01:29 +00001509
1510 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001511 if (!BuildingImportedModule && Imported) {
1512 if (Callbacks) {
1513 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1514 FilenameRange, File,
1515 SearchPath, RelativePath, Imported);
1516 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001517 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001518 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001519
1520 // If we failed to find a submodule that we expected to find, we can
1521 // continue. Otherwise, there's an error in the included file, so we
1522 // don't want to include it.
1523 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1524 return;
1525 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001526 }
1527
1528 if (Callbacks && SuggestedModule) {
1529 // We didn't notify the callback object that we've seen an inclusion
1530 // directive before. Now that we are parsing the include normally and not
1531 // turning it to a module import, notify the callback object.
1532 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1533 FilenameRange, File,
1534 SearchPath, RelativePath,
1535 /*ImportedModule=*/0);
Douglas Gregor97eec242011-09-15 22:00:41 +00001536 }
1537
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001538 // The #included file will be considered to be a system header if either it is
1539 // in a system include directory, or if the #includer is a system include
1540 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001541 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001542 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001543 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001544
Chris Lattner72286d62010-04-19 20:44:31 +00001545 // Ask HeaderInfo if we should enter this #include file. If not, #including
1546 // this file will have no effect.
1547 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001548 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001549 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001550 return;
1551 }
1552
Chris Lattnerf64b3522008-03-09 01:54:53 +00001553 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001554 SourceLocation IncludePos = End;
1555 // If the filename string was the result of macro expansions, set the include
1556 // position on the file where it will be included and after the expansions.
1557 if (IncludePos.isMacroID())
1558 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1559 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001560 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001561
1562 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001563 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001564}
1565
James Dennettf6333ac2012-06-22 05:46:07 +00001566/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001567///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001568void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1569 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001570 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001571
Chris Lattnerf64b3522008-03-09 01:54:53 +00001572 // #include_next is like #include, except that we start searching after
1573 // the current found directory. If we can't do this, issue a
1574 // diagnostic.
1575 const DirectoryLookup *Lookup = CurDirLookup;
1576 if (isInPrimaryFile()) {
1577 Lookup = 0;
1578 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1579 } else if (Lookup == 0) {
1580 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1581 } else {
1582 // Start looking up in the next directory.
1583 ++Lookup;
1584 }
Mike Stump11289f42009-09-09 15:08:12 +00001585
Douglas Gregor796d76a2010-10-20 22:00:55 +00001586 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001587}
1588
James Dennettf6333ac2012-06-22 05:46:07 +00001589/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001590void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1591 // The Microsoft #import directive takes a type library and generates header
1592 // files from it, and includes those. This is beyond the scope of what clang
1593 // does, so we ignore it and error out. However, #import can optionally have
1594 // trailing attributes that span multiple lines. We're going to eat those
1595 // so we can continue processing from there.
1596 Diag(Tok, diag::err_pp_import_directive_ms );
1597
1598 // Read tokens until we get to the end of the directive. Note that the
1599 // directive can be split over multiple lines using the backslash character.
1600 DiscardUntilEndOfDirective();
1601}
1602
James Dennettf6333ac2012-06-22 05:46:07 +00001603/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001604///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001605void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1606 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001607 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1608 if (LangOpts.MicrosoftMode)
1609 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001610 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001611 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001612 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001613}
1614
Chris Lattner58a1eb02009-04-08 18:46:40 +00001615/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1616/// pseudo directive in the predefines buffer. This handles it by sucking all
1617/// tokens through the preprocessor and discarding them (only keeping the side
1618/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001619void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1620 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001621 // This directive should only occur in the predefines buffer. If not, emit an
1622 // error and reject it.
1623 SourceLocation Loc = IncludeMacrosTok.getLocation();
1624 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1625 Diag(IncludeMacrosTok.getLocation(),
1626 diag::pp_include_macros_out_of_predefines);
1627 DiscardUntilEndOfDirective();
1628 return;
1629 }
Mike Stump11289f42009-09-09 15:08:12 +00001630
Chris Lattnere01d82b2009-04-08 20:53:24 +00001631 // Treat this as a normal #include for checking purposes. If this is
1632 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001633 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chris Lattnere01d82b2009-04-08 20:53:24 +00001635 Token TmpTok;
1636 do {
1637 Lex(TmpTok);
1638 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1639 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001640}
1641
Chris Lattnerf64b3522008-03-09 01:54:53 +00001642//===----------------------------------------------------------------------===//
1643// Preprocessor Macro Directive Handling.
1644//===----------------------------------------------------------------------===//
1645
1646/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1647/// definition has just been read. Lex the rest of the arguments and the
1648/// closing ), updating MI with what we learn. Return true if an error occurs
1649/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001650bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001651 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001652
Chris Lattnerf64b3522008-03-09 01:54:53 +00001653 while (1) {
1654 LexUnexpandedToken(Tok);
1655 switch (Tok.getKind()) {
1656 case tok::r_paren:
1657 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001658 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001659 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001660 // Otherwise we have #define FOO(A,)
1661 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1662 return true;
1663 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001664 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001665 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001666 diag::warn_cxx98_compat_variadic_macro :
1667 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001668
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001669 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1670 if (LangOpts.OpenCL) {
1671 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1672 return true;
1673 }
1674
Chris Lattnerf64b3522008-03-09 01:54:53 +00001675 // Lex the token after the identifier.
1676 LexUnexpandedToken(Tok);
1677 if (Tok.isNot(tok::r_paren)) {
1678 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1679 return true;
1680 }
1681 // Add the __VA_ARGS__ identifier as an argument.
1682 Arguments.push_back(Ident__VA_ARGS__);
1683 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001684 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001685 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001686 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001687 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1688 return true;
1689 default:
1690 // Handle keywords and identifiers here to accept things like
1691 // #define Foo(for) for.
1692 IdentifierInfo *II = Tok.getIdentifierInfo();
1693 if (II == 0) {
1694 // #define X(1
1695 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1696 return true;
1697 }
1698
1699 // If this is already used as an argument, it is used multiple times (e.g.
1700 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001701 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001702 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001703 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001704 return true;
1705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
Chris Lattnerf64b3522008-03-09 01:54:53 +00001707 // Add the argument to the macro info.
1708 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Chris Lattnerf64b3522008-03-09 01:54:53 +00001710 // Lex the token after the identifier.
1711 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001712
Chris Lattnerf64b3522008-03-09 01:54:53 +00001713 switch (Tok.getKind()) {
1714 default: // #define X(A B
1715 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1716 return true;
1717 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001718 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001719 return false;
1720 case tok::comma: // #define X(A,
1721 break;
1722 case tok::ellipsis: // #define X(A... -> GCC extension
1723 // Diagnose extension.
1724 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001725
Chris Lattnerf64b3522008-03-09 01:54:53 +00001726 // Lex the token after the identifier.
1727 LexUnexpandedToken(Tok);
1728 if (Tok.isNot(tok::r_paren)) {
1729 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1730 return true;
1731 }
Mike Stump11289f42009-09-09 15:08:12 +00001732
Chris Lattnerf64b3522008-03-09 01:54:53 +00001733 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001734 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001735 return false;
1736 }
1737 }
1738 }
1739}
1740
James Dennettf6333ac2012-06-22 05:46:07 +00001741/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001742/// line then lets the caller lex the next real token.
1743void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1744 ++NumDefined;
1745
1746 Token MacroNameTok;
1747 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001748
Chris Lattnerf64b3522008-03-09 01:54:53 +00001749 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001750 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001751 return;
1752
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001753 Token LastTok = MacroNameTok;
1754
Chris Lattnerf64b3522008-03-09 01:54:53 +00001755 // If we are supposed to keep comments in #defines, reenable comment saving
1756 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001757 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001758
Chris Lattnerf64b3522008-03-09 01:54:53 +00001759 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001760 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001761
Chris Lattnerf64b3522008-03-09 01:54:53 +00001762 Token Tok;
1763 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001764
Chris Lattnerf64b3522008-03-09 01:54:53 +00001765 // If this is a function-like macro definition, parse the argument list,
1766 // marking each of the identifiers as being used as macro arguments. Also,
1767 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001768 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001769 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001770 } else if (Tok.hasLeadingSpace()) {
1771 // This is a normal token with leading space. Clear the leading space
1772 // marker on the first token to get proper expansion.
1773 Tok.clearFlag(Token::LeadingSpace);
1774 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001775 // This is a function-like macro definition. Read the argument list.
1776 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001777 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001778 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001779 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001780 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001781 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001782 DiscardUntilEndOfDirective();
1783 return;
1784 }
1785
Chris Lattner249c38b2009-04-19 18:26:34 +00001786 // If this is a definition of a variadic C99 function-like macro, not using
1787 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001788
Chris Lattner249c38b2009-04-19 18:26:34 +00001789 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1790 // This gets unpoisoned where it is allowed.
1791 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1792 if (MI->isC99Varargs())
1793 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001794
Chris Lattnerf64b3522008-03-09 01:54:53 +00001795 // Read the first token after the arg list for down below.
1796 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001797 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001798 // C99 requires whitespace between the macro definition and the body. Emit
1799 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001800 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001801 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001802 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1803 // first character of a replacement list is not a character required by
1804 // subclause 5.2.1, then there shall be white-space separation between the
1805 // identifier and the replacement list.". 5.2.1 lists this set:
1806 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1807 // is irrelevant here.
1808 bool isInvalid = false;
1809 if (Tok.is(tok::at)) // @ is not in the list above.
1810 isInvalid = true;
1811 else if (Tok.is(tok::unknown)) {
1812 // If we have an unknown token, it is something strange like "`". Since
1813 // all of valid characters would have lexed into a single character
1814 // token of some sort, we know this is not a valid case.
1815 isInvalid = true;
1816 }
1817 if (isInvalid)
1818 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1819 else
1820 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001821 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001822
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001823 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001824 LastTok = Tok;
1825
Chris Lattnerf64b3522008-03-09 01:54:53 +00001826 // Read the rest of the macro body.
1827 if (MI->isObjectLike()) {
1828 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001829 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001830 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001831 MI->AddTokenToBody(Tok);
1832 // Get the next token of the macro.
1833 LexUnexpandedToken(Tok);
1834 }
Mike Stump11289f42009-09-09 15:08:12 +00001835
Chris Lattnerf64b3522008-03-09 01:54:53 +00001836 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001837 // Otherwise, read the body of a function-like macro. While we are at it,
1838 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1839 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001840 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001841 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001842
Eli Friedman14d3c792012-11-14 02:18:46 +00001843 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001844 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattnerf64b3522008-03-09 01:54:53 +00001846 // Get the next token of the macro.
1847 LexUnexpandedToken(Tok);
1848 continue;
1849 }
Mike Stump11289f42009-09-09 15:08:12 +00001850
Eli Friedman14d3c792012-11-14 02:18:46 +00001851 if (Tok.is(tok::hashhash)) {
1852
1853 // If we see token pasting, check if it looks like the gcc comma
1854 // pasting extension. We'll use this information to suppress
1855 // diagnostics later on.
1856
1857 // Get the next token of the macro.
1858 LexUnexpandedToken(Tok);
1859
1860 if (Tok.is(tok::eod)) {
1861 MI->AddTokenToBody(LastTok);
1862 break;
1863 }
1864
1865 unsigned NumTokens = MI->getNumTokens();
1866 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1867 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1868 MI->setHasCommaPasting();
1869
1870 // Things look ok, add the '##' and param name tokens to the macro.
1871 MI->AddTokenToBody(LastTok);
1872 MI->AddTokenToBody(Tok);
1873 LastTok = Tok;
1874
1875 // Get the next token of the macro.
1876 LexUnexpandedToken(Tok);
1877 continue;
1878 }
1879
Chris Lattnerf64b3522008-03-09 01:54:53 +00001880 // Get the next token of the macro.
1881 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001882
Chris Lattner83bd8282009-05-25 17:16:10 +00001883 // Check for a valid macro arg identifier.
1884 if (Tok.getIdentifierInfo() == 0 ||
1885 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1886
1887 // If this is assembler-with-cpp mode, we accept random gibberish after
1888 // the '#' because '#' is often a comment character. However, change
1889 // the kind of the token to tok::unknown so that the preprocessor isn't
1890 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001891 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001892 LastTok.setKind(tok::unknown);
1893 } else {
1894 Diag(Tok, diag::err_pp_stringize_not_parameter);
1895 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001896
Chris Lattner83bd8282009-05-25 17:16:10 +00001897 // Disable __VA_ARGS__ again.
1898 Ident__VA_ARGS__->setIsPoisoned(true);
1899 return;
1900 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001901 }
Mike Stump11289f42009-09-09 15:08:12 +00001902
Chris Lattner83bd8282009-05-25 17:16:10 +00001903 // Things look ok, add the '#' and param name tokens to the macro.
1904 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001905 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001906 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001907
Chris Lattnerf64b3522008-03-09 01:54:53 +00001908 // Get the next token of the macro.
1909 LexUnexpandedToken(Tok);
1910 }
1911 }
Mike Stump11289f42009-09-09 15:08:12 +00001912
1913
Chris Lattnerf64b3522008-03-09 01:54:53 +00001914 // Disable __VA_ARGS__ again.
1915 Ident__VA_ARGS__->setIsPoisoned(true);
1916
Chris Lattner57540c52011-04-15 05:22:18 +00001917 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001918 // replacement list.
1919 unsigned NumTokens = MI->getNumTokens();
1920 if (NumTokens != 0) {
1921 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1922 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001923 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001924 return;
1925 }
1926 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1927 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001928 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001929 return;
1930 }
1931 }
Mike Stump11289f42009-09-09 15:08:12 +00001932
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001933 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001934
Chris Lattnerf64b3522008-03-09 01:54:53 +00001935 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00001936 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001937 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001938 // It is very common for system headers to have tons of macro redefinitions
1939 // and for warnings to be disabled in system headers. If this is the case,
1940 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001941 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001942 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001943 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001944 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001945
Richard Smith7b242542013-03-06 00:46:00 +00001946 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
1947 // C++ [cpp.predefined]p4, but allow it as an extension.
1948 if (OtherMI->isBuiltinMacro())
1949 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001950 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001951 // separation must be the same. C99 6.10.3.2.
Richard Smith7b242542013-03-06 00:46:00 +00001952 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
1953 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001954 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1955 << MacroNameTok.getIdentifierInfo();
1956 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1957 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001958 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001959 if (OtherMI->isWarnIfUnused())
1960 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00001963 MacroDirective *MD = setMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001964
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001965 assert(!MI->isUsed());
1966 // If we need warning for not using the macro, add its location in the
1967 // warn-because-unused-macro set. If it gets used it will be removed from set.
1968 if (isInPrimaryFile() && // don't warn for include'd macros.
1969 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00001970 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001971 MI->setIsWarnIfUnused(true);
1972 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1973 }
1974
Chris Lattner928e9092009-04-12 01:39:54 +00001975 // If the callbacks want to know, tell them about the macro definition.
1976 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00001977 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001978}
1979
James Dennettf6333ac2012-06-22 05:46:07 +00001980/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001981///
1982void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1983 ++NumUndefined;
1984
1985 Token MacroNameTok;
1986 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001987
Chris Lattnerf64b3522008-03-09 01:54:53 +00001988 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001989 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001990 return;
Mike Stump11289f42009-09-09 15:08:12 +00001991
Chris Lattnerf64b3522008-03-09 01:54:53 +00001992 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001993 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001994
Chris Lattnerf64b3522008-03-09 01:54:53 +00001995 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001996 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
1997 const MacroInfo *MI = MD ? MD->getInfo() : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001998
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00001999 // If the callbacks want to know, tell them about the macro #undef.
2000 // Note: no matter if the macro was defined or not.
2001 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002002 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002003
Chris Lattnerf64b3522008-03-09 01:54:53 +00002004 // If the macro is not defined, this is a noop undef, just return.
2005 if (MI == 0) return;
2006
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002007 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002008 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002009
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002010 if (MI->isWarnIfUnused())
2011 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2012
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002013 UndefineMacro(MacroNameTok.getIdentifierInfo(), MD,
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002014 MacroNameTok.getLocation());
2015}
2016
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002017void Preprocessor::UndefineMacro(IdentifierInfo *II, MacroDirective *MD,
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002018 SourceLocation UndefLoc) {
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002019 MD->setUndefLoc(UndefLoc);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002020 if (MD->isFromPCH()) {
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002021 MD->setChangedAfterLoad();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002022 if (Listener)
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002023 Listener->UndefinedMacro(MD);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002024 }
2025
2026 clearMacroInfo(II);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002027}
2028
2029
2030//===----------------------------------------------------------------------===//
2031// Preprocessor Conditional Directive Handling.
2032//===----------------------------------------------------------------------===//
2033
James Dennettf6333ac2012-06-22 05:46:07 +00002034/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2035/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2036/// true if any tokens have been returned or pp-directives activated before this
2037/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002038///
2039void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2040 bool ReadAnyTokensBeforeDirective) {
2041 ++NumIf;
2042 Token DirectiveTok = Result;
2043
2044 Token MacroNameTok;
2045 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002046
Chris Lattnerf64b3522008-03-09 01:54:53 +00002047 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002048 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002049 // Skip code until we get to #endif. This helps with recovery by not
2050 // emitting an error when the #endif is reached.
2051 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2052 /*Foundnonskip*/false, /*FoundElse*/false);
2053 return;
2054 }
Mike Stump11289f42009-09-09 15:08:12 +00002055
Chris Lattnerf64b3522008-03-09 01:54:53 +00002056 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002057 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002058
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002059 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002060 MacroDirective *MD = getMacroDirective(MII);
2061 MacroInfo *MI = MD ? MD->getInfo() : 0;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002062
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002063 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002064 // If the start of a top-level #ifdef and if the macro is not defined,
2065 // inform MIOpt that this might be the start of a proper include guard.
2066 // Otherwise it is some other form of unknown conditional which we can't
2067 // handle.
2068 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002069 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002070 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002071 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002072 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002073 }
2074
Chris Lattnerf64b3522008-03-09 01:54:53 +00002075 // If there is a macro, process it.
2076 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002077 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002078
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002079 if (Callbacks) {
2080 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002081 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002082 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002083 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002084 }
2085
Chris Lattnerf64b3522008-03-09 01:54:53 +00002086 // Should we include the stuff contained by this directive?
2087 if (!MI == isIfndef) {
2088 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002089 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2090 /*wasskip*/false, /*foundnonskip*/true,
2091 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002092 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002093 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002094 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002095 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002096 /*FoundElse*/false);
2097 }
2098}
2099
James Dennettf6333ac2012-06-22 05:46:07 +00002100/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002101///
2102void Preprocessor::HandleIfDirective(Token &IfToken,
2103 bool ReadAnyTokensBeforeDirective) {
2104 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002105
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002106 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002107 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002108 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2109 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2110 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002111
2112 // If this condition is equivalent to #ifndef X, and if this is the first
2113 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002114 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002115 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002116 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00002117 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002118 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002119 }
2120
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002121 if (Callbacks)
2122 Callbacks->If(IfToken.getLocation(),
2123 SourceRange(ConditionalBegin, ConditionalEnd));
2124
Chris Lattnerf64b3522008-03-09 01:54:53 +00002125 // Should we include the stuff contained by this directive?
2126 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002127 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002128 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002129 /*foundnonskip*/true, /*foundelse*/false);
2130 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002131 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002132 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002133 /*FoundElse*/false);
2134 }
2135}
2136
James Dennettf6333ac2012-06-22 05:46:07 +00002137/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002138///
2139void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2140 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002141
Chris Lattnerf64b3522008-03-09 01:54:53 +00002142 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002143 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002144
Chris Lattnerf64b3522008-03-09 01:54:53 +00002145 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002146 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002147 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002148 Diag(EndifToken, diag::err_pp_endif_without_if);
2149 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002150 }
Mike Stump11289f42009-09-09 15:08:12 +00002151
Chris Lattnerf64b3522008-03-09 01:54:53 +00002152 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002153 if (CurPPLexer->getConditionalStackDepth() == 0)
2154 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002155
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002156 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002157 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002158
2159 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002160 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002161}
2162
James Dennettf6333ac2012-06-22 05:46:07 +00002163/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002164///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002165void Preprocessor::HandleElseDirective(Token &Result) {
2166 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002167
Chris Lattnerf64b3522008-03-09 01:54:53 +00002168 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002169 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002170
Chris Lattnerf64b3522008-03-09 01:54:53 +00002171 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002172 if (CurPPLexer->popConditionalLevel(CI)) {
2173 Diag(Result, diag::pp_err_else_without_if);
2174 return;
2175 }
Mike Stump11289f42009-09-09 15:08:12 +00002176
Chris Lattnerf64b3522008-03-09 01:54:53 +00002177 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002178 if (CurPPLexer->getConditionalStackDepth() == 0)
2179 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002180
2181 // If this is a #else with a #else before it, report the error.
2182 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002183
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002184 if (Callbacks)
2185 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2186
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002187 // Finally, skip the rest of the contents of this block.
2188 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002189 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002190}
2191
James Dennettf6333ac2012-06-22 05:46:07 +00002192/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002193///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002194void Preprocessor::HandleElifDirective(Token &ElifToken) {
2195 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002196
Chris Lattnerf64b3522008-03-09 01:54:53 +00002197 // #elif directive in a non-skipping conditional... start skipping.
2198 // We don't care what the condition is, because we will always skip it (since
2199 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002200 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002201 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002202 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002203
2204 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002205 if (CurPPLexer->popConditionalLevel(CI)) {
2206 Diag(ElifToken, diag::pp_err_elif_without_if);
2207 return;
2208 }
Mike Stump11289f42009-09-09 15:08:12 +00002209
Chris Lattnerf64b3522008-03-09 01:54:53 +00002210 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002211 if (CurPPLexer->getConditionalStackDepth() == 0)
2212 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002213
Chris Lattnerf64b3522008-03-09 01:54:53 +00002214 // If this is a #elif with a #else before it, report the error.
2215 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002216
2217 if (Callbacks)
2218 Callbacks->Elif(ElifToken.getLocation(),
2219 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002220
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002221 // Finally, skip the rest of the contents of this block.
2222 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002223 /*FoundElse*/CI.FoundElse,
2224 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002225}