blob: 163dbf413e673bfb9d81db6da23e61ada43b2831 [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
1122 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001123 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001124
1125 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001126 if (MD == 0) {
Douglas Gregorebf00492011-10-17 15:32:29 +00001127 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001128 << MacroNameTok.getIdentifierInfo();
1129 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
Douglas Gregorebf00492011-10-17 15:32:29 +00001135 // If this macro definition came from a PCH file, mark it
1136 // as having changed since serialization.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001137 if (MD->isImported())
1138 MD->setChangedAfterLoad();
Douglas Gregorebf00492011-10-17 15:32:29 +00001139}
1140
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001141/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001142void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1143 Token MacroNameTok;
1144 ReadMacroName(MacroNameTok, 2);
1145
1146 // Error reading macro name? If so, diagnostic already issued.
1147 if (MacroNameTok.is(tok::eod))
1148 return;
1149
Douglas Gregor663b48f2012-01-03 19:48:16 +00001150 // Check to see if this is the last token on the #__private_macro line.
1151 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001152
1153 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001154 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Douglas Gregorebf00492011-10-17 15:32:29 +00001155
1156 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001157 if (MD == 0) {
Douglas Gregorebf00492011-10-17 15:32:29 +00001158 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1159 << MacroNameTok.getIdentifierInfo();
1160 return;
1161 }
1162
1163 // Note that this macro has now been marked private.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001164 MD->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
1165
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001166 // If this macro definition came from a PCH file, mark it
1167 // as having changed since serialization.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001168 if (MD->isImported())
1169 MD->setChangedAfterLoad();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001170}
1171
Chris Lattnerf64b3522008-03-09 01:54:53 +00001172//===----------------------------------------------------------------------===//
1173// Preprocessor Include Directive Handling.
1174//===----------------------------------------------------------------------===//
1175
1176/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001177/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001178/// true if the input filename was in <>'s or false if it were in ""'s. The
1179/// caller is expected to provide a buffer that is large enough to hold the
1180/// spelling of the filename, but is also expected to handle the case when
1181/// this method decides to use a different buffer.
1182bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001183 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001184 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001185 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001186
Chris Lattnerf64b3522008-03-09 01:54:53 +00001187 // Make sure the filename is <x> or "x".
1188 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001189 if (Buffer[0] == '<') {
1190 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001191 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001192 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001193 return true;
1194 }
1195 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001196 } else if (Buffer[0] == '"') {
1197 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001198 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001199 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001200 return true;
1201 }
1202 isAngled = false;
1203 } else {
1204 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 }
Mike Stump11289f42009-09-09 15:08:12 +00001208
Chris Lattnerf64b3522008-03-09 01:54:53 +00001209 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001210 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001211 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001212 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001213 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001214 }
Mike Stump11289f42009-09-09 15:08:12 +00001215
Chris Lattnerf64b3522008-03-09 01:54:53 +00001216 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001217 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001218 return isAngled;
1219}
1220
James Dennettf6333ac2012-06-22 05:46:07 +00001221/// \brief Handle cases where the \#include name is expanded from a macro
1222/// as multiple tokens, which need to be glued together.
1223///
1224/// This occurs for code like:
1225/// \code
1226/// \#define FOO <a/b.h>
1227/// \#include FOO
1228/// \endcode
Chris Lattnerf64b3522008-03-09 01:54:53 +00001229/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1230///
1231/// This code concatenates and consumes tokens up to the '>' token. It returns
1232/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001233/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001234bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001235 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001236 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001237 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001238
John Thompsonb5353522009-10-30 13:49:06 +00001239 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001240 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001241 End = CurTok.getLocation();
1242
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001243 // FIXME: Provide code completion for #includes.
1244 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001245 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001246 Lex(CurTok);
1247 continue;
1248 }
1249
Chris Lattnerf64b3522008-03-09 01:54:53 +00001250 // Append the spelling of this token to the buffer. If there was a space
1251 // before it, add it now.
1252 if (CurTok.hasLeadingSpace())
1253 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001254
Chris Lattnerf64b3522008-03-09 01:54:53 +00001255 // Get the spelling of the token, directly into FilenameBuffer if possible.
1256 unsigned PreAppendSize = FilenameBuffer.size();
1257 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001258
Chris Lattnerf64b3522008-03-09 01:54:53 +00001259 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001260 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattnerf64b3522008-03-09 01:54:53 +00001262 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1263 if (BufPtr != &FilenameBuffer[PreAppendSize])
1264 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001265
Chris Lattnerf64b3522008-03-09 01:54:53 +00001266 // Resize FilenameBuffer to the correct size.
1267 if (CurTok.getLength() != ActualLen)
1268 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001269
Chris Lattnerf64b3522008-03-09 01:54:53 +00001270 // If we found the '>' marker, return success.
1271 if (CurTok.is(tok::greater))
1272 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001273
John Thompsonb5353522009-10-30 13:49:06 +00001274 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001275 }
1276
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001277 // If we hit the eod marker, emit an error and return true so that the caller
1278 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001279 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001280 return true;
1281}
1282
James Dennettf6333ac2012-06-22 05:46:07 +00001283/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1284/// the file to be included from the lexer, then include it! This is a common
1285/// routine with functionality shared between \#include, \#include_next and
1286/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001287/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001288void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1289 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001290 const DirectoryLookup *LookupFrom,
1291 bool isImport) {
1292
1293 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001294 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001295
Chris Lattnerf64b3522008-03-09 01:54:53 +00001296 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001297 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001298 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001299 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001300 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001301
Chris Lattnerf64b3522008-03-09 01:54:53 +00001302 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001303 case tok::eod:
1304 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001305 return;
Mike Stump11289f42009-09-09 15:08:12 +00001306
Chris Lattnerf64b3522008-03-09 01:54:53 +00001307 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001308 case tok::string_literal:
1309 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001310 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001311 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001312 break;
Mike Stump11289f42009-09-09 15:08:12 +00001313
Chris Lattnerf64b3522008-03-09 01:54:53 +00001314 case tok::less:
1315 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1316 // case, glue the tokens together into FilenameBuffer and interpret those.
1317 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001318 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001319 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001320 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001321 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001322 break;
1323 default:
1324 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1325 DiscardUntilEndOfDirective();
1326 return;
1327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001329 CharSourceRange FilenameRange
1330 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001331 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001332 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001333 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001334 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1335 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001336 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001337 DiscardUntilEndOfDirective();
1338 return;
1339 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001341 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001342 // we allow macros that expand to nothing after the filename, because this
1343 // falls into the category of "#include pp-tokens new-line" specified in
1344 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001345 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001346
1347 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001348 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1349 Diag(FilenameTok, diag::err_pp_include_too_deep);
1350 return;
1351 }
Mike Stump11289f42009-09-09 15:08:12 +00001352
John McCall32f5fe12011-09-30 05:12:12 +00001353 // Complain about attempts to #include files in an audit pragma.
1354 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1355 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1356 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1357
1358 // Immediately leave the pragma.
1359 PragmaARCCFCodeAuditedLoc = SourceLocation();
1360 }
1361
Aaron Ballman611306e2012-03-02 22:51:54 +00001362 if (HeaderInfo.HasIncludeAliasMap()) {
1363 // Map the filename with the brackets still attached. If the name doesn't
1364 // map to anything, fall back on the filename we've already gotten the
1365 // spelling for.
1366 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1367 if (!NewName.empty())
1368 Filename = NewName;
1369 }
1370
Chris Lattnerf64b3522008-03-09 01:54:53 +00001371 // Search include directories.
1372 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001373 SmallString<1024> SearchPath;
1374 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001375 // We get the raw path only if we have 'Callbacks' to which we later pass
1376 // the path.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001377 Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001378 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001379 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001380 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001381 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001382
Douglas Gregor11729f02011-11-30 18:12:06 +00001383 if (Callbacks) {
1384 if (!File) {
1385 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001386 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001387 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1388 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1389 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001390 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001391 HeaderInfo.AddSearchPath(DL, isAngled);
1392
1393 // Try the lookup again, skipping the cache.
1394 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001395 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001396 /*SkipCache*/true);
1397 }
1398 }
1399 }
1400
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001401 if (!SuggestedModule) {
1402 // Notify the callback object that we've seen an inclusion directive.
1403 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1404 FilenameRange, File,
1405 SearchPath, RelativePath,
1406 /*ImportedModule=*/0);
1407 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001408 }
1409
1410 if (File == 0) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001411 if (!SuppressIncludeNotFoundError) {
1412 // If the file could not be located and it was included via angle
1413 // brackets, we can attempt a lookup as though it were a quoted path to
1414 // provide the user with a possible fixit.
1415 if (isAngled) {
1416 File = LookupFile(Filename, false, LookupFrom, CurDir,
1417 Callbacks ? &SearchPath : 0,
1418 Callbacks ? &RelativePath : 0,
1419 getLangOpts().Modules ? &SuggestedModule : 0);
1420 if (File) {
1421 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1422 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1423 Filename <<
1424 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1425 }
1426 }
1427 // If the file is still not found, just go with the vanilla diagnostic
1428 if (!File)
1429 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1430 }
1431 if (!File)
1432 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001433 }
1434
Douglas Gregor97eec242011-09-15 22:00:41 +00001435 // If we are supposed to import a module rather than including the header,
1436 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001437 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001438 // Compute the module access path corresponding to this module.
1439 // FIXME: Should we have a second loadModule() overload to avoid this
1440 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001441 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregorde3ef502011-11-30 23:21:26 +00001442 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001443 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1444 FilenameTok.getLocation()));
1445 std::reverse(Path.begin(), Path.end());
1446
Douglas Gregor41e115a2011-11-30 18:02:36 +00001447 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001448 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001449 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1450 if (I)
1451 PathString += '.';
1452 PathString += Path[I].first->getName();
1453 }
1454 int IncludeKind = 0;
1455
1456 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1457 case tok::pp_include:
1458 IncludeKind = 0;
1459 break;
1460
1461 case tok::pp_import:
1462 IncludeKind = 1;
1463 break;
1464
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001465 case tok::pp_include_next:
1466 IncludeKind = 2;
1467 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001468
1469 case tok::pp___include_macros:
1470 IncludeKind = 3;
1471 break;
1472
1473 default:
1474 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001475 }
1476
Douglas Gregor2537a362011-12-08 17:01:29 +00001477 // Determine whether we are actually building the module that this
1478 // include directive maps to.
1479 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001480 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001481
David Blaikiebbafb8a2012-03-11 07:00:24 +00001482 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001483 // If we're not building the imported module, warn that we're going
1484 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001485 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001486 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1487 /*IsTokenRange=*/false);
1488 Diag(HashLoc, diag::warn_auto_module_import)
1489 << IncludeKind << PathString
1490 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001491 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001492 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001493
Douglas Gregor71944202011-11-30 00:36:36 +00001494 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001495 // If this was an #__include_macros directive, only make macros visible.
1496 Module::NameVisibilityKind Visibility
1497 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001498 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001499 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1500 /*IsIncludeDirective=*/true);
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001501 assert((Imported == 0 || Imported == SuggestedModule) &&
1502 "the imported module is different than the suggested one");
Douglas Gregor2537a362011-12-08 17:01:29 +00001503
1504 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001505 if (!BuildingImportedModule && Imported) {
1506 if (Callbacks) {
1507 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1508 FilenameRange, File,
1509 SearchPath, RelativePath, Imported);
1510 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001511 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001512 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001513
1514 // If we failed to find a submodule that we expected to find, we can
1515 // continue. Otherwise, there's an error in the included file, so we
1516 // don't want to include it.
1517 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1518 return;
1519 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001520 }
1521
1522 if (Callbacks && SuggestedModule) {
1523 // We didn't notify the callback object that we've seen an inclusion
1524 // directive before. Now that we are parsing the include normally and not
1525 // turning it to a module import, notify the callback object.
1526 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1527 FilenameRange, File,
1528 SearchPath, RelativePath,
1529 /*ImportedModule=*/0);
Douglas Gregor97eec242011-09-15 22:00:41 +00001530 }
1531
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001532 // The #included file will be considered to be a system header if either it is
1533 // in a system include directory, or if the #includer is a system include
1534 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001535 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001536 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001537 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001538
Chris Lattner72286d62010-04-19 20:44:31 +00001539 // Ask HeaderInfo if we should enter this #include file. If not, #including
1540 // this file will have no effect.
1541 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001542 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001543 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001544 return;
1545 }
1546
Chris Lattnerf64b3522008-03-09 01:54:53 +00001547 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001548 SourceLocation IncludePos = End;
1549 // If the filename string was the result of macro expansions, set the include
1550 // position on the file where it will be included and after the expansions.
1551 if (IncludePos.isMacroID())
1552 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1553 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001554 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001555
1556 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001557 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001558}
1559
James Dennettf6333ac2012-06-22 05:46:07 +00001560/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001561///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001562void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1563 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001564 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001565
Chris Lattnerf64b3522008-03-09 01:54:53 +00001566 // #include_next is like #include, except that we start searching after
1567 // the current found directory. If we can't do this, issue a
1568 // diagnostic.
1569 const DirectoryLookup *Lookup = CurDirLookup;
1570 if (isInPrimaryFile()) {
1571 Lookup = 0;
1572 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1573 } else if (Lookup == 0) {
1574 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1575 } else {
1576 // Start looking up in the next directory.
1577 ++Lookup;
1578 }
Mike Stump11289f42009-09-09 15:08:12 +00001579
Douglas Gregor796d76a2010-10-20 22:00:55 +00001580 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001581}
1582
James Dennettf6333ac2012-06-22 05:46:07 +00001583/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001584void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1585 // The Microsoft #import directive takes a type library and generates header
1586 // files from it, and includes those. This is beyond the scope of what clang
1587 // does, so we ignore it and error out. However, #import can optionally have
1588 // trailing attributes that span multiple lines. We're going to eat those
1589 // so we can continue processing from there.
1590 Diag(Tok, diag::err_pp_import_directive_ms );
1591
1592 // Read tokens until we get to the end of the directive. Note that the
1593 // directive can be split over multiple lines using the backslash character.
1594 DiscardUntilEndOfDirective();
1595}
1596
James Dennettf6333ac2012-06-22 05:46:07 +00001597/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001598///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001599void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1600 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001601 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1602 if (LangOpts.MicrosoftMode)
1603 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001604 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001605 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001606 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001607}
1608
Chris Lattner58a1eb02009-04-08 18:46:40 +00001609/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1610/// pseudo directive in the predefines buffer. This handles it by sucking all
1611/// tokens through the preprocessor and discarding them (only keeping the side
1612/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001613void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1614 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001615 // This directive should only occur in the predefines buffer. If not, emit an
1616 // error and reject it.
1617 SourceLocation Loc = IncludeMacrosTok.getLocation();
1618 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1619 Diag(IncludeMacrosTok.getLocation(),
1620 diag::pp_include_macros_out_of_predefines);
1621 DiscardUntilEndOfDirective();
1622 return;
1623 }
Mike Stump11289f42009-09-09 15:08:12 +00001624
Chris Lattnere01d82b2009-04-08 20:53:24 +00001625 // Treat this as a normal #include for checking purposes. If this is
1626 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001627 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001628
Chris Lattnere01d82b2009-04-08 20:53:24 +00001629 Token TmpTok;
1630 do {
1631 Lex(TmpTok);
1632 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1633 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001634}
1635
Chris Lattnerf64b3522008-03-09 01:54:53 +00001636//===----------------------------------------------------------------------===//
1637// Preprocessor Macro Directive Handling.
1638//===----------------------------------------------------------------------===//
1639
1640/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1641/// definition has just been read. Lex the rest of the arguments and the
1642/// closing ), updating MI with what we learn. Return true if an error occurs
1643/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001644bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001645 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001646
Chris Lattnerf64b3522008-03-09 01:54:53 +00001647 while (1) {
1648 LexUnexpandedToken(Tok);
1649 switch (Tok.getKind()) {
1650 case tok::r_paren:
1651 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001652 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001653 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001654 // Otherwise we have #define FOO(A,)
1655 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1656 return true;
1657 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001658 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001659 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001660 diag::warn_cxx98_compat_variadic_macro :
1661 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001662
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001663 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1664 if (LangOpts.OpenCL) {
1665 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1666 return true;
1667 }
1668
Chris Lattnerf64b3522008-03-09 01:54:53 +00001669 // Lex the token after the identifier.
1670 LexUnexpandedToken(Tok);
1671 if (Tok.isNot(tok::r_paren)) {
1672 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1673 return true;
1674 }
1675 // Add the __VA_ARGS__ identifier as an argument.
1676 Arguments.push_back(Ident__VA_ARGS__);
1677 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001678 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001679 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001680 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001681 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1682 return true;
1683 default:
1684 // Handle keywords and identifiers here to accept things like
1685 // #define Foo(for) for.
1686 IdentifierInfo *II = Tok.getIdentifierInfo();
1687 if (II == 0) {
1688 // #define X(1
1689 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1690 return true;
1691 }
1692
1693 // If this is already used as an argument, it is used multiple times (e.g.
1694 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001695 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001696 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001697 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001698 return true;
1699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700
Chris Lattnerf64b3522008-03-09 01:54:53 +00001701 // Add the argument to the macro info.
1702 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001703
Chris Lattnerf64b3522008-03-09 01:54:53 +00001704 // Lex the token after the identifier.
1705 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001706
Chris Lattnerf64b3522008-03-09 01:54:53 +00001707 switch (Tok.getKind()) {
1708 default: // #define X(A B
1709 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1710 return true;
1711 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001712 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001713 return false;
1714 case tok::comma: // #define X(A,
1715 break;
1716 case tok::ellipsis: // #define X(A... -> GCC extension
1717 // Diagnose extension.
1718 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001719
Chris Lattnerf64b3522008-03-09 01:54:53 +00001720 // Lex the token after the identifier.
1721 LexUnexpandedToken(Tok);
1722 if (Tok.isNot(tok::r_paren)) {
1723 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1724 return true;
1725 }
Mike Stump11289f42009-09-09 15:08:12 +00001726
Chris Lattnerf64b3522008-03-09 01:54:53 +00001727 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001728 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001729 return false;
1730 }
1731 }
1732 }
1733}
1734
James Dennettf6333ac2012-06-22 05:46:07 +00001735/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001736/// line then lets the caller lex the next real token.
1737void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1738 ++NumDefined;
1739
1740 Token MacroNameTok;
1741 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001742
Chris Lattnerf64b3522008-03-09 01:54:53 +00001743 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001744 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001745 return;
1746
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001747 Token LastTok = MacroNameTok;
1748
Chris Lattnerf64b3522008-03-09 01:54:53 +00001749 // If we are supposed to keep comments in #defines, reenable comment saving
1750 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001751 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001752
Chris Lattnerf64b3522008-03-09 01:54:53 +00001753 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001754 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001755
Chris Lattnerf64b3522008-03-09 01:54:53 +00001756 Token Tok;
1757 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001758
Chris Lattnerf64b3522008-03-09 01:54:53 +00001759 // If this is a function-like macro definition, parse the argument list,
1760 // marking each of the identifiers as being used as macro arguments. Also,
1761 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001762 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001763 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001764 } else if (Tok.hasLeadingSpace()) {
1765 // This is a normal token with leading space. Clear the leading space
1766 // marker on the first token to get proper expansion.
1767 Tok.clearFlag(Token::LeadingSpace);
1768 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001769 // This is a function-like macro definition. Read the argument list.
1770 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001771 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001772 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001773 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001774 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001775 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001776 DiscardUntilEndOfDirective();
1777 return;
1778 }
1779
Chris Lattner249c38b2009-04-19 18:26:34 +00001780 // If this is a definition of a variadic C99 function-like macro, not using
1781 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001782
Chris Lattner249c38b2009-04-19 18:26:34 +00001783 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1784 // This gets unpoisoned where it is allowed.
1785 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1786 if (MI->isC99Varargs())
1787 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001788
Chris Lattnerf64b3522008-03-09 01:54:53 +00001789 // Read the first token after the arg list for down below.
1790 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001791 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001792 // C99 requires whitespace between the macro definition and the body. Emit
1793 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001794 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001795 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001796 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1797 // first character of a replacement list is not a character required by
1798 // subclause 5.2.1, then there shall be white-space separation between the
1799 // identifier and the replacement list.". 5.2.1 lists this set:
1800 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1801 // is irrelevant here.
1802 bool isInvalid = false;
1803 if (Tok.is(tok::at)) // @ is not in the list above.
1804 isInvalid = true;
1805 else if (Tok.is(tok::unknown)) {
1806 // If we have an unknown token, it is something strange like "`". Since
1807 // all of valid characters would have lexed into a single character
1808 // token of some sort, we know this is not a valid case.
1809 isInvalid = true;
1810 }
1811 if (isInvalid)
1812 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1813 else
1814 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001815 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001816
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001817 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001818 LastTok = Tok;
1819
Chris Lattnerf64b3522008-03-09 01:54:53 +00001820 // Read the rest of the macro body.
1821 if (MI->isObjectLike()) {
1822 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001823 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001824 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001825 MI->AddTokenToBody(Tok);
1826 // Get the next token of the macro.
1827 LexUnexpandedToken(Tok);
1828 }
Mike Stump11289f42009-09-09 15:08:12 +00001829
Chris Lattnerf64b3522008-03-09 01:54:53 +00001830 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001831 // Otherwise, read the body of a function-like macro. While we are at it,
1832 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1833 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001834 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001835 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001836
Eli Friedman14d3c792012-11-14 02:18:46 +00001837 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001838 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001839
Chris Lattnerf64b3522008-03-09 01:54:53 +00001840 // Get the next token of the macro.
1841 LexUnexpandedToken(Tok);
1842 continue;
1843 }
Mike Stump11289f42009-09-09 15:08:12 +00001844
Eli Friedman14d3c792012-11-14 02:18:46 +00001845 if (Tok.is(tok::hashhash)) {
1846
1847 // If we see token pasting, check if it looks like the gcc comma
1848 // pasting extension. We'll use this information to suppress
1849 // diagnostics later on.
1850
1851 // Get the next token of the macro.
1852 LexUnexpandedToken(Tok);
1853
1854 if (Tok.is(tok::eod)) {
1855 MI->AddTokenToBody(LastTok);
1856 break;
1857 }
1858
1859 unsigned NumTokens = MI->getNumTokens();
1860 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
1861 MI->getReplacementToken(NumTokens-1).is(tok::comma))
1862 MI->setHasCommaPasting();
1863
1864 // Things look ok, add the '##' and param name tokens to the macro.
1865 MI->AddTokenToBody(LastTok);
1866 MI->AddTokenToBody(Tok);
1867 LastTok = Tok;
1868
1869 // Get the next token of the macro.
1870 LexUnexpandedToken(Tok);
1871 continue;
1872 }
1873
Chris Lattnerf64b3522008-03-09 01:54:53 +00001874 // Get the next token of the macro.
1875 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001876
Chris Lattner83bd8282009-05-25 17:16:10 +00001877 // Check for a valid macro arg identifier.
1878 if (Tok.getIdentifierInfo() == 0 ||
1879 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1880
1881 // If this is assembler-with-cpp mode, we accept random gibberish after
1882 // the '#' because '#' is often a comment character. However, change
1883 // the kind of the token to tok::unknown so that the preprocessor isn't
1884 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001885 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001886 LastTok.setKind(tok::unknown);
1887 } else {
1888 Diag(Tok, diag::err_pp_stringize_not_parameter);
1889 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001890
Chris Lattner83bd8282009-05-25 17:16:10 +00001891 // Disable __VA_ARGS__ again.
1892 Ident__VA_ARGS__->setIsPoisoned(true);
1893 return;
1894 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001895 }
Mike Stump11289f42009-09-09 15:08:12 +00001896
Chris Lattner83bd8282009-05-25 17:16:10 +00001897 // Things look ok, add the '#' and param name tokens to the macro.
1898 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001899 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001900 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001901
Chris Lattnerf64b3522008-03-09 01:54:53 +00001902 // Get the next token of the macro.
1903 LexUnexpandedToken(Tok);
1904 }
1905 }
Mike Stump11289f42009-09-09 15:08:12 +00001906
1907
Chris Lattnerf64b3522008-03-09 01:54:53 +00001908 // Disable __VA_ARGS__ again.
1909 Ident__VA_ARGS__->setIsPoisoned(true);
1910
Chris Lattner57540c52011-04-15 05:22:18 +00001911 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001912 // replacement list.
1913 unsigned NumTokens = MI->getNumTokens();
1914 if (NumTokens != 0) {
1915 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1916 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001917 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001918 return;
1919 }
1920 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1921 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001922 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001923 return;
1924 }
1925 }
Mike Stump11289f42009-09-09 15:08:12 +00001926
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001927 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001928
Chris Lattnerf64b3522008-03-09 01:54:53 +00001929 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00001930 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001931 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001932 // It is very common for system headers to have tons of macro redefinitions
1933 // and for warnings to be disabled in system headers. If this is the case,
1934 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001935 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001936 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001937 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001938 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001939
Richard Smith7b242542013-03-06 00:46:00 +00001940 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
1941 // C++ [cpp.predefined]p4, but allow it as an extension.
1942 if (OtherMI->isBuiltinMacro())
1943 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001944 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001945 // separation must be the same. C99 6.10.3.2.
Richard Smith7b242542013-03-06 00:46:00 +00001946 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
1947 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001948 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1949 << MacroNameTok.getIdentifierInfo();
1950 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1951 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001952 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001953 if (OtherMI->isWarnIfUnused())
1954 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001955 }
Mike Stump11289f42009-09-09 15:08:12 +00001956
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00001957 MacroDirective *MD = setMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001958
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001959 assert(!MI->isUsed());
1960 // If we need warning for not using the macro, add its location in the
1961 // warn-because-unused-macro set. If it gets used it will be removed from set.
1962 if (isInPrimaryFile() && // don't warn for include'd macros.
1963 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00001964 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001965 MI->setIsWarnIfUnused(true);
1966 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1967 }
1968
Chris Lattner928e9092009-04-12 01:39:54 +00001969 // If the callbacks want to know, tell them about the macro definition.
1970 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00001971 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001972}
1973
James Dennettf6333ac2012-06-22 05:46:07 +00001974/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001975///
1976void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1977 ++NumUndefined;
1978
1979 Token MacroNameTok;
1980 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001981
Chris Lattnerf64b3522008-03-09 01:54:53 +00001982 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001983 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001984 return;
Mike Stump11289f42009-09-09 15:08:12 +00001985
Chris Lattnerf64b3522008-03-09 01:54:53 +00001986 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001987 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001988
Chris Lattnerf64b3522008-03-09 01:54:53 +00001989 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001990 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
1991 const MacroInfo *MI = MD ? MD->getInfo() : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001992
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00001993 // If the callbacks want to know, tell them about the macro #undef.
1994 // Note: no matter if the macro was defined or not.
1995 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00001996 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00001997
Chris Lattnerf64b3522008-03-09 01:54:53 +00001998 // If the macro is not defined, this is a noop undef, just return.
1999 if (MI == 0) return;
2000
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002001 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002002 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002003
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002004 if (MI->isWarnIfUnused())
2005 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2006
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002007 UndefineMacro(MacroNameTok.getIdentifierInfo(), MD,
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002008 MacroNameTok.getLocation());
2009}
2010
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002011void Preprocessor::UndefineMacro(IdentifierInfo *II, MacroDirective *MD,
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002012 SourceLocation UndefLoc) {
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002013 MD->setUndefLoc(UndefLoc);
2014 if (MD->isImported()) {
2015 MD->setChangedAfterLoad();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002016 if (Listener)
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002017 Listener->UndefinedMacro(MD);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002018 }
2019
2020 clearMacroInfo(II);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002021}
2022
2023
2024//===----------------------------------------------------------------------===//
2025// Preprocessor Conditional Directive Handling.
2026//===----------------------------------------------------------------------===//
2027
James Dennettf6333ac2012-06-22 05:46:07 +00002028/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2029/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2030/// true if any tokens have been returned or pp-directives activated before this
2031/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002032///
2033void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2034 bool ReadAnyTokensBeforeDirective) {
2035 ++NumIf;
2036 Token DirectiveTok = Result;
2037
2038 Token MacroNameTok;
2039 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002040
Chris Lattnerf64b3522008-03-09 01:54:53 +00002041 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002042 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002043 // Skip code until we get to #endif. This helps with recovery by not
2044 // emitting an error when the #endif is reached.
2045 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2046 /*Foundnonskip*/false, /*FoundElse*/false);
2047 return;
2048 }
Mike Stump11289f42009-09-09 15:08:12 +00002049
Chris Lattnerf64b3522008-03-09 01:54:53 +00002050 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002051 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002052
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002053 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002054 MacroDirective *MD = getMacroDirective(MII);
2055 MacroInfo *MI = MD ? MD->getInfo() : 0;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002056
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002057 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002058 // If the start of a top-level #ifdef and if the macro is not defined,
2059 // inform MIOpt that this might be the start of a proper include guard.
2060 // Otherwise it is some other form of unknown conditional which we can't
2061 // handle.
2062 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002063 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002064 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002065 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002066 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002067 }
2068
Chris Lattnerf64b3522008-03-09 01:54:53 +00002069 // If there is a macro, process it.
2070 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002071 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002072
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002073 if (Callbacks) {
2074 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002075 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002076 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002077 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002078 }
2079
Chris Lattnerf64b3522008-03-09 01:54:53 +00002080 // Should we include the stuff contained by this directive?
2081 if (!MI == isIfndef) {
2082 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002083 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2084 /*wasskip*/false, /*foundnonskip*/true,
2085 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002086 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002087 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002088 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002089 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002090 /*FoundElse*/false);
2091 }
2092}
2093
James Dennettf6333ac2012-06-22 05:46:07 +00002094/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002095///
2096void Preprocessor::HandleIfDirective(Token &IfToken,
2097 bool ReadAnyTokensBeforeDirective) {
2098 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002099
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002100 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002101 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002102 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2103 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2104 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002105
2106 // If this condition is equivalent to #ifndef X, and if this is the first
2107 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002108 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002109 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002110 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00002111 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002112 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002113 }
2114
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002115 if (Callbacks)
2116 Callbacks->If(IfToken.getLocation(),
2117 SourceRange(ConditionalBegin, ConditionalEnd));
2118
Chris Lattnerf64b3522008-03-09 01:54:53 +00002119 // Should we include the stuff contained by this directive?
2120 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002121 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002122 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002123 /*foundnonskip*/true, /*foundelse*/false);
2124 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002125 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002126 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002127 /*FoundElse*/false);
2128 }
2129}
2130
James Dennettf6333ac2012-06-22 05:46:07 +00002131/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002132///
2133void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2134 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002135
Chris Lattnerf64b3522008-03-09 01:54:53 +00002136 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002137 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002138
Chris Lattnerf64b3522008-03-09 01:54:53 +00002139 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002140 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002141 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002142 Diag(EndifToken, diag::err_pp_endif_without_if);
2143 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145
Chris Lattnerf64b3522008-03-09 01:54:53 +00002146 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002147 if (CurPPLexer->getConditionalStackDepth() == 0)
2148 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002149
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002150 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002151 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002152
2153 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002154 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002155}
2156
James Dennettf6333ac2012-06-22 05:46:07 +00002157/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002158///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002159void Preprocessor::HandleElseDirective(Token &Result) {
2160 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002161
Chris Lattnerf64b3522008-03-09 01:54:53 +00002162 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002163 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002164
Chris Lattnerf64b3522008-03-09 01:54:53 +00002165 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002166 if (CurPPLexer->popConditionalLevel(CI)) {
2167 Diag(Result, diag::pp_err_else_without_if);
2168 return;
2169 }
Mike Stump11289f42009-09-09 15:08:12 +00002170
Chris Lattnerf64b3522008-03-09 01:54:53 +00002171 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002172 if (CurPPLexer->getConditionalStackDepth() == 0)
2173 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002174
2175 // If this is a #else with a #else before it, report the error.
2176 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002177
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002178 if (Callbacks)
2179 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2180
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002181 // Finally, skip the rest of the contents of this block.
2182 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002183 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002184}
2185
James Dennettf6333ac2012-06-22 05:46:07 +00002186/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002187///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002188void Preprocessor::HandleElifDirective(Token &ElifToken) {
2189 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002190
Chris Lattnerf64b3522008-03-09 01:54:53 +00002191 // #elif directive in a non-skipping conditional... start skipping.
2192 // We don't care what the condition is, because we will always skip it (since
2193 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002194 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002195 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002196 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002197
2198 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002199 if (CurPPLexer->popConditionalLevel(CI)) {
2200 Diag(ElifToken, diag::pp_err_elif_without_if);
2201 return;
2202 }
Mike Stump11289f42009-09-09 15:08:12 +00002203
Chris Lattnerf64b3522008-03-09 01:54:53 +00002204 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002205 if (CurPPLexer->getConditionalStackDepth() == 0)
2206 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002207
Chris Lattnerf64b3522008-03-09 01:54:53 +00002208 // If this is a #elif with a #else before it, report the error.
2209 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002210
2211 if (Callbacks)
2212 Callbacks->Elif(ElifToken.getLocation(),
2213 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002214
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002215 // Finally, skip the rest of the contents of this block.
2216 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002217 /*FoundElse*/CI.FoundElse,
2218 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002219}