blob: 8f79796c58c9d3605e2826bd927a19202fbc458c [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//===----------------------------------------------------------------------===//
9//
10// This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor3a7ad252010-08-24 19:08:16 +000019#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor97eec242011-09-15 22:00:41 +000020#include "clang/Lex/ModuleLoader.h"
Douglas Gregorc7d65762010-09-09 22:45:38 +000021#include "clang/Lex/Pragma.h"
Chris Lattner710bb872009-11-30 04:18:44 +000022#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000023#include "clang/Basic/SourceManager.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000024#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000026using namespace clang;
27
28//===----------------------------------------------------------------------===//
29// Utility Methods for Preprocessor Directive Handling.
30//===----------------------------------------------------------------------===//
31
Chris Lattnerc0a585d2010-08-17 15:55:45 +000032MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000033 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000034
Ted Kremenekc8456f82010-10-19 22:15:20 +000035 if (MICache) {
36 MIChain = MICache;
37 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000038 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000039 else {
40 MIChain = BP.Allocate<MacroInfoChain>();
41 }
42
43 MIChain->Next = MIChainHead;
44 MIChain->Prev = 0;
45 if (MIChainHead)
46 MIChainHead->Prev = MIChain;
47 MIChainHead = MIChain;
48
49 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000050}
51
52MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
53 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000054 new (MI) MacroInfo(L);
55 return MI;
56}
57
Chris Lattnerc0a585d2010-08-17 15:55:45 +000058MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
59 MacroInfo *MI = AllocateMacroInfo();
60 new (MI) MacroInfo(MacroToClone, BP);
61 return MI;
62}
63
Chris Lattner666f7a42009-02-20 22:19:20 +000064/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
65/// be reused for allocating new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +000066void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +000067 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
68 if (MacroInfoChain *Prev = MIChain->Prev) {
69 MacroInfoChain *Next = MIChain->Next;
70 Prev->Next = Next;
71 if (Next)
72 Next->Prev = Prev;
73 }
74 else {
75 assert(MIChainHead == MIChain);
76 MIChainHead = MIChain->Next;
77 MIChainHead->Prev = 0;
78 }
79 MIChain->Next = MICache;
80 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +000081
Ted Kremenekc8456f82010-10-19 22:15:20 +000082 MI->Destroy();
83}
Chris Lattner666f7a42009-02-20 22:19:20 +000084
Chris Lattnerf64b3522008-03-09 01:54:53 +000085/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000086/// current line until the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000087void Preprocessor::DiscardUntilEndOfDirective() {
88 Token Tmp;
89 do {
90 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000091 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000092 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000093}
94
Chris Lattnerf64b3522008-03-09 01:54:53 +000095/// ReadMacroName - Lex and validate a macro name, which occurs after a
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000096/// #define or #undef. This sets the token kind to eod and discards the rest
Chris Lattnerf64b3522008-03-09 01:54:53 +000097/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
98/// this is due to a a #define, 2 if #undef directive, 0 if it is something
99/// else (e.g. #ifdef).
100void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
101 // Read the token, don't allow macro expansion on it.
102 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000103
Douglas Gregor12785102010-08-24 20:21:13 +0000104 if (MacroNameTok.is(tok::code_completion)) {
105 if (CodeComplete)
106 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000107 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000108 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000109 }
110
Chris Lattnerf64b3522008-03-09 01:54:53 +0000111 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000112 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000113 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
114 return;
115 }
Mike Stump11289f42009-09-09 15:08:12 +0000116
Chris Lattnerf64b3522008-03-09 01:54:53 +0000117 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
118 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000119 bool Invalid = false;
120 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
121 if (Invalid)
122 return;
Nico Weber2e686202012-02-29 22:54:43 +0000123
Chris Lattner77c76ae2008-12-13 20:12:40 +0000124 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000125
126 // Allow #defining |and| and friends in microsoft mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000127 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weber2e686202012-02-29 22:54:43 +0000128 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
129 return;
130 }
131
Chris Lattner77c76ae2008-12-13 20:12:40 +0000132 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000133 // C++ 2.5p2: Alternative tokens behave the same as its primary token
134 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000135 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000136 else
137 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
138 // Fall through on error.
139 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
140 // Error if defining "defined": C99 6.10.8.4.
141 Diag(MacroNameTok, diag::err_defined_macro_name);
142 } else if (isDefineUndef && II->hasMacroDefinition() &&
143 getMacroInfo(II)->isBuiltinMacro()) {
144 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
145 if (isDefineUndef == 1)
146 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
147 else
148 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
149 } else {
150 // Okay, we got a good identifier node. Return it.
151 return;
152 }
Mike Stump11289f42009-09-09 15:08:12 +0000153
Chris Lattnerf64b3522008-03-09 01:54:53 +0000154 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000155 // token kind to tok::eod.
156 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000157 return DiscardUntilEndOfDirective();
158}
159
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000160/// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
161/// not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000162/// true, then we consider macros that expand to zero tokens as being ok.
163void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000164 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000165 // Lex unexpanded tokens for most directives: macros might expand to zero
166 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
167 // #line) allow empty macros.
168 if (EnableMacros)
169 Lex(Tmp);
170 else
171 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000172
Chris Lattnerf64b3522008-03-09 01:54:53 +0000173 // There should be no tokens after the directive, but we allow them as an
174 // extension.
175 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
176 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000177
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000178 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000179 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000180 // or if this is a macro-style preprocessing directive, because it is more
181 // trouble than it is worth to insert /**/ and check that there is no /**/
182 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000183 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000184 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000185 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000186 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
187 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000188 DiscardUntilEndOfDirective();
189 }
190}
191
192
193
194/// SkipExcludedConditionalBlock - We just read a #if or related directive and
195/// decided that the subsequent tokens are in the #if'd out portion of the
196/// file. Lex the rest of the file, until we see an #endif. If
197/// FoundNonSkipPortion is true, then we have already emitted code for part of
198/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
199/// is true, then #else directives are ok, if not, then we have already seen one
200/// so a #else directive is a duplicate. When this returns, the caller can lex
201/// the first valid token.
202void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
203 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000204 bool FoundElse,
205 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000206 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000207 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000208
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000209 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000210 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000211
Ted Kremenek56572ab2008-12-12 18:34:08 +0000212 if (CurPTHLexer) {
213 PTHSkipExcludedConditionalBlock();
214 return;
215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattnerf64b3522008-03-09 01:54:53 +0000217 // Enter raw mode to disable identifier lookup (and thus macro expansion),
218 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000219 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000220 Token Tok;
221 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000222 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000223
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000224 if (Tok.is(tok::code_completion)) {
225 if (CodeComplete)
226 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000227 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000228 continue;
229 }
230
Chris Lattnerf64b3522008-03-09 01:54:53 +0000231 // If this is the end of the buffer, we have an error.
232 if (Tok.is(tok::eof)) {
233 // Emit errors for each unterminated conditional on the stack, including
234 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000235 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000236 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000237 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
238 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000239 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000240 }
241
Chris Lattnerf64b3522008-03-09 01:54:53 +0000242 // Just return and let the caller lex after this #include.
243 break;
244 }
Mike Stump11289f42009-09-09 15:08:12 +0000245
Chris Lattnerf64b3522008-03-09 01:54:53 +0000246 // If this token is not a preprocessor directive, just skip it.
247 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
248 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattnerf64b3522008-03-09 01:54:53 +0000250 // We just parsed a # character at the start of a line, so we're in
251 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000252 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000253 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000254 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000255
Mike Stump11289f42009-09-09 15:08:12 +0000256
Chris Lattnerf64b3522008-03-09 01:54:53 +0000257 // Read the next token, the directive flavor.
258 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000259
Chris Lattnerf64b3522008-03-09 01:54:53 +0000260 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
261 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000262 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000263 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000264 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000265 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000266 continue;
267 }
268
269 // If the first letter isn't i or e, it isn't intesting to us. We know that
270 // this is safe in the face of spelling differences, because there is no way
271 // to spell an i/e in a strange way that is another letter. Skipping this
272 // allows us to avoid looking up the identifier info for #define/#undef and
273 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000274 const char *RawCharData = Tok.getRawIdentifierData();
275
Chris Lattnerf64b3522008-03-09 01:54:53 +0000276 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000277 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000278 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000279 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000280 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000281 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000282 continue;
283 }
Mike Stump11289f42009-09-09 15:08:12 +0000284
Chris Lattnerf64b3522008-03-09 01:54:53 +0000285 // Get the identifier name without trigraphs or embedded newlines. Note
286 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
287 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000288 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000289 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000290 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000291 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000292 } else {
293 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000294 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000295 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000296 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000297 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000298 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000299 continue;
300 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000301 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000302 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000303 }
Mike Stump11289f42009-09-09 15:08:12 +0000304
Benjamin Kramer144884642009-12-31 13:32:38 +0000305 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000306 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000307 if (Sub.empty() || // "if"
308 Sub == "def" || // "ifdef"
309 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000310 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
311 // bother parsing the condition.
312 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000313 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000315 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000316 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000317 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000318 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000319 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000320 PPConditionalInfo CondInfo;
321 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000322 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000323 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000324 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattnerf64b3522008-03-09 01:54:53 +0000326 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000327 if (!CondInfo.WasSkipping) {
Richard Smithd0124572012-06-21 00:35:03 +0000328 CheckEndOfDirective("endif");
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000329 if (Callbacks)
330 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000331 break;
Richard Smithd0124572012-06-21 00:35:03 +0000332 } else {
333 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000334 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000335 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000336 // #else directive in a skipping conditional. If not in some other
337 // skipping conditional, and if #else hasn't already been seen, enter it
338 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000339 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000340
Chris Lattnerf64b3522008-03-09 01:54:53 +0000341 // If this is a #else with a #else before it, report the error.
342 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattnerf64b3522008-03-09 01:54:53 +0000344 // Note that we've seen a #else in this conditional.
345 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000346
Chris Lattnerf64b3522008-03-09 01:54:53 +0000347 // If the conditional is at the top level, and the #if block wasn't
348 // entered, enter the #else block now.
349 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
350 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000351 CheckEndOfDirective("else");
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000352 if (Callbacks)
353 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000354 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000355 } else {
356 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000357 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000358 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000359 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000360
361 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000362 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000363 // If this is in a skipping block or if we're already handled this #if
364 // block, don't bother parsing the condition.
365 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
366 DiscardUntilEndOfDirective();
367 ShouldEnter = false;
368 } else {
369 // Restore the value of LexingRawMode so that identifiers are
370 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000371 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
372 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000373 IdentifierInfo *IfNDefMacro = 0;
374 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000375 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000376 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000377 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000378
Chris Lattnerf64b3522008-03-09 01:54:53 +0000379 // If this is a #elif with a #else before it, report the error.
380 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Chris Lattnerf64b3522008-03-09 01:54:53 +0000382 // If this condition is true, enter it!
383 if (ShouldEnter) {
384 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000385 if (Callbacks)
386 Callbacks->Elif(Tok.getLocation(),
387 SourceRange(ConditionalBegin, ConditionalEnd),
388 CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000389 break;
390 }
391 }
392 }
Mike Stump11289f42009-09-09 15:08:12 +0000393
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000394 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000395 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000396 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000397 }
398
399 // Finally, if we are out of the conditional (saw an #endif or ran off the end
400 // of the file, just stop skipping and return to lexing whatever came after
401 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000402 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000403
404 if (Callbacks) {
405 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
406 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
407 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000408}
409
Ted Kremenek56572ab2008-12-12 18:34:08 +0000410void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000411
412 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000413 assert(CurPTHLexer);
414 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000415
Ted Kremenek56572ab2008-12-12 18:34:08 +0000416 // Skip to the next '#else', '#elif', or #endif.
417 if (CurPTHLexer->SkipBlock()) {
418 // We have reached an #endif. Both the '#' and 'endif' tokens
419 // have been consumed by the PTHLexer. Just pop off the condition level.
420 PPConditionalInfo CondInfo;
421 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000422 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000423 assert(!InCond && "Can't be skipping if not in a conditional!");
424 break;
425 }
Mike Stump11289f42009-09-09 15:08:12 +0000426
Ted Kremenek56572ab2008-12-12 18:34:08 +0000427 // We have reached a '#else' or '#elif'. Lex the next token to get
428 // the directive flavor.
429 Token Tok;
430 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000431
Ted Kremenek56572ab2008-12-12 18:34:08 +0000432 // We can actually look up the IdentifierInfo here since we aren't in
433 // raw mode.
434 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
435
436 if (K == tok::pp_else) {
437 // #else: Enter the else condition. We aren't in a nested condition
438 // since we skip those. We're always in the one matching the last
439 // blocked we skipped.
440 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
441 // Note that we've seen a #else in this conditional.
442 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000443
Ted Kremenek56572ab2008-12-12 18:34:08 +0000444 // If the #if block wasn't entered then enter the #else block now.
445 if (!CondInfo.FoundNonSkip) {
446 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000447
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000448 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000449 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000450 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000451 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000452
Ted Kremenek56572ab2008-12-12 18:34:08 +0000453 break;
454 }
Mike Stump11289f42009-09-09 15:08:12 +0000455
Ted Kremenek56572ab2008-12-12 18:34:08 +0000456 // Otherwise skip this block.
457 continue;
458 }
Mike Stump11289f42009-09-09 15:08:12 +0000459
Ted Kremenek56572ab2008-12-12 18:34:08 +0000460 assert(K == tok::pp_elif);
461 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
462
463 // If this is a #elif with a #else before it, report the error.
464 if (CondInfo.FoundElse)
465 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000466
Ted Kremenek56572ab2008-12-12 18:34:08 +0000467 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000468 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000469 if (CondInfo.FoundNonSkip)
470 continue;
471
472 // Evaluate the condition of the #elif.
473 IdentifierInfo *IfNDefMacro = 0;
474 CurPTHLexer->ParsingPreprocessorDirective = true;
475 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
476 CurPTHLexer->ParsingPreprocessorDirective = false;
477
478 // If this condition is true, enter it!
479 if (ShouldEnter) {
480 CondInfo.FoundNonSkip = true;
481 break;
482 }
483
484 // Otherwise, skip this block and go to the next one.
485 continue;
486 }
487}
488
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000489/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
490/// return null on failure. isAngled indicates whether the file reference is
491/// for system #include's or not (i.e. using <> instead of "").
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000492const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000493 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000494 bool isAngled,
495 const DirectoryLookup *FromDir,
496 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000497 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000498 SmallVectorImpl<char> *RelativePath,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000499 Module **SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000500 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000501 // If the header lookup mechanism may be relative to the current file, pass in
502 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000503 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000504 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000505 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000506 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000507
Chris Lattner022923a2009-02-04 19:45:07 +0000508 // If there is no file entry associated with this file, it must be the
509 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000510 // it won't be scanned for preprocessor directives. If we have the
511 // predefines buffer, resolve #include references (which come from the
512 // -include command line argument) as if they came from the main file, this
513 // affects file lookup etc.
514 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000515 FID = SourceMgr.getMainFileID();
516 CurFileEnt = SourceMgr.getFileEntryForID(FID);
517 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000518 }
Mike Stump11289f42009-09-09 15:08:12 +0000519
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000520 // Do a standard file entry lookup.
521 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000522 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000523 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000524 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerfde85352010-01-22 00:14:44 +0000525 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000527 // Otherwise, see if this is a subframework header. If so, this is relative
528 // to one of the headers on the #include stack. Walk the list of the current
529 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregor97eec242011-09-15 22:00:41 +0000530 // FIXME: SuggestedModule!
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000531 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000532 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000533 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000534 SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000535 return FE;
536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000538 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
539 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000540 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000541 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000542 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000543 if ((FE = HeaderInfo.LookupSubframeworkHeader(
544 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000545 return FE;
546 }
547 }
Mike Stump11289f42009-09-09 15:08:12 +0000548
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000549 // Otherwise, we really couldn't find the file.
550 return 0;
551}
552
Chris Lattnerf64b3522008-03-09 01:54:53 +0000553
554//===----------------------------------------------------------------------===//
555// Preprocessor Directive Handling.
556//===----------------------------------------------------------------------===//
557
David Blaikied5321242012-06-06 18:52:13 +0000558class Preprocessor::ResetMacroExpansionHelper {
559public:
560 ResetMacroExpansionHelper(Preprocessor *pp)
561 : PP(pp), save(pp->DisableMacroExpansion) {
562 if (pp->MacroExpansionInDirectivesOverride)
563 pp->DisableMacroExpansion = false;
564 }
565 ~ResetMacroExpansionHelper() {
566 PP->DisableMacroExpansion = save;
567 }
568private:
569 Preprocessor *PP;
570 bool save;
571};
572
Chris Lattnerf64b3522008-03-09 01:54:53 +0000573/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000574/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000575/// lexer/preprocessor state, and advances the lexer(s) so that the next token
576/// read is the correct one.
577void Preprocessor::HandleDirective(Token &Result) {
578 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000579
Chris Lattnerf64b3522008-03-09 01:54:53 +0000580 // We just parsed a # character at the start of a line, so we're in directive
581 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000582 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000583 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000584
Chris Lattnerf64b3522008-03-09 01:54:53 +0000585 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000586
Chris Lattnerf64b3522008-03-09 01:54:53 +0000587 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000588 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000589 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000590 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000591
Chris Lattner2d17ab72009-03-18 21:00:25 +0000592 // Save the '#' token in case we need to return it later.
593 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000594
Chris Lattnerf64b3522008-03-09 01:54:53 +0000595 // Read the next token, the directive flavor. This isn't expanded due to
596 // C99 6.10.3p8.
597 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000598
Chris Lattnerf64b3522008-03-09 01:54:53 +0000599 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
600 // #define A(x) #x
601 // A(abc
602 // #warning blah
603 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000604 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
605 // not support this for #include-like directives, since that can result in
606 // terrible diagnostics, and does not work in GCC.
607 if (InMacroArgs) {
608 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
609 switch (II->getPPKeywordID()) {
610 case tok::pp_include:
611 case tok::pp_import:
612 case tok::pp_include_next:
613 case tok::pp___include_macros:
614 Diag(Result, diag::err_embedded_include) << II->getName();
615 DiscardUntilEndOfDirective();
616 return;
617 default:
618 break;
619 }
620 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000621 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000622 }
Mike Stump11289f42009-09-09 15:08:12 +0000623
David Blaikied5321242012-06-06 18:52:13 +0000624 // Temporarily enable macro expansion if set so
625 // and reset to previous state when returning from this function.
626 ResetMacroExpansionHelper helper(this);
627
Chris Lattnerf64b3522008-03-09 01:54:53 +0000628TryAgain:
629 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000630 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000631 return; // null directive.
632 case tok::comment:
633 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
634 LexUnexpandedToken(Result);
635 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000636 case tok::code_completion:
637 if (CodeComplete)
638 CodeComplete->CodeCompleteDirective(
639 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000640 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000641 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000642 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000643 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000644 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000645 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000646 default:
647 IdentifierInfo *II = Result.getIdentifierInfo();
648 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000649
Chris Lattnerf64b3522008-03-09 01:54:53 +0000650 // Ask what the preprocessor keyword ID is.
651 switch (II->getPPKeywordID()) {
652 default: break;
653 // C99 6.10.1 - Conditional Inclusion.
654 case tok::pp_if:
655 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
656 case tok::pp_ifdef:
657 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
658 case tok::pp_ifndef:
659 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
660 case tok::pp_elif:
661 return HandleElifDirective(Result);
662 case tok::pp_else:
663 return HandleElseDirective(Result);
664 case tok::pp_endif:
665 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattnerf64b3522008-03-09 01:54:53 +0000667 // C99 6.10.2 - Source File Inclusion.
668 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000669 // Handle #include.
670 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000671 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000672 // Handle -imacros.
673 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000674
Chris Lattnerf64b3522008-03-09 01:54:53 +0000675 // C99 6.10.3 - Macro Replacement.
676 case tok::pp_define:
677 return HandleDefineDirective(Result);
678 case tok::pp_undef:
679 return HandleUndefDirective(Result);
680
681 // C99 6.10.4 - Line Control.
682 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000683 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000684
Chris Lattnerf64b3522008-03-09 01:54:53 +0000685 // C99 6.10.5 - Error Directive.
686 case tok::pp_error:
687 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000688
Chris Lattnerf64b3522008-03-09 01:54:53 +0000689 // C99 6.10.6 - Pragma Directive.
690 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000691 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000692
Chris Lattnerf64b3522008-03-09 01:54:53 +0000693 // GNU Extensions.
694 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000695 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000696 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000697 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000698
Chris Lattnerf64b3522008-03-09 01:54:53 +0000699 case tok::pp_warning:
700 Diag(Result, diag::ext_pp_warning_directive);
701 return HandleUserDiagnosticDirective(Result, true);
702 case tok::pp_ident:
703 return HandleIdentSCCSDirective(Result);
704 case tok::pp_sccs:
705 return HandleIdentSCCSDirective(Result);
706 case tok::pp_assert:
707 //isExtension = true; // FIXME: implement #assert
708 break;
709 case tok::pp_unassert:
710 //isExtension = true; // FIXME: implement #unassert
711 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000712
Douglas Gregor663b48f2012-01-03 19:48:16 +0000713 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000714 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000715 return HandleMacroPublicDirective(Result);
716 break;
717
Douglas Gregor663b48f2012-01-03 19:48:16 +0000718 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000719 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000720 return HandleMacroPrivateDirective(Result);
721 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000722 }
723 break;
724 }
Mike Stump11289f42009-09-09 15:08:12 +0000725
Chris Lattner2d17ab72009-03-18 21:00:25 +0000726 // If this is a .S file, treat unknown # directives as non-preprocessor
727 // directives. This is important because # may be a comment or introduce
728 // various pseudo-ops. Just return the # token and push back the following
729 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000730 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000731 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000732 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000733 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000734 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000735
736 // If the second token is a hashhash token, then we need to translate it to
737 // unknown so the token lexer doesn't try to perform token pasting.
738 if (Result.is(tok::hashhash))
739 Toks[1].setKind(tok::unknown);
740
Chris Lattner2d17ab72009-03-18 21:00:25 +0000741 // Enter this token stream so that we re-lex the tokens. Make sure to
742 // enable macro expansion, in case the token after the # is an identifier
743 // that is expanded.
744 EnterTokenStream(Toks, 2, false, true);
745 return;
746 }
Mike Stump11289f42009-09-09 15:08:12 +0000747
Chris Lattnerf64b3522008-03-09 01:54:53 +0000748 // If we reached here, the preprocessing token is not valid!
749 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000750
Chris Lattnerf64b3522008-03-09 01:54:53 +0000751 // Read the rest of the PP line.
752 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000753
Chris Lattnerf64b3522008-03-09 01:54:53 +0000754 // Okay, we're done parsing the directive.
755}
756
Chris Lattner76e68962009-01-26 06:19:46 +0000757/// GetLineValue - Convert a numeric token into an unsigned value, emitting
758/// Diagnostic DiagID if it is invalid, and returning the value in Val.
759static bool GetLineValue(Token &DigitTok, unsigned &Val,
760 unsigned DiagID, Preprocessor &PP) {
761 if (DigitTok.isNot(tok::numeric_constant)) {
762 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000763
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000764 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000765 PP.DiscardUntilEndOfDirective();
766 return true;
767 }
Mike Stump11289f42009-09-09 15:08:12 +0000768
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000769 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000770 IntegerBuffer.resize(DigitTok.getLength());
771 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000772 bool Invalid = false;
773 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
774 if (Invalid)
775 return true;
776
Chris Lattnerd66f1722009-04-18 18:35:15 +0000777 // Verify that we have a simple digit-sequence, and compute the value. This
778 // is always a simple digit string computed in decimal, so we do this manually
779 // here.
780 Val = 0;
781 for (unsigned i = 0; i != ActualLength; ++i) {
782 if (!isdigit(DigitTokBegin[i])) {
783 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
784 diag::err_pp_line_digit_sequence);
785 PP.DiscardUntilEndOfDirective();
786 return true;
787 }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Chris Lattnerd66f1722009-04-18 18:35:15 +0000789 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
790 if (NextVal < Val) { // overflow.
791 PP.Diag(DigitTok, DiagID);
792 PP.DiscardUntilEndOfDirective();
793 return true;
794 }
795 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000796 }
Mike Stump11289f42009-09-09 15:08:12 +0000797
798 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000799 if (Val == 0) {
800 PP.Diag(DigitTok, DiagID);
801 PP.DiscardUntilEndOfDirective();
802 return true;
803 }
Mike Stump11289f42009-09-09 15:08:12 +0000804
Chris Lattnerd66f1722009-04-18 18:35:15 +0000805 if (DigitTokBegin[0] == '0')
806 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000807
Chris Lattner76e68962009-01-26 06:19:46 +0000808 return false;
809}
810
Mike Stump11289f42009-09-09 15:08:12 +0000811/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner100c65e2009-01-26 05:29:08 +0000812/// acceptable forms are:
813/// # line digit-sequence
814/// # line digit-sequence "s-char-sequence"
815void Preprocessor::HandleLineDirective(Token &Tok) {
816 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
817 // expanded.
818 Token DigitTok;
819 Lex(DigitTok);
820
Chris Lattner100c65e2009-01-26 05:29:08 +0000821 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000822 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000823 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000824 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000825
Chris Lattner76e68962009-01-26 06:19:46 +0000826 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
827 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000828 unsigned LineLimit = 32768U;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000829 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
Eli Friedman192e0342011-10-10 23:35:28 +0000830 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000831 if (LineNo >= LineLimit)
832 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000833 else if (LangOpts.CPlusPlus0x && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000834 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000836 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000837 Token StrTok;
838 Lex(StrTok);
839
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000840 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
841 // string followed by eod.
842 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000843 ; // ok
844 else if (StrTok.isNot(tok::string_literal)) {
845 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000846 return DiscardUntilEndOfDirective();
847 } else if (StrTok.hasUDSuffix()) {
848 Diag(StrTok, diag::err_invalid_string_udl);
849 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000850 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000851 // Parse and validate the string, converting it into a unique ID.
852 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000853 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000854 if (Literal.hadError)
855 return DiscardUntilEndOfDirective();
856 if (Literal.Pascal) {
857 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
858 return DiscardUntilEndOfDirective();
859 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000860 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000861
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000862 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000863 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
864 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000865 }
Mike Stump11289f42009-09-09 15:08:12 +0000866
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000867 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000868
Chris Lattner839150e2009-03-27 17:13:49 +0000869 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000870 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
871 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000872 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000873}
874
Chris Lattner76e68962009-01-26 06:19:46 +0000875/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
876/// marker directive.
877static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
878 bool &IsSystemHeader, bool &IsExternCHeader,
879 Preprocessor &PP) {
880 unsigned FlagVal;
881 Token FlagTok;
882 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000883 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000884 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
885 return true;
886
887 if (FlagVal == 1) {
888 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000889
Chris Lattner76e68962009-01-26 06:19:46 +0000890 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000891 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000892 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
893 return true;
894 } else if (FlagVal == 2) {
895 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000896
Chris Lattner1c967782009-02-04 06:25:26 +0000897 SourceManager &SM = PP.getSourceManager();
898 // If we are leaving the current presumed file, check to make sure the
899 // presumed include stack isn't empty!
900 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000901 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000902 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000903 if (PLoc.isInvalid())
904 return true;
905
Chris Lattner1c967782009-02-04 06:25:26 +0000906 // If there is no include loc (main file) or if the include loc is in a
907 // different physical file, then we aren't in a "1" line marker flag region.
908 SourceLocation IncLoc = PLoc.getIncludeLoc();
909 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000910 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000911 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
912 PP.DiscardUntilEndOfDirective();
913 return true;
914 }
Mike Stump11289f42009-09-09 15:08:12 +0000915
Chris Lattner76e68962009-01-26 06:19:46 +0000916 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000917 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000918 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
919 return true;
920 }
921
922 // We must have 3 if there are still flags.
923 if (FlagVal != 3) {
924 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000925 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000926 return true;
927 }
Mike Stump11289f42009-09-09 15:08:12 +0000928
Chris Lattner76e68962009-01-26 06:19:46 +0000929 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000930
Chris Lattner76e68962009-01-26 06:19:46 +0000931 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000932 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000933 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000934 return true;
935
936 // We must have 4 if there is yet another flag.
937 if (FlagVal != 4) {
938 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000939 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000940 return true;
941 }
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattner76e68962009-01-26 06:19:46 +0000943 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000944
Chris Lattner76e68962009-01-26 06:19:46 +0000945 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000946 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000947
948 // There are no more valid flags here.
949 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000950 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000951 return true;
952}
953
954/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
955/// one of the following forms:
956///
957/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000958/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000959/// # 42 "file" ('1' | '2')? '3' '4'?
960///
961void Preprocessor::HandleDigitDirective(Token &DigitTok) {
962 // Validate the number and convert it to an unsigned. GNU does not have a
963 // line # limit other than it fit in 32-bits.
964 unsigned LineNo;
965 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
966 *this))
967 return;
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattner76e68962009-01-26 06:19:46 +0000969 Token StrTok;
970 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000971
Chris Lattner76e68962009-01-26 06:19:46 +0000972 bool IsFileEntry = false, IsFileExit = false;
973 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000974 int FilenameID = -1;
975
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000976 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
977 // string followed by eod.
978 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000979 ; // ok
980 else if (StrTok.isNot(tok::string_literal)) {
981 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000982 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +0000983 } else if (StrTok.hasUDSuffix()) {
984 Diag(StrTok, diag::err_invalid_string_udl);
985 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000986 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000987 // Parse and validate the string, converting it into a unique ID.
988 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000989 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000990 if (Literal.hadError)
991 return DiscardUntilEndOfDirective();
992 if (Literal.Pascal) {
993 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
994 return DiscardUntilEndOfDirective();
995 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000996 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000997
Chris Lattner76e68962009-01-26 06:19:46 +0000998 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +0000999 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001000 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001001 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001002 }
Mike Stump11289f42009-09-09 15:08:12 +00001003
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001004 // Create a line note with this information.
1005 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001006 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001007 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001008
Chris Lattner839150e2009-03-27 17:13:49 +00001009 // If the preprocessor has callbacks installed, notify them of the #line
1010 // change. This is used so that the line marker comes out in -E mode for
1011 // example.
1012 if (Callbacks) {
1013 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1014 if (IsFileEntry)
1015 Reason = PPCallbacks::EnterFile;
1016 else if (IsFileExit)
1017 Reason = PPCallbacks::ExitFile;
1018 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1019 if (IsExternCHeader)
1020 FileKind = SrcMgr::C_ExternCSystem;
1021 else if (IsSystemHeader)
1022 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001023
Chris Lattnerc745cec2010-04-14 04:28:50 +00001024 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001025 }
Chris Lattner76e68962009-01-26 06:19:46 +00001026}
1027
1028
Chris Lattner38d7fd22009-01-26 05:30:54 +00001029/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1030///
Mike Stump11289f42009-09-09 15:08:12 +00001031void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001032 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001033 // PTH doesn't emit #warning or #error directives.
1034 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001035 return CurPTHLexer->DiscardToEndOfLine();
1036
Chris Lattnerf64b3522008-03-09 01:54:53 +00001037 // Read the rest of the line raw. We do this because we don't want macros
1038 // to be expanded and we don't require that the tokens be valid preprocessing
1039 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1040 // collapse multiple consequtive white space between tokens, but this isn't
1041 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001042 SmallString<128> Message;
1043 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001044
1045 // Find the first non-whitespace character, so that we can make the
1046 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001047 StringRef Msg = Message.str().ltrim(" ");
1048
Chris Lattner100c65e2009-01-26 05:29:08 +00001049 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001050 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001051 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001052 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001053}
1054
1055/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1056///
1057void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1058 // Yes, this directive is an extension.
1059 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001060
Chris Lattnerf64b3522008-03-09 01:54:53 +00001061 // Read the string argument.
1062 Token StrTok;
1063 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001064
Chris Lattnerf64b3522008-03-09 01:54:53 +00001065 // If the token kind isn't a string, it's a malformed directive.
1066 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001067 StrTok.isNot(tok::wide_string_literal)) {
1068 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001069 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001070 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001071 return;
1072 }
Mike Stump11289f42009-09-09 15:08:12 +00001073
Richard Smithd67aea22012-03-06 03:21:47 +00001074 if (StrTok.hasUDSuffix()) {
1075 Diag(StrTok, diag::err_invalid_string_udl);
1076 return DiscardUntilEndOfDirective();
1077 }
1078
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001079 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001080 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001081
Douglas Gregordc970f02010-03-16 22:30:13 +00001082 if (Callbacks) {
1083 bool Invalid = false;
1084 std::string Str = getSpelling(StrTok, &Invalid);
1085 if (!Invalid)
1086 Callbacks->Ident(Tok.getLocation(), Str);
1087 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001088}
1089
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001090/// \brief Handle a #public directive.
1091void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001092 Token MacroNameTok;
1093 ReadMacroName(MacroNameTok, 2);
1094
1095 // Error reading macro name? If so, diagnostic already issued.
1096 if (MacroNameTok.is(tok::eod))
1097 return;
1098
Douglas Gregor663b48f2012-01-03 19:48:16 +00001099 // Check to see if this is the last token on the #__public_macro line.
1100 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001101
1102 // Okay, we finally have a valid identifier to undef.
1103 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1104
1105 // If the macro is not defined, this is an error.
1106 if (MI == 0) {
Douglas Gregorebf00492011-10-17 15:32:29 +00001107 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001108 << MacroNameTok.getIdentifierInfo();
1109 return;
1110 }
1111
1112 // Note that this macro has now been exported.
Douglas Gregorebf00492011-10-17 15:32:29 +00001113 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1114
1115 // If this macro definition came from a PCH file, mark it
1116 // as having changed since serialization.
1117 if (MI->isFromAST())
1118 MI->setChangedAfterLoad();
1119}
1120
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001121/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001122void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1123 Token MacroNameTok;
1124 ReadMacroName(MacroNameTok, 2);
1125
1126 // Error reading macro name? If so, diagnostic already issued.
1127 if (MacroNameTok.is(tok::eod))
1128 return;
1129
Douglas Gregor663b48f2012-01-03 19:48:16 +00001130 // Check to see if this is the last token on the #__private_macro line.
1131 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001132
1133 // Okay, we finally have a valid identifier to undef.
1134 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1135
1136 // If the macro is not defined, this is an error.
1137 if (MI == 0) {
1138 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1139 << MacroNameTok.getIdentifierInfo();
1140 return;
1141 }
1142
1143 // Note that this macro has now been marked private.
1144 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001145
1146 // If this macro definition came from a PCH file, mark it
1147 // as having changed since serialization.
1148 if (MI->isFromAST())
1149 MI->setChangedAfterLoad();
1150}
1151
Chris Lattnerf64b3522008-03-09 01:54:53 +00001152//===----------------------------------------------------------------------===//
1153// Preprocessor Include Directive Handling.
1154//===----------------------------------------------------------------------===//
1155
1156/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1157/// checked and spelled filename, e.g. as an operand of #include. This returns
1158/// true if the input filename was in <>'s or false if it were in ""'s. The
1159/// caller is expected to provide a buffer that is large enough to hold the
1160/// spelling of the filename, but is also expected to handle the case when
1161/// this method decides to use a different buffer.
1162bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001163 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001164 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001165 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001166
Chris Lattnerf64b3522008-03-09 01:54:53 +00001167 // Make sure the filename is <x> or "x".
1168 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001169 if (Buffer[0] == '<') {
1170 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001171 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001172 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001173 return true;
1174 }
1175 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001176 } else if (Buffer[0] == '"') {
1177 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001178 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001179 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001180 return true;
1181 }
1182 isAngled = false;
1183 } else {
1184 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001185 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001186 return true;
1187 }
Mike Stump11289f42009-09-09 15:08:12 +00001188
Chris Lattnerf64b3522008-03-09 01:54:53 +00001189 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001190 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001191 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001192 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001193 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001194 }
Mike Stump11289f42009-09-09 15:08:12 +00001195
Chris Lattnerf64b3522008-03-09 01:54:53 +00001196 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001197 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001198 return isAngled;
1199}
1200
1201/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1202/// from a macro as multiple tokens, which need to be glued together. This
1203/// occurs for code like:
1204/// #define FOO <a/b.h>
1205/// #include FOO
1206/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1207///
1208/// This code concatenates and consumes tokens up to the '>' token. It returns
1209/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001210/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001211bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001212 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001213 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001214 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001215
John Thompsonb5353522009-10-30 13:49:06 +00001216 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001217 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001218 End = CurTok.getLocation();
1219
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001220 // FIXME: Provide code completion for #includes.
1221 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001222 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001223 Lex(CurTok);
1224 continue;
1225 }
1226
Chris Lattnerf64b3522008-03-09 01:54:53 +00001227 // Append the spelling of this token to the buffer. If there was a space
1228 // before it, add it now.
1229 if (CurTok.hasLeadingSpace())
1230 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001231
Chris Lattnerf64b3522008-03-09 01:54:53 +00001232 // Get the spelling of the token, directly into FilenameBuffer if possible.
1233 unsigned PreAppendSize = FilenameBuffer.size();
1234 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001235
Chris Lattnerf64b3522008-03-09 01:54:53 +00001236 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001237 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001238
Chris Lattnerf64b3522008-03-09 01:54:53 +00001239 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1240 if (BufPtr != &FilenameBuffer[PreAppendSize])
1241 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001242
Chris Lattnerf64b3522008-03-09 01:54:53 +00001243 // Resize FilenameBuffer to the correct size.
1244 if (CurTok.getLength() != ActualLen)
1245 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001246
Chris Lattnerf64b3522008-03-09 01:54:53 +00001247 // If we found the '>' marker, return success.
1248 if (CurTok.is(tok::greater))
1249 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001250
John Thompsonb5353522009-10-30 13:49:06 +00001251 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001252 }
1253
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001254 // If we hit the eod marker, emit an error and return true so that the caller
1255 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001256 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001257 return true;
1258}
1259
1260/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1261/// file to be included from the lexer, then include it! This is a common
1262/// routine with functionality shared between #include, #include_next and
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001263/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001264/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001265void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1266 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001267 const DirectoryLookup *LookupFrom,
1268 bool isImport) {
1269
1270 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001271 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001272
Chris Lattnerf64b3522008-03-09 01:54:53 +00001273 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001274 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001275 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001276 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001277 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001278
Chris Lattnerf64b3522008-03-09 01:54:53 +00001279 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001280 case tok::eod:
1281 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001282 return;
Mike Stump11289f42009-09-09 15:08:12 +00001283
Chris Lattnerf64b3522008-03-09 01:54:53 +00001284 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001285 case tok::string_literal:
1286 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001287 End = FilenameTok.getLocation();
Douglas Gregor41e115a2011-11-30 18:02:36 +00001288 CharEnd = End.getLocWithOffset(Filename.size());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001289 break;
Mike Stump11289f42009-09-09 15:08:12 +00001290
Chris Lattnerf64b3522008-03-09 01:54:53 +00001291 case tok::less:
1292 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1293 // case, glue the tokens together into FilenameBuffer and interpret those.
1294 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001295 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001296 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001297 Filename = FilenameBuffer.str();
Douglas Gregor41e115a2011-11-30 18:02:36 +00001298 CharEnd = getLocForEndOfToken(End);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001299 break;
1300 default:
1301 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1302 DiscardUntilEndOfDirective();
1303 return;
1304 }
Mike Stump11289f42009-09-09 15:08:12 +00001305
Aaron Ballman611306e2012-03-02 22:51:54 +00001306 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001307 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001308 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001309 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1310 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001311 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001312 DiscardUntilEndOfDirective();
1313 return;
1314 }
Mike Stump11289f42009-09-09 15:08:12 +00001315
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001316 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001317 // we allow macros that expand to nothing after the filename, because this
1318 // falls into the category of "#include pp-tokens new-line" specified in
1319 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001320 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001321
1322 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001323 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1324 Diag(FilenameTok, diag::err_pp_include_too_deep);
1325 return;
1326 }
Mike Stump11289f42009-09-09 15:08:12 +00001327
John McCall32f5fe12011-09-30 05:12:12 +00001328 // Complain about attempts to #include files in an audit pragma.
1329 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1330 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1331 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1332
1333 // Immediately leave the pragma.
1334 PragmaARCCFCodeAuditedLoc = SourceLocation();
1335 }
1336
Aaron Ballman611306e2012-03-02 22:51:54 +00001337 if (HeaderInfo.HasIncludeAliasMap()) {
1338 // Map the filename with the brackets still attached. If the name doesn't
1339 // map to anything, fall back on the filename we've already gotten the
1340 // spelling for.
1341 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1342 if (!NewName.empty())
1343 Filename = NewName;
1344 }
1345
Chris Lattnerf64b3522008-03-09 01:54:53 +00001346 // Search include directories.
1347 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001348 SmallString<1024> SearchPath;
1349 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001350 // We get the raw path only if we have 'Callbacks' to which we later pass
1351 // the path.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001352 Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001353 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001354 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001355 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001356 getLangOpts().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001357
Douglas Gregor11729f02011-11-30 18:12:06 +00001358 if (Callbacks) {
1359 if (!File) {
1360 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001361 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001362 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1363 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1364 // Add the recovery path to the list of search paths.
1365 DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
1366 HeaderInfo.AddSearchPath(DL, isAngled);
1367
1368 // Try the lookup again, skipping the cache.
1369 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001370 getLangOpts().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001371 /*SkipCache*/true);
1372 }
1373 }
1374 }
1375
1376 // Notify the callback object that we've seen an inclusion directive.
1377 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1378 End, SearchPath, RelativePath);
1379 }
1380
1381 if (File == 0) {
1382 if (!SuppressIncludeNotFoundError)
1383 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1384 return;
1385 }
1386
Douglas Gregor97eec242011-09-15 22:00:41 +00001387 // If we are supposed to import a module rather than including the header,
1388 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001389 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001390 // Compute the module access path corresponding to this module.
1391 // FIXME: Should we have a second loadModule() overload to avoid this
1392 // extra lookup step?
1393 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregorde3ef502011-11-30 23:21:26 +00001394 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001395 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1396 FilenameTok.getLocation()));
1397 std::reverse(Path.begin(), Path.end());
1398
Douglas Gregor41e115a2011-11-30 18:02:36 +00001399 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001400 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001401 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1402 if (I)
1403 PathString += '.';
1404 PathString += Path[I].first->getName();
1405 }
1406 int IncludeKind = 0;
1407
1408 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1409 case tok::pp_include:
1410 IncludeKind = 0;
1411 break;
1412
1413 case tok::pp_import:
1414 IncludeKind = 1;
1415 break;
1416
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001417 case tok::pp_include_next:
1418 IncludeKind = 2;
1419 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001420
1421 case tok::pp___include_macros:
1422 IncludeKind = 3;
1423 break;
1424
1425 default:
1426 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001427 }
1428
Douglas Gregor2537a362011-12-08 17:01:29 +00001429 // Determine whether we are actually building the module that this
1430 // include directive maps to.
1431 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001432 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001433
David Blaikiebbafb8a2012-03-11 07:00:24 +00001434 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001435 // If we're not building the imported module, warn that we're going
1436 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001437 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001438 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1439 /*IsTokenRange=*/false);
1440 Diag(HashLoc, diag::warn_auto_module_import)
1441 << IncludeKind << PathString
1442 << FixItHint::CreateReplacement(ReplaceRange,
Ted Kremenekc1e4dd02012-03-01 22:07:04 +00001443 "@__experimental_modules_import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001444 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001445
Douglas Gregor71944202011-11-30 00:36:36 +00001446 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001447 // If this was an #__include_macros directive, only make macros visible.
1448 Module::NameVisibilityKind Visibility
1449 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor98a52db2011-12-20 00:28:52 +00001450 Module *Imported
1451 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1452 /*IsIncludeDirective=*/true);
Douglas Gregor2537a362011-12-08 17:01:29 +00001453
1454 // If this header isn't part of the module we're building, we're done.
Douglas Gregor98a52db2011-12-20 00:28:52 +00001455 if (!BuildingImportedModule && Imported)
Douglas Gregor2537a362011-12-08 17:01:29 +00001456 return;
Douglas Gregor97eec242011-09-15 22:00:41 +00001457 }
1458
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001459 // The #included file will be considered to be a system header if either it is
1460 // in a system include directory, or if the #includer is a system include
1461 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001462 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001463 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001464 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001465
Chris Lattner72286d62010-04-19 20:44:31 +00001466 // Ask HeaderInfo if we should enter this #include file. If not, #including
1467 // this file will have no effect.
1468 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001469 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001470 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001471 return;
1472 }
1473
Chris Lattnerf64b3522008-03-09 01:54:53 +00001474 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001475 SourceLocation IncludePos = End;
1476 // If the filename string was the result of macro expansions, set the include
1477 // position on the file where it will be included and after the expansions.
1478 if (IncludePos.isMacroID())
1479 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1480 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001481 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001482
1483 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001484 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001485}
1486
1487/// HandleIncludeNextDirective - Implements #include_next.
1488///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001489void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1490 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001491 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001492
Chris Lattnerf64b3522008-03-09 01:54:53 +00001493 // #include_next is like #include, except that we start searching after
1494 // the current found directory. If we can't do this, issue a
1495 // diagnostic.
1496 const DirectoryLookup *Lookup = CurDirLookup;
1497 if (isInPrimaryFile()) {
1498 Lookup = 0;
1499 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1500 } else if (Lookup == 0) {
1501 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1502 } else {
1503 // Start looking up in the next directory.
1504 ++Lookup;
1505 }
Mike Stump11289f42009-09-09 15:08:12 +00001506
Douglas Gregor796d76a2010-10-20 22:00:55 +00001507 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001508}
1509
Aaron Ballman0467f552012-03-18 03:10:37 +00001510/// HandleMicrosoftImportDirective - Implements #import for Microsoft Mode
1511void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1512 // The Microsoft #import directive takes a type library and generates header
1513 // files from it, and includes those. This is beyond the scope of what clang
1514 // does, so we ignore it and error out. However, #import can optionally have
1515 // trailing attributes that span multiple lines. We're going to eat those
1516 // so we can continue processing from there.
1517 Diag(Tok, diag::err_pp_import_directive_ms );
1518
1519 // Read tokens until we get to the end of the directive. Note that the
1520 // directive can be split over multiple lines using the backslash character.
1521 DiscardUntilEndOfDirective();
1522}
1523
Chris Lattnerf64b3522008-03-09 01:54:53 +00001524/// HandleImportDirective - Implements #import.
1525///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001526void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1527 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001528 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1529 if (LangOpts.MicrosoftMode)
1530 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001531 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001532 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001533 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001534}
1535
Chris Lattner58a1eb02009-04-08 18:46:40 +00001536/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1537/// pseudo directive in the predefines buffer. This handles it by sucking all
1538/// tokens through the preprocessor and discarding them (only keeping the side
1539/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001540void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1541 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001542 // This directive should only occur in the predefines buffer. If not, emit an
1543 // error and reject it.
1544 SourceLocation Loc = IncludeMacrosTok.getLocation();
1545 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1546 Diag(IncludeMacrosTok.getLocation(),
1547 diag::pp_include_macros_out_of_predefines);
1548 DiscardUntilEndOfDirective();
1549 return;
1550 }
Mike Stump11289f42009-09-09 15:08:12 +00001551
Chris Lattnere01d82b2009-04-08 20:53:24 +00001552 // Treat this as a normal #include for checking purposes. If this is
1553 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001554 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001555
Chris Lattnere01d82b2009-04-08 20:53:24 +00001556 Token TmpTok;
1557 do {
1558 Lex(TmpTok);
1559 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1560 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001561}
1562
Chris Lattnerf64b3522008-03-09 01:54:53 +00001563//===----------------------------------------------------------------------===//
1564// Preprocessor Macro Directive Handling.
1565//===----------------------------------------------------------------------===//
1566
1567/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1568/// definition has just been read. Lex the rest of the arguments and the
1569/// closing ), updating MI with what we learn. Return true if an error occurs
1570/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001571bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001572 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001573
Chris Lattnerf64b3522008-03-09 01:54:53 +00001574 while (1) {
1575 LexUnexpandedToken(Tok);
1576 switch (Tok.getKind()) {
1577 case tok::r_paren:
1578 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001579 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001580 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001581 // Otherwise we have #define FOO(A,)
1582 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1583 return true;
1584 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001585 if (!LangOpts.C99)
1586 Diag(Tok, LangOpts.CPlusPlus0x ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001587 diag::warn_cxx98_compat_variadic_macro :
1588 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001589
1590 // Lex the token after the identifier.
1591 LexUnexpandedToken(Tok);
1592 if (Tok.isNot(tok::r_paren)) {
1593 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1594 return true;
1595 }
1596 // Add the __VA_ARGS__ identifier as an argument.
1597 Arguments.push_back(Ident__VA_ARGS__);
1598 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001599 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001600 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001601 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001602 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1603 return true;
1604 default:
1605 // Handle keywords and identifiers here to accept things like
1606 // #define Foo(for) for.
1607 IdentifierInfo *II = Tok.getIdentifierInfo();
1608 if (II == 0) {
1609 // #define X(1
1610 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1611 return true;
1612 }
1613
1614 // If this is already used as an argument, it is used multiple times (e.g.
1615 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001616 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001617 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001618 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001619 return true;
1620 }
Mike Stump11289f42009-09-09 15:08:12 +00001621
Chris Lattnerf64b3522008-03-09 01:54:53 +00001622 // Add the argument to the macro info.
1623 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001624
Chris Lattnerf64b3522008-03-09 01:54:53 +00001625 // Lex the token after the identifier.
1626 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001627
Chris Lattnerf64b3522008-03-09 01:54:53 +00001628 switch (Tok.getKind()) {
1629 default: // #define X(A B
1630 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1631 return true;
1632 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001633 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001634 return false;
1635 case tok::comma: // #define X(A,
1636 break;
1637 case tok::ellipsis: // #define X(A... -> GCC extension
1638 // Diagnose extension.
1639 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001640
Chris Lattnerf64b3522008-03-09 01:54:53 +00001641 // Lex the token after the identifier.
1642 LexUnexpandedToken(Tok);
1643 if (Tok.isNot(tok::r_paren)) {
1644 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1645 return true;
1646 }
Mike Stump11289f42009-09-09 15:08:12 +00001647
Chris Lattnerf64b3522008-03-09 01:54:53 +00001648 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001649 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001650 return false;
1651 }
1652 }
1653 }
1654}
1655
1656/// HandleDefineDirective - Implements #define. This consumes the entire macro
1657/// line then lets the caller lex the next real token.
1658void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1659 ++NumDefined;
1660
1661 Token MacroNameTok;
1662 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001663
Chris Lattnerf64b3522008-03-09 01:54:53 +00001664 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001665 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001666 return;
1667
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001668 Token LastTok = MacroNameTok;
1669
Chris Lattnerf64b3522008-03-09 01:54:53 +00001670 // If we are supposed to keep comments in #defines, reenable comment saving
1671 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001672 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001673
Chris Lattnerf64b3522008-03-09 01:54:53 +00001674 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001675 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001676
Chris Lattnerf64b3522008-03-09 01:54:53 +00001677 Token Tok;
1678 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001679
Chris Lattnerf64b3522008-03-09 01:54:53 +00001680 // If this is a function-like macro definition, parse the argument list,
1681 // marking each of the identifiers as being used as macro arguments. Also,
1682 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001683 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001684 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001685 } else if (Tok.hasLeadingSpace()) {
1686 // This is a normal token with leading space. Clear the leading space
1687 // marker on the first token to get proper expansion.
1688 Tok.clearFlag(Token::LeadingSpace);
1689 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001690 // This is a function-like macro definition. Read the argument list.
1691 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001692 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001693 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001694 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001695 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001696 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001697 DiscardUntilEndOfDirective();
1698 return;
1699 }
1700
Chris Lattner249c38b2009-04-19 18:26:34 +00001701 // If this is a definition of a variadic C99 function-like macro, not using
1702 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001703
Chris Lattner249c38b2009-04-19 18:26:34 +00001704 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1705 // This gets unpoisoned where it is allowed.
1706 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1707 if (MI->isC99Varargs())
1708 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Chris Lattnerf64b3522008-03-09 01:54:53 +00001710 // Read the first token after the arg list for down below.
1711 LexUnexpandedToken(Tok);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001712 } else if (LangOpts.C99 || LangOpts.CPlusPlus0x) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001713 // C99 requires whitespace between the macro definition and the body. Emit
1714 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001715 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001716 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001717 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1718 // first character of a replacement list is not a character required by
1719 // subclause 5.2.1, then there shall be white-space separation between the
1720 // identifier and the replacement list.". 5.2.1 lists this set:
1721 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1722 // is irrelevant here.
1723 bool isInvalid = false;
1724 if (Tok.is(tok::at)) // @ is not in the list above.
1725 isInvalid = true;
1726 else if (Tok.is(tok::unknown)) {
1727 // If we have an unknown token, it is something strange like "`". Since
1728 // all of valid characters would have lexed into a single character
1729 // token of some sort, we know this is not a valid case.
1730 isInvalid = true;
1731 }
1732 if (isInvalid)
1733 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1734 else
1735 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001736 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001737
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001738 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001739 LastTok = Tok;
1740
Chris Lattnerf64b3522008-03-09 01:54:53 +00001741 // Read the rest of the macro body.
1742 if (MI->isObjectLike()) {
1743 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001744 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001745 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001746 MI->AddTokenToBody(Tok);
1747 // Get the next token of the macro.
1748 LexUnexpandedToken(Tok);
1749 }
Mike Stump11289f42009-09-09 15:08:12 +00001750
Chris Lattnerf64b3522008-03-09 01:54:53 +00001751 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001752 // Otherwise, read the body of a function-like macro. While we are at it,
1753 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1754 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001755 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001756 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001757
Chris Lattnerf64b3522008-03-09 01:54:53 +00001758 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001759 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001760
Chris Lattnerf64b3522008-03-09 01:54:53 +00001761 // Get the next token of the macro.
1762 LexUnexpandedToken(Tok);
1763 continue;
1764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765
Chris Lattnerf64b3522008-03-09 01:54:53 +00001766 // Get the next token of the macro.
1767 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001768
Chris Lattner83bd8282009-05-25 17:16:10 +00001769 // Check for a valid macro arg identifier.
1770 if (Tok.getIdentifierInfo() == 0 ||
1771 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1772
1773 // If this is assembler-with-cpp mode, we accept random gibberish after
1774 // the '#' because '#' is often a comment character. However, change
1775 // the kind of the token to tok::unknown so that the preprocessor isn't
1776 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001777 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001778 LastTok.setKind(tok::unknown);
1779 } else {
1780 Diag(Tok, diag::err_pp_stringize_not_parameter);
1781 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001782
Chris Lattner83bd8282009-05-25 17:16:10 +00001783 // Disable __VA_ARGS__ again.
1784 Ident__VA_ARGS__->setIsPoisoned(true);
1785 return;
1786 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001787 }
Mike Stump11289f42009-09-09 15:08:12 +00001788
Chris Lattner83bd8282009-05-25 17:16:10 +00001789 // Things look ok, add the '#' and param name tokens to the macro.
1790 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001791 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001792 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001793
Chris Lattnerf64b3522008-03-09 01:54:53 +00001794 // Get the next token of the macro.
1795 LexUnexpandedToken(Tok);
1796 }
1797 }
Mike Stump11289f42009-09-09 15:08:12 +00001798
1799
Chris Lattnerf64b3522008-03-09 01:54:53 +00001800 // Disable __VA_ARGS__ again.
1801 Ident__VA_ARGS__->setIsPoisoned(true);
1802
Chris Lattner57540c52011-04-15 05:22:18 +00001803 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001804 // replacement list.
1805 unsigned NumTokens = MI->getNumTokens();
1806 if (NumTokens != 0) {
1807 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1808 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001809 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001810 return;
1811 }
1812 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1813 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001814 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001815 return;
1816 }
1817 }
Mike Stump11289f42009-09-09 15:08:12 +00001818
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001819 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001820
Chris Lattnerf64b3522008-03-09 01:54:53 +00001821 // Finally, if this identifier already had a macro defined for it, verify that
1822 // the macro bodies are identical and free the old definition.
1823 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001824 // It is very common for system headers to have tons of macro redefinitions
1825 // and for warnings to be disabled in system headers. If this is the case,
1826 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001827 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001828 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001829 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001830 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001831
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001832 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001833 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001834 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001835 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001836 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1837 << MacroNameTok.getIdentifierInfo();
1838 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1839 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001840 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001841 if (OtherMI->isWarnIfUnused())
1842 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001843 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattnerf64b3522008-03-09 01:54:53 +00001846 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001847
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001848 assert(!MI->isUsed());
1849 // If we need warning for not using the macro, add its location in the
1850 // warn-because-unused-macro set. If it gets used it will be removed from set.
1851 if (isInPrimaryFile() && // don't warn for include'd macros.
1852 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00001853 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001854 MI->setIsWarnIfUnused(true);
1855 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1856 }
1857
Chris Lattner928e9092009-04-12 01:39:54 +00001858 // If the callbacks want to know, tell them about the macro definition.
1859 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001860 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001861}
1862
1863/// HandleUndefDirective - Implements #undef.
1864///
1865void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1866 ++NumUndefined;
1867
1868 Token MacroNameTok;
1869 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001870
Chris Lattnerf64b3522008-03-09 01:54:53 +00001871 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001872 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001873 return;
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattnerf64b3522008-03-09 01:54:53 +00001875 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001876 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001877
Chris Lattnerf64b3522008-03-09 01:54:53 +00001878 // Okay, we finally have a valid identifier to undef.
1879 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001880
Chris Lattnerf64b3522008-03-09 01:54:53 +00001881 // If the macro is not defined, this is a noop undef, just return.
1882 if (MI == 0) return;
1883
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00001884 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00001885 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001886
1887 // If the callbacks want to know, tell them about the macro #undef.
1888 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001889 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001890
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001891 if (MI->isWarnIfUnused())
1892 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1893
Chris Lattnerf64b3522008-03-09 01:54:53 +00001894 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001895 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001896 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1897}
1898
1899
1900//===----------------------------------------------------------------------===//
1901// Preprocessor Conditional Directive Handling.
1902//===----------------------------------------------------------------------===//
1903
1904/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1905/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1906/// if any tokens have been returned or pp-directives activated before this
1907/// #ifndef has been lexed.
1908///
1909void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1910 bool ReadAnyTokensBeforeDirective) {
1911 ++NumIf;
1912 Token DirectiveTok = Result;
1913
1914 Token MacroNameTok;
1915 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001916
Chris Lattnerf64b3522008-03-09 01:54:53 +00001917 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001918 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001919 // Skip code until we get to #endif. This helps with recovery by not
1920 // emitting an error when the #endif is reached.
1921 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1922 /*Foundnonskip*/false, /*FoundElse*/false);
1923 return;
1924 }
Mike Stump11289f42009-09-09 15:08:12 +00001925
Chris Lattnerf64b3522008-03-09 01:54:53 +00001926 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001927 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001928
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001929 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1930 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001931
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001932 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001933 // If the start of a top-level #ifdef and if the macro is not defined,
1934 // inform MIOpt that this might be the start of a proper include guard.
1935 // Otherwise it is some other form of unknown conditional which we can't
1936 // handle.
1937 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001938 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001939 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001940 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001941 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001942 }
1943
Chris Lattnerf64b3522008-03-09 01:54:53 +00001944 // If there is a macro, process it.
1945 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001946 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001947
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00001948 if (Callbacks) {
1949 if (isIfndef)
1950 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok);
1951 else
1952 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok);
1953 }
1954
Chris Lattnerf64b3522008-03-09 01:54:53 +00001955 // Should we include the stuff contained by this directive?
1956 if (!MI == isIfndef) {
1957 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001958 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1959 /*wasskip*/false, /*foundnonskip*/true,
1960 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001961 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001962 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001963 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001964 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001965 /*FoundElse*/false);
1966 }
1967}
1968
1969/// HandleIfDirective - Implements the #if directive.
1970///
1971void Preprocessor::HandleIfDirective(Token &IfToken,
1972 bool ReadAnyTokensBeforeDirective) {
1973 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001974
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001975 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001976 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001977 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1978 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1979 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001980
1981 // If this condition is equivalent to #ifndef X, and if this is the first
1982 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001983 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001984 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001985 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001986 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001987 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001988 }
1989
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00001990 if (Callbacks)
1991 Callbacks->If(IfToken.getLocation(),
1992 SourceRange(ConditionalBegin, ConditionalEnd));
1993
Chris Lattnerf64b3522008-03-09 01:54:53 +00001994 // Should we include the stuff contained by this directive?
1995 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001996 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001997 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001998 /*foundnonskip*/true, /*foundelse*/false);
1999 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002000 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002001 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002002 /*FoundElse*/false);
2003 }
2004}
2005
2006/// HandleEndifDirective - Implements the #endif directive.
2007///
2008void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2009 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002010
Chris Lattnerf64b3522008-03-09 01:54:53 +00002011 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002012 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002013
Chris Lattnerf64b3522008-03-09 01:54:53 +00002014 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002015 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002016 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002017 Diag(EndifToken, diag::err_pp_endif_without_if);
2018 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002019 }
Mike Stump11289f42009-09-09 15:08:12 +00002020
Chris Lattnerf64b3522008-03-09 01:54:53 +00002021 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002022 if (CurPPLexer->getConditionalStackDepth() == 0)
2023 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002024
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002025 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002026 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002027
2028 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002029 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002030}
2031
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002032/// HandleElseDirective - Implements the #else directive.
2033///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002034void Preprocessor::HandleElseDirective(Token &Result) {
2035 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002036
Chris Lattnerf64b3522008-03-09 01:54:53 +00002037 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002038 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002039
Chris Lattnerf64b3522008-03-09 01:54:53 +00002040 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002041 if (CurPPLexer->popConditionalLevel(CI)) {
2042 Diag(Result, diag::pp_err_else_without_if);
2043 return;
2044 }
Mike Stump11289f42009-09-09 15:08:12 +00002045
Chris Lattnerf64b3522008-03-09 01:54:53 +00002046 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002047 if (CurPPLexer->getConditionalStackDepth() == 0)
2048 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002049
2050 // If this is a #else with a #else before it, report the error.
2051 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002052
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002053 if (Callbacks)
2054 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2055
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002056 // Finally, skip the rest of the contents of this block.
2057 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002058 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002059}
2060
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002061/// HandleElifDirective - Implements the #elif directive.
2062///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002063void Preprocessor::HandleElifDirective(Token &ElifToken) {
2064 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002065
Chris Lattnerf64b3522008-03-09 01:54:53 +00002066 // #elif directive in a non-skipping conditional... start skipping.
2067 // We don't care what the condition is, because we will always skip it (since
2068 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002069 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002070 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002071 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002072
2073 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002074 if (CurPPLexer->popConditionalLevel(CI)) {
2075 Diag(ElifToken, diag::pp_err_elif_without_if);
2076 return;
2077 }
Mike Stump11289f42009-09-09 15:08:12 +00002078
Chris Lattnerf64b3522008-03-09 01:54:53 +00002079 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002080 if (CurPPLexer->getConditionalStackDepth() == 0)
2081 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002082
Chris Lattnerf64b3522008-03-09 01:54:53 +00002083 // If this is a #elif with a #else before it, report the error.
2084 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002085
2086 if (Callbacks)
2087 Callbacks->Elif(ElifToken.getLocation(),
2088 SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002089
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002090 // Finally, skip the rest of the contents of this block.
2091 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002092 /*FoundElse*/CI.FoundElse,
2093 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002094}