blob: 141536a1be985c2418ead8459dadd06910cdaabc [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner22eb9722006-06-18 05:43:12 +000016// -d[MDNI] - Dump various things.
17// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000029#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000030#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000031#include "clang/Lex/PPCallbacks.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000032#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000033#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000034#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000037#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000038#include "llvm/ADT/SmallVector.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000039#include "llvm/Support/MemoryBuffer.h"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +000040#include "llvm/Support/Streams.h"
Chris Lattnera2633932007-09-03 18:30:32 +000041#include <ctime>
Chris Lattner22eb9722006-06-18 05:43:12 +000042using namespace clang;
43
44//===----------------------------------------------------------------------===//
45
Chris Lattner02dffbd2006-10-14 07:50:21 +000046Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000047 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000048 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000049 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
50 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000051 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000052 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000053
Chris Lattner22eb9722006-06-18 05:43:12 +000054 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000055 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000056 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000057 NumEnteredSourceFiles = 0;
58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000059 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000060 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000061 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000062
63 // Default to discarding comments.
64 KeepComments = false;
65 KeepMacroComments = false;
66
Chris Lattner22eb9722006-06-18 05:43:12 +000067 // Macro expansion is enabled.
68 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000069 InMacroArgs = false;
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000070 NumCachedMacroExpanders = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000071
Chris Lattner8ff71992006-07-06 05:17:39 +000072 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
73 // This gets unpoisoned where it is allowed.
74 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
75
Chris Lattner1f1b0db2007-10-09 22:10:18 +000076 Predefines = 0;
77
Chris Lattnerb8761832006-06-24 21:31:03 +000078 // Initialize the pragma handlers.
79 PragmaHandlers = new PragmaNamespace(0);
80 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000081
82 // Initialize builtin macros like __LINE__ and friends.
83 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000084}
85
86Preprocessor::~Preprocessor() {
87 // Free any active lexers.
88 delete CurLexer;
89
Chris Lattner69772b02006-07-02 20:34:39 +000090 while (!IncludeMacroStack.empty()) {
91 delete IncludeMacroStack.back().TheLexer;
92 delete IncludeMacroStack.back().TheMacroExpander;
93 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000094 }
Chris Lattnerc43ddc82007-10-07 08:44:20 +000095
96 // Free any macro definitions.
97 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
98 Macros.begin(), E = Macros.end(); I != E; ++I) {
99 // Free the macro definition.
100 delete I->second;
101 I->second = 0;
102 I->first->setHasMacroDefinition(false);
103 }
Chris Lattnerb8761832006-06-24 21:31:03 +0000104
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000105 // Free any cached macro expanders.
106 for (unsigned i = 0, e = NumCachedMacroExpanders; i != e; ++i)
107 delete MacroExpanderCache[i];
108
Chris Lattnerb8761832006-06-24 21:31:03 +0000109 // Release pragma information.
110 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000111
112 // Delete the scratch buffer info.
113 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +0000114}
115
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000116PPCallbacks::~PPCallbacks() {
117}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000118
Chris Lattner22eb9722006-06-18 05:43:12 +0000119/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
Chris Lattner146762e2007-07-20 16:59:19 +0000120/// the specified Token's location, translating the token's start
Chris Lattner22eb9722006-06-18 05:43:12 +0000121/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattner36982e42007-05-16 17:49:37 +0000122void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +0000123 Diags.Report(getFullLoc(Loc), DiagID);
Chris Lattner36982e42007-05-16 17:49:37 +0000124}
125
Chris Lattnercb283342006-06-18 06:48:37 +0000126void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000127 const std::string &Msg) {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +0000128 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000129}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000130
Chris Lattner146762e2007-07-20 16:59:19 +0000131void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000132 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
133 << getSpelling(Tok) << "'";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000134
135 if (!DumpFlags) return;
Chris Lattner615315f2007-12-09 20:31:55 +0000136
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000137 llvm::cerr << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000138 if (Tok.isAtStartOfLine())
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000139 llvm::cerr << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000140 if (Tok.hasLeadingSpace())
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000141 llvm::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000142 if (Tok.isExpandDisabled())
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000143 llvm::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000144 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000145 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000146 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
147 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000148 }
Chris Lattner615315f2007-12-09 20:31:55 +0000149
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000150 llvm::cerr << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000151 DumpLocation(Tok.getLocation());
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000152 llvm::cerr << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000153}
154
155void Preprocessor::DumpLocation(SourceLocation Loc) const {
156 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000157 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
158 << SourceMgr.getLineNumber(LogLoc) << ':'
159 << SourceMgr.getLineNumber(LogLoc);
Chris Lattner615315f2007-12-09 20:31:55 +0000160
161 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
162 if (PhysLoc != LogLoc) {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000163 llvm::cerr << " <PhysLoc=";
Chris Lattner615315f2007-12-09 20:31:55 +0000164 DumpLocation(PhysLoc);
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000165 llvm::cerr << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000166 }
Chris Lattnerd01e2912006-06-18 16:22:51 +0000167}
168
169void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000170 llvm::cerr << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000171 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
172 DumpToken(MI.getReplacementToken(i));
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000173 llvm::cerr << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000174 }
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000175 llvm::cerr << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000176}
177
Chris Lattner22eb9722006-06-18 05:43:12 +0000178void Preprocessor::PrintStats() {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000179 llvm::cerr << "\n*** Preprocessor Stats:\n";
180 llvm::cerr << NumDirectives << " directives found:\n";
181 llvm::cerr << " " << NumDefined << " #define.\n";
182 llvm::cerr << " " << NumUndefined << " #undef.\n";
183 llvm::cerr << " #include/#include_next/#import:\n";
184 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
185 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
186 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
187 llvm::cerr << " " << NumElse << " #else/#elif.\n";
188 llvm::cerr << " " << NumEndif << " #endif.\n";
189 llvm::cerr << " " << NumPragma << " #pragma.\n";
190 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000191
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000192 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
193 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
194 << NumFastMacroExpanded << " on the fast path.\n";
195 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
196 << " token paste (##) operations performed, "
197 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000198}
199
200//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000201// Token Spelling
202//===----------------------------------------------------------------------===//
203
204
205/// getSpelling() - Return the 'spelling' of this token. The spelling of a
206/// token are the characters used to represent the token in the source file
207/// after trigraph expansion and escaped-newline folding. In particular, this
208/// wants to get the true, uncanonicalized, spelling of things like digraphs
209/// UCNs, etc.
Chris Lattner146762e2007-07-20 16:59:19 +0000210std::string Preprocessor::getSpelling(const Token &Tok) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000211 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
212
213 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000214 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000215 if (!Tok.needsCleaning())
216 return std::string(TokStart, TokStart+Tok.getLength());
217
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218 std::string Result;
219 Result.reserve(Tok.getLength());
220
Chris Lattneref9eae12006-07-04 22:33:12 +0000221 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000222 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
223 Ptr != End; ) {
224 unsigned CharSize;
225 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
226 Ptr += CharSize;
227 }
228 assert(Result.size() != unsigned(Tok.getLength()) &&
229 "NeedsCleaning flag set on something that didn't need cleaning!");
230 return Result;
231}
232
233/// getSpelling - This method is used to get the spelling of a token into a
234/// preallocated buffer, instead of as an std::string. The caller is required
235/// to allocate enough space for the token, which is guaranteed to be at least
236/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000237///
238/// Note that this method may do two possible things: it may either fill in
239/// the buffer specified with characters, or it may *change the input pointer*
240/// to point to a constant buffer with the data already in it (avoiding a
241/// copy). The caller is not allowed to modify the returned buffer pointer
242/// if an internal buffer is returned.
Chris Lattner146762e2007-07-20 16:59:19 +0000243unsigned Preprocessor::getSpelling(const Token &Tok,
Chris Lattneref9eae12006-07-04 22:33:12 +0000244 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000245 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
246
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000247 // If this token is an identifier, just return the string from the identifier
248 // table, which is very quick.
249 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
250 Buffer = II->getName();
Chris Lattner32e6d642007-07-22 22:50:09 +0000251
252 // Return the length of the token. If the token needed cleaning, don't
253 // include the size of the newlines or trigraphs in it.
254 if (!Tok.needsCleaning())
255 return Tok.getLength();
256 else
257 return strlen(Buffer);
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000258 }
259
260 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000261 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000262
263 // If this token contains nothing interesting, return it directly.
264 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000265 Buffer = TokStart;
266 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000267 }
268 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000269 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000270 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
271 Ptr != End; ) {
272 unsigned CharSize;
273 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
274 Ptr += CharSize;
275 }
276 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
277 "NeedsCleaning flag set on something that didn't need cleaning!");
278
279 return OutBuf-Buffer;
280}
281
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000282
283/// CreateString - Plop the specified string into a scratch buffer and return a
284/// location for it. If specified, the source location provides a source
285/// location for the token.
286SourceLocation Preprocessor::
287CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
288 if (SLoc.isValid())
289 return ScratchBuf->getToken(Buf, Len, SLoc);
290 return ScratchBuf->getToken(Buf, Len);
291}
292
293
Chris Lattner8a7003c2007-07-16 06:48:38 +0000294/// AdvanceToTokenCharacter - Given a location that specifies the start of a
295/// token, return a new location that specifies a character within the token.
296SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
297 unsigned CharNo) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000298 // If they request the first char of the token, we're trivially done. If this
299 // is a macro expansion, it doesn't make sense to point to a character within
300 // the instantiation point (the name). We could point to the source
301 // character, but without also pointing to instantiation info, this is
302 // confusing.
303 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000304
305 // Figure out how many physical characters away the specified logical
306 // character is. This needs to take into consideration newlines and
307 // trigraphs.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000308 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
309 unsigned PhysOffset = 0;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000310
311 // The usual case is that tokens don't contain anything interesting. Skip
312 // over the uninteresting characters. If a token only consists of simple
313 // chars, this method is extremely fast.
314 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000315 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000316
317 // If we have a character that may be a trigraph or escaped newline, create a
318 // lexer to parse it correctly.
Chris Lattner8a7003c2007-07-16 06:48:38 +0000319 if (CharNo != 0) {
320 // Create a lexer starting at this token position.
Chris Lattner77e9de52007-07-20 16:52:03 +0000321 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattner146762e2007-07-20 16:59:19 +0000322 Token Tok;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000323 // Skip over characters the remaining characters.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000324 const char *TokStartPtr = TokPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000325 for (; CharNo; --CharNo)
326 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000327
328 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000329 }
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000330
331 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner8a7003c2007-07-16 06:48:38 +0000332}
333
334
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000335//===----------------------------------------------------------------------===//
336// Preprocessor Initialization Methods
337//===----------------------------------------------------------------------===//
338
339// Append a #define line to Buf for Macro. Macro should be of the form XXX,
340// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
341// "#define XXX Y z W". To get a #define with no value, use "XXX=".
342static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
343 const char *Command = "#define ") {
344 Buf.insert(Buf.end(), Command, Command+strlen(Command));
345 if (const char *Equal = strchr(Macro, '=')) {
346 // Turn the = into ' '.
347 Buf.insert(Buf.end(), Macro, Equal);
348 Buf.push_back(' ');
349 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
350 } else {
351 // Push "macroname 1".
352 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
353 Buf.push_back(' ');
354 Buf.push_back('1');
355 }
356 Buf.push_back('\n');
357}
358
359
360static void InitializePredefinedMacros(Preprocessor &PP,
361 std::vector<char> &Buf) {
362 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
363 // and __DATE__ etc.
364#if 0
365 /* __STDC__ has the value 1 under normal circumstances.
366 However, if (a) we are in a system header, (b) the option
367 stdc_0_in_system_headers is true (set by target config), and
368 (c) we are not in strictly conforming mode, then it has the
369 value 0. (b) and (c) are already checked in cpp_init_builtins. */
370 //case BT_STDC:
371 if (cpp_in_system_header (pfile))
372 number = 0;
373 else
374 number = 1;
375 break;
376#endif
377 // These should all be defined in the preprocessor according to the
378 // current language configuration.
379 DefineBuiltinMacro(Buf, "__STDC__=1");
380 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
381 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
382 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
383 else if (0) // STDC94 ?
384 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
385
386 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
387 if (PP.getLangOptions().ObjC1)
388 DefineBuiltinMacro(Buf, "__OBJC__=1");
389 if (PP.getLangOptions().ObjC2)
390 DefineBuiltinMacro(Buf, "__OBJC2__=1");
Steve Naroff6d40db02007-10-31 18:42:27 +0000391
Chris Lattnered2a9eb2007-10-10 17:48:53 +0000392 // Add __builtin_va_list typedef.
393 {
394 const char *VAList = PP.getTargetInfo().getVAListDeclaration();
395 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
396 Buf.push_back('\n');
397 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000398
399 // Get the target #defines.
400 PP.getTargetInfo().getTargetDefines(Buf);
401
402 // Compiler set macros.
403 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
Steve Naroff68754c52007-11-10 18:06:36 +0000404 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1050");
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000405 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
406 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
407 DefineBuiltinMacro(Buf, "__GNUC__=4");
408 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
409 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
410 "build 5250)\"");
411
412 // Build configuration options.
413 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
414 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
415 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
416 DefineBuiltinMacro(Buf, "__PIC__=1");
417
418
419 if (PP.getLangOptions().CPlusPlus) {
420 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
421 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
422 DefineBuiltinMacro(Buf, "__GNUG__=4");
423 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
424 DefineBuiltinMacro(Buf, "__cplusplus=1");
425 DefineBuiltinMacro(Buf, "__private_extern__=extern");
426 }
Steve Naroffb2c80c72008-02-07 03:50:06 +0000427 if (PP.getLangOptions().Microsoft) {
428 DefineBuiltinMacro(Buf, "__stdcall=");
429 DefineBuiltinMacro(Buf, "__cdecl=");
430 DefineBuiltinMacro(Buf, "_cdecl=");
431 DefineBuiltinMacro(Buf, "__ptr64=");
Steve Naroff4e79d342008-02-07 23:24:32 +0000432 DefineBuiltinMacro(Buf, "__w64=");
Steve Naroffb2c80c72008-02-07 03:50:06 +0000433 DefineBuiltinMacro(Buf, "__forceinline=");
Steve Naroff6936a082008-02-07 15:26:07 +0000434 DefineBuiltinMacro(Buf, "__int8=char");
435 DefineBuiltinMacro(Buf, "__int16=short");
436 DefineBuiltinMacro(Buf, "__int32=int");
437 DefineBuiltinMacro(Buf, "__int64=long");
Steve Naroffb2c80c72008-02-07 03:50:06 +0000438 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000439 // FIXME: Should emit a #line directive here.
440}
441
442
443/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000444/// which implicitly adds the builtin defines etc.
Ted Kremenek230bd912007-12-19 22:51:13 +0000445void Preprocessor::EnterMainSourceFile() {
446
447 unsigned MainFileID = SourceMgr.getMainFileID();
448
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000449 // Enter the main file source buffer.
450 EnterSourceFile(MainFileID, 0);
451
Chris Lattner609d4132007-11-15 19:07:47 +0000452 // Tell the header info that the main file was entered. If the file is later
453 // #imported, it won't be re-entered.
454 if (const FileEntry *FE =
455 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
456 HeaderInfo.IncrementIncludeCount(FE);
457
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000458 std::vector<char> PrologFile;
459 PrologFile.reserve(4080);
460
461 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
462 InitializePredefinedMacros(*this, PrologFile);
463
464 // Add on the predefines from the driver.
465 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
466
467 // Memory buffer must end with a null byte!
468 PrologFile.push_back(0);
469
470 // Now that we have emitted the predefined macros, #includes, etc into
471 // PrologFile, preprocess it to populate the initial preprocessor state.
472 llvm::MemoryBuffer *SB =
473 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
474 "<predefines>");
475 assert(SB && "Cannot fail to create predefined source buffer");
476 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
477 assert(FileID && "Could not create FileID for predefines?");
478
479 // Start parsing the predefines.
480 EnterSourceFile(FileID, 0);
481}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000482
Chris Lattnerd01e2912006-06-18 16:22:51 +0000483//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000484// Source File Location Methods.
485//===----------------------------------------------------------------------===//
486
Chris Lattner22eb9722006-06-18 05:43:12 +0000487/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
488/// return null on failure. isAngled indicates whether the file reference is
489/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000490const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
491 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000492 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000493 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000494 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000495 // If the header lookup mechanism may be relative to the current file, pass in
496 // info about where the current file is.
497 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000498 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000499 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
500 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000501 }
502
Chris Lattner63dd32b2006-10-20 04:42:40 +0000503 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000504 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000505 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000506 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
507 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000508 if (FE) return FE;
509
510 // Otherwise, see if this is a subframework header. If so, this is relative
511 // to one of the headers on the #include stack. Walk the list of the current
512 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000513 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner12261882008-02-01 05:34:02 +0000514 if ((CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc())))
515 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
516 CurFileEnt)))
517 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000518 }
519
520 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
521 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000522 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner12261882008-02-01 05:34:02 +0000523 if ((CurFileEnt =
524 SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc())))
525 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
526 FilenameEnd, CurFileEnt)))
527 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000528 }
529 }
530
531 // Otherwise, we really couldn't find the file.
532 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000533}
534
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000535/// isInPrimaryFile - Return true if we're in the top-level file, not in a
536/// #include.
537bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000538 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000539 return IncludeMacroStack.empty();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000540
Chris Lattner13044d92006-07-03 05:16:44 +0000541 // If there are any stacked lexers, we're in a #include.
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000542 assert(IncludeMacroStack[0].TheLexer &&
543 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
544 "Top level include stack isn't our primary lexer?");
545 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000546 if (IncludeMacroStack[i].TheLexer &&
547 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000548 return false;
549 return true;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000550}
551
552/// getCurrentLexer - Return the current file lexer being lexed from. Note
553/// that this ignores any potentially active macro expansions and _Pragma
554/// expansions going on at the time.
555Lexer *Preprocessor::getCurrentFileLexer() const {
556 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
557
558 // Look for a stacked lexer.
559 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000560 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000561 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
562 return L;
563 }
564 return 0;
565}
566
567
Chris Lattner22eb9722006-06-18 05:43:12 +0000568/// EnterSourceFile - Add a source file to the top of the include stack and
569/// start lexing tokens from it instead of the current buffer. Return true
570/// on failure.
571void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000572 const DirectoryLookup *CurDir) {
Chris Lattner69772b02006-07-02 20:34:39 +0000573 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000574 ++NumEnteredSourceFiles;
575
Chris Lattner69772b02006-07-02 20:34:39 +0000576 if (MaxIncludeStackDepth < IncludeMacroStack.size())
577 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000578
Chris Lattner77e9de52007-07-20 16:52:03 +0000579 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Chris Lattner69772b02006-07-02 20:34:39 +0000580 EnterSourceFileWithLexer(TheLexer, CurDir);
581}
Chris Lattner22eb9722006-06-18 05:43:12 +0000582
Chris Lattner69772b02006-07-02 20:34:39 +0000583/// EnterSourceFile - Add a source file to the top of the include stack and
584/// start lexing tokens from it instead of the current buffer.
585void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
586 const DirectoryLookup *CurDir) {
587
588 // Add the current lexer to the include stack.
589 if (CurLexer || CurMacroExpander)
590 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
591 CurMacroExpander));
592
593 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000594 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000595 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000596
597 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000598 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000599 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
600
601 // Get the file entry for the current file.
602 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000603 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000604 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000605
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000606 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000607 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000608 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000609}
610
Chris Lattner69772b02006-07-02 20:34:39 +0000611
612
Chris Lattner22eb9722006-06-18 05:43:12 +0000613/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000614/// tokens from it instead of the current buffer.
Chris Lattner146762e2007-07-20 16:59:19 +0000615void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000616 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
617 CurMacroExpander));
618 CurLexer = 0;
619 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000620
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000621 if (NumCachedMacroExpanders == 0) {
622 CurMacroExpander = new MacroExpander(Tok, Args, *this);
623 } else {
624 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
625 CurMacroExpander->Init(Tok, Args);
626 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000627}
628
Chris Lattner7667d0d2006-07-16 18:16:58 +0000629/// EnterTokenStream - Add a "macro" context to the top of the include stack,
630/// which will cause the lexer to start returning the specified tokens. Note
631/// that these tokens will be re-macro-expanded when/if expansion is enabled.
632/// This method assumes that the specified stream of tokens has a permanent
633/// owner somewhere, so they do not need to be copied.
Chris Lattner146762e2007-07-20 16:59:19 +0000634void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000635 // Save our current state.
636 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
637 CurMacroExpander));
638 CurLexer = 0;
639 CurDirLookup = 0;
640
641 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000642 if (NumCachedMacroExpanders == 0) {
643 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
644 } else {
645 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
646 CurMacroExpander->Init(Toks, NumToks);
647 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000648}
649
650/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
651/// lexer stack. This should only be used in situations where the current
652/// state of the top-of-stack lexer is known.
653void Preprocessor::RemoveTopOfLexerStack() {
654 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000655
656 if (CurMacroExpander) {
657 // Delete or cache the now-dead macro expander.
658 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
659 delete CurMacroExpander;
660 else
661 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
662 } else {
663 delete CurLexer;
664 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000665 CurLexer = IncludeMacroStack.back().TheLexer;
666 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
667 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
668 IncludeMacroStack.pop_back();
669}
670
Chris Lattner22eb9722006-06-18 05:43:12 +0000671//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000672// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000673//===----------------------------------------------------------------------===//
674
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000675/// setMacroInfo - Specify a macro for this identifier.
676///
677void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
678 if (MI == 0) {
679 if (II->hasMacroDefinition()) {
680 Macros.erase(II);
681 II->setHasMacroDefinition(false);
682 }
683 } else {
684 Macros[II] = MI;
685 II->setHasMacroDefinition(true);
686 }
687}
688
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000689/// RegisterBuiltinMacro - Register the specified identifier in the identifier
690/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000691IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000692 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000693 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000694
695 // Mark it as being a macro that is builtin.
696 MacroInfo *MI = new MacroInfo(SourceLocation());
697 MI->setIsBuiltinMacro();
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000698 setMacroInfo(Id, MI);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000699 return Id;
700}
701
702
Chris Lattner677757a2006-06-28 05:26:32 +0000703/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
704/// identifier table.
705void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000706 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000707 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000708 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
709 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000710 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000711
712 // GCC Extensions.
713 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
714 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000715 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000716}
717
Chris Lattnerc2395832006-07-09 00:57:04 +0000718/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
719/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000720static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000721 const IdentifierInfo *MacroIdent,
722 Preprocessor &PP) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000723 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
724
725 // If the token isn't an identifier, it's always literally expanded.
726 if (II == 0) return true;
727
728 // If the identifier is a macro, and if that macro is enabled, it may be
729 // expanded so it's not a trivial expansion.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000730 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000731 // Fast expanding "#define X X" is ok, because X would be disabled.
732 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000733 return false;
734
735 // If this is an object-like macro invocation, it is safe to trivially expand
736 // it.
737 if (MI->isObjectLike()) return true;
738
739 // If this is a function-like macro invocation, it's safe to trivially expand
740 // as long as the identifier is not a macro argument.
741 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
742 I != E; ++I)
743 if (*I == II)
744 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000745
Chris Lattnerc2395832006-07-09 00:57:04 +0000746 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000747}
748
Chris Lattnerc2395832006-07-09 00:57:04 +0000749
Chris Lattnerafe603f2006-07-11 04:02:46 +0000750/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
751/// lexed is a '('. If so, consume the token and return true, if not, this
752/// method should have no observable side-effect on the lexed tokens.
753bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000754 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000755 unsigned Val;
756 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000757 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000758 else
759 Val = CurMacroExpander->isNextTokenLParen();
760
761 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000762 // We have run off the end. If it's a source file we don't
763 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
764 // macro stack.
765 if (CurLexer)
766 return false;
767 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000768 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
769 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000770 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000771 else
772 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000773
774 if (Val != 2)
775 break;
776
777 // Ran off the end of a source file?
778 if (Entry.TheLexer)
779 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000780 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000781 }
782
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000783 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
784 // have found something that isn't a '(' or we found the end of the
785 // translation unit. In either case, return false.
786 if (Val != 1)
787 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000788
Chris Lattner146762e2007-07-20 16:59:19 +0000789 Token Tok;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000790 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000791 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000792 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000793}
Chris Lattner677757a2006-06-28 05:26:32 +0000794
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000795/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
796/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner146762e2007-07-20 16:59:19 +0000797bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000798 MacroInfo *MI) {
Chris Lattnera30be592008-01-07 19:50:27 +0000799 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
800 // then the macro could expand to different things in other contexts, we need
801 // to disable the optimization in this case.
802 if (CurLexer) CurLexer->MIOpt.ExpandedMacro();
Chris Lattner78186052006-07-09 00:45:31 +0000803
804 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
805 if (MI->isBuiltinMacro()) {
806 ExpandBuiltinMacro(Identifier);
807 return false;
808 }
809
Chris Lattner81278c62006-10-14 19:03:49 +0000810 // If this is the first use of a target-specific macro, warn about it.
811 if (MI->isTargetSpecific()) {
812 MI->setIsTargetSpecific(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +0000813 getTargetInfo().DiagnoseNonPortability(getFullLoc(Identifier.getLocation()),
Chris Lattner81278c62006-10-14 19:03:49 +0000814 diag::port_target_macro_use);
815 }
816
Chris Lattneree8760b2006-07-15 07:42:55 +0000817 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000818 /// for each macro argument, the list of tokens that were provided to the
819 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000820 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000821
822 // If this is a function-like macro, read the arguments.
823 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000824 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000825 // name isn't a '(', this macro should not be expanded. Otherwise, consume
826 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000827 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000828 return true;
829
Chris Lattner78186052006-07-09 00:45:31 +0000830 // Remember that we are now parsing the arguments to a macro invocation.
831 // Preprocessor directives used inside macro arguments are not portable, and
832 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000833 InMacroArgs = true;
834 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000835
836 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000837 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000838
839 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000840 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000841
842 ++NumFnMacroExpanded;
843 } else {
844 ++NumMacroExpanded;
845 }
Chris Lattner13044d92006-07-03 05:16:44 +0000846
847 // Notice that this macro has been used.
848 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000849
850 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000851
852 // If this macro expands to no tokens, don't bother to push it onto the
853 // expansion stack, only to take it right back off.
854 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000855 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000856 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000857
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000858 // Ignore this macro use, just return the next token in the current
859 // buffer.
860 bool HadLeadingSpace = Identifier.hasLeadingSpace();
861 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
862
863 Lex(Identifier);
864
865 // If the identifier isn't on some OTHER line, inherit the leading
866 // whitespace/first-on-a-line property of this token. This handles
867 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
868 // empty.
869 if (!Identifier.isAtStartOfLine()) {
Chris Lattner146762e2007-07-20 16:59:19 +0000870 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
871 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000872 }
873 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000874 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000875
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000876 } else if (MI->getNumTokens() == 1 &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000877 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
878 *this)){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000879 // Otherwise, if this macro expands into a single trivially-expanded
880 // token: expand it now. This handles common cases like
881 // "#define VAL 42".
882
883 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
884 // identifier to the expanded token.
885 bool isAtStartOfLine = Identifier.isAtStartOfLine();
886 bool hasLeadingSpace = Identifier.hasLeadingSpace();
887
888 // Remember where the token is instantiated.
889 SourceLocation InstantiateLoc = Identifier.getLocation();
890
891 // Replace the result token.
892 Identifier = MI->getReplacementToken(0);
893
894 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner146762e2007-07-20 16:59:19 +0000895 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
896 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000897
898 // Update the tokens location to include both its logical and physical
899 // locations.
900 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000901 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000902 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000903
Chris Lattner6e4bf522006-07-27 06:59:25 +0000904 // If this is #define X X, we must mark the result as unexpandible.
905 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000906 if (getMacroInfo(NewII) == MI)
Chris Lattner146762e2007-07-20 16:59:19 +0000907 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000908
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000909 // Since this is not an identifier token, it can't be macro expanded, so
910 // we're done.
911 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000912 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000913 }
914
Chris Lattner78186052006-07-09 00:45:31 +0000915 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000916 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000917
918 // Now that the macro is at the top of the include stack, ask the
919 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000920 Lex(Identifier);
921 return false;
922}
923
Chris Lattneree8760b2006-07-15 07:42:55 +0000924/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000925/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000926/// invocation. This returns null on error.
Chris Lattner146762e2007-07-20 16:59:19 +0000927MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattneree8760b2006-07-15 07:42:55 +0000928 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000929 // The number of fixed arguments to parse.
930 unsigned NumFixedArgsLeft = MI->getNumArgs();
931 bool isVariadic = MI->isVariadic();
932
Chris Lattner78186052006-07-09 00:45:31 +0000933 // Outer loop, while there are more arguments, keep reading them.
Chris Lattner146762e2007-07-20 16:59:19 +0000934 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000935 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000936 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000937
938 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000939 // argument is separated by an EOF token. Use a SmallVector so we can avoid
940 // heap allocations in the common case.
Chris Lattner146762e2007-07-20 16:59:19 +0000941 llvm::SmallVector<Token, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000942
943 unsigned NumActuals = 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000944 while (Tok.is(tok::comma)) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000945 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
946 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000947 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000948
Chris Lattner78186052006-07-09 00:45:31 +0000949 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000950 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
951 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000952 LexUnexpandedToken(Tok);
953
Chris Lattner97ff7762008-01-22 19:34:51 +0000954 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
Chris Lattner78186052006-07-09 00:45:31 +0000955 Diag(MacroName, diag::err_unterm_macro_invoc);
Chris Lattner97ff7762008-01-22 19:34:51 +0000956 // Do not lose the EOF/EOM. Return it to the client.
Chris Lattner78186052006-07-09 00:45:31 +0000957 MacroName = Tok;
958 return 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000959 } else if (Tok.is(tok::r_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000960 // If we found the ) token, the macro arg list is done.
961 if (NumParens-- == 0)
962 break;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000963 } else if (Tok.is(tok::l_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000964 ++NumParens;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000965 } else if (Tok.is(tok::comma) && NumParens == 0) {
Chris Lattner78186052006-07-09 00:45:31 +0000966 // Comma ends this argument if there are more fixed arguments expected.
967 if (NumFixedArgsLeft)
968 break;
969
Chris Lattner2ada5d32006-07-15 07:51:24 +0000970 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000971 if (!isVariadic) {
972 // Emit the diagnostic at the macro name in case there is a missing ).
973 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000974 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000975 return 0;
976 }
977 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000978 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000979 // If this is a comment token in the argument list and we're just in
980 // -C mode (not -CC mode), discard the comment.
981 continue;
Chris Lattner9fcdc522007-11-23 06:50:21 +0000982 } else if (Tok.is(tok::identifier)) {
983 // Reading macro arguments can cause macros that we are currently
984 // expanding from to be popped off the expansion stack. Doing so causes
985 // them to be reenabled for expansion. Here we record whether any
986 // identifiers we lex as macro arguments correspond to disabled macros.
987 // If so, we mark the token as noexpand. This is a subtle aspect of
988 // C99 6.10.3.4p2.
989 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
990 if (!MI->isEnabled())
991 Tok.setFlag(Token::DisableExpand);
Chris Lattner78186052006-07-09 00:45:31 +0000992 }
993
994 ArgTokens.push_back(Tok);
995 }
996
Chris Lattnera12dd152006-07-11 04:09:02 +0000997 // Empty arguments are standard in C99 and supported as an extension in
998 // other modes.
999 if (ArgTokens.empty() && !Features.C99)
1000 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +00001001
Chris Lattner36b6e812006-07-21 06:38:30 +00001002 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001003 Token EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +00001004 EOFTok.startToken();
1005 EOFTok.setKind(tok::eof);
1006 EOFTok.setLocation(Tok.getLocation());
1007 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +00001008 ArgTokens.push_back(EOFTok);
1009 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +00001010 --NumFixedArgsLeft;
1011 };
1012
1013 // Okay, we either found the r_paren. Check to see if we parsed too few
1014 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +00001015 unsigned MinArgsExpected = MI->getNumArgs();
1016
Chris Lattner775d8322006-07-29 04:39:41 +00001017 // See MacroArgs instance var for description of this.
1018 bool isVarargsElided = false;
1019
Chris Lattner2ada5d32006-07-15 07:51:24 +00001020 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +00001021 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +00001022 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +00001023 // Varargs where the named vararg parameter is missing: ok as extension.
1024 // #define A(x, ...)
1025 // A("blah")
1026 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +00001027
1028 // Remember this occurred if this is a C99 macro invocation with at least
1029 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +00001030 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +00001031 } else if (MI->getNumArgs() == 1) {
1032 // #define A(x)
1033 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +00001034 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +00001035
1036 // Empty arguments are standard in C99 and supported as an extension in
1037 // other modes.
1038 if (ArgTokens.empty() && !Features.C99)
1039 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +00001040 } else {
1041 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +00001042 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +00001043 return 0;
1044 }
Chris Lattnere7a51302006-07-29 01:25:12 +00001045
1046 // Add a marker EOF token to the end of the token list for this argument.
1047 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +00001048 Tok.startToken();
1049 Tok.setKind(tok::eof);
1050 Tok.setLocation(EndLoc);
1051 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +00001052 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +00001053 }
1054
Chris Lattner775d8322006-07-29 04:39:41 +00001055 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +00001056}
1057
Chris Lattnerc673f902006-06-30 06:10:41 +00001058/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1059/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1060/// the identifier tokens inserted.
1061static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001062 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001063 time_t TT = time(0);
1064 struct tm *TM = localtime(&TT);
1065
1066 static const char * const Months[] = {
1067 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1068 };
1069
1070 char TmpBuffer[100];
1071 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1072 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001073 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001074
1075 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001076 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001077}
1078
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001079/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1080/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +00001081void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001082 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001083 IdentifierInfo *II = Tok.getIdentifierInfo();
1084 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +00001085
1086 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1087 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001088 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +00001089 return Handle_Pragma(Tok);
1090
Chris Lattner78186052006-07-09 00:45:31 +00001091 ++NumBuiltinMacroExpanded;
1092
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001093 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +00001094
1095 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +00001096 Tok.setIdentifierInfo(0);
Chris Lattner146762e2007-07-20 16:59:19 +00001097 Tok.clearFlag(Token::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +00001098
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001099 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001100 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001101 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001102 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001103 Tok.setKind(tok::numeric_constant);
1104 Tok.setLength(Length);
1105 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001106 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001107 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001108 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001109 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001110 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1111 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001112 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001113 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001114 }
1115 }
1116
Chris Lattner0766e592006-07-03 01:07:01 +00001117 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001118 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +00001119 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +00001120 Tok.setKind(tok::string_literal);
1121 Tok.setLength(FN.size());
1122 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001123 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001124 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001125 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001126 Tok.setKind(tok::string_literal);
1127 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1128 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001129 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001130 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001131 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001132 Tok.setKind(tok::string_literal);
1133 Tok.setLength(strlen("\"hh:mm:ss\""));
1134 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001135 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001136 Diag(Tok, diag::ext_pp_include_level);
1137
1138 // Compute the include depth of this token.
1139 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001140 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1141 for (; Loc.isValid(); ++Depth)
1142 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001143
1144 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1145 sprintf(TmpBuffer, "%u", Depth);
1146 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001147 Tok.setKind(tok::numeric_constant);
1148 Tok.setLength(Length);
1149 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001150 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +00001151 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1152 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1153 Diag(Tok, diag::ext_pp_timestamp);
1154
1155 // Get the file that we are lexing out of. If we're currently lexing from
1156 // a macro, dig into the include stack.
1157 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +00001158 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +00001159
1160 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001161 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +00001162
1163 // If this file is older than the file it depends on, emit a diagnostic.
1164 const char *Result;
1165 if (CurFile) {
1166 time_t TT = CurFile->getModificationTime();
1167 struct tm *TM = localtime(&TT);
1168 Result = asctime(TM);
1169 } else {
1170 Result = "??? ??? ?? ??:??:?? ????\n";
1171 }
1172 TmpBuffer[0] = '"';
1173 strcpy(TmpBuffer+1, Result);
1174 unsigned Len = strlen(TmpBuffer);
1175 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +00001176 Tok.setKind(tok::string_literal);
1177 Tok.setLength(Len);
1178 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001179 } else {
1180 assert(0 && "Unknown identifier!");
Chris Lattner615315f2007-12-09 20:31:55 +00001181 }
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001182}
Chris Lattner677757a2006-06-28 05:26:32 +00001183
1184//===----------------------------------------------------------------------===//
1185// Lexer Event Handling.
1186//===----------------------------------------------------------------------===//
1187
Chris Lattnercefc7682006-07-08 08:28:12 +00001188/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1189/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +00001190IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +00001191 const char *BufPtr) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001192 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattnercefc7682006-07-08 08:28:12 +00001193 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1194
1195 // Look up this token, see if it is a macro, or if it is a language keyword.
1196 IdentifierInfo *II;
1197 if (BufPtr && !Identifier.needsCleaning()) {
1198 // No cleaning needed, just use the characters from the lexed buffer.
1199 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1200 } else {
1201 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +00001202 llvm::SmallVector<char, 64> IdentifierBuffer;
1203 IdentifierBuffer.resize(Identifier.getLength());
1204 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +00001205 unsigned Size = getSpelling(Identifier, TmpBuf);
1206 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1207 }
Chris Lattner8c204872006-10-14 05:19:21 +00001208 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001209 return II;
1210}
1211
1212
Chris Lattner677757a2006-06-28 05:26:32 +00001213/// HandleIdentifier - This callback is invoked when the lexer reads an
1214/// identifier. This callback looks up the identifier in the map and/or
1215/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +00001216void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001217 assert(Identifier.getIdentifierInfo() &&
1218 "Can't handle identifiers without identifier info!");
1219
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001220 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001221
1222 // If this identifier was poisoned, and if it was not produced from a macro
1223 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001224 if (II.isPoisoned() && CurLexer) {
1225 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1226 Diag(Identifier, diag::err_pp_used_poisoned_id);
1227 else
1228 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1229 }
Chris Lattner677757a2006-06-28 05:26:32 +00001230
Chris Lattner78186052006-07-09 00:45:31 +00001231 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001232 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001233 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1234 if (MI->isEnabled()) {
1235 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1236 return;
1237 } else {
1238 // C99 6.10.3.4p2 says that a disabled macro may never again be
1239 // expanded, even if it's in a context where it could be expanded in the
1240 // future.
Chris Lattner146762e2007-07-20 16:59:19 +00001241 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001242 }
1243 }
Chris Lattner063400e2006-10-14 19:54:15 +00001244 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1245 // If this identifier is a macro on some other target, emit a diagnostic.
1246 // This diagnosic is only emitted when macro expansion is enabled, because
1247 // the macro would not have been expanded for the other target either.
1248 II.setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001249 getTargetInfo().DiagnoseNonPortability(getFullLoc(Identifier.getLocation()),
Chris Lattner063400e2006-10-14 19:54:15 +00001250 diag::port_target_macro_use);
1251
1252 }
Chris Lattner677757a2006-06-28 05:26:32 +00001253
Chris Lattner5b9f4892006-11-21 17:23:33 +00001254 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1255 // then we act as if it is the actual operator and not the textual
1256 // representation of it.
1257 if (II.isCPlusPlusOperatorKeyword())
1258 Identifier.setIdentifierInfo(0);
1259
Chris Lattner677757a2006-06-28 05:26:32 +00001260 // Change the kind of this identifier to the appropriate token kind, e.g.
1261 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001262 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001263
1264 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001265 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1266 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001267 if (II.isExtensionToken() && Features.C99)
1268 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001269}
1270
Chris Lattner22eb9722006-06-18 05:43:12 +00001271/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1272/// the current file. This either returns the EOF token or pops a level off
1273/// the include stack and keeps going.
Chris Lattner146762e2007-07-20 16:59:19 +00001274bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001275 assert(!CurMacroExpander &&
1276 "Ending a file when currently in a macro!");
1277
Chris Lattner371ac8a2006-07-04 07:11:10 +00001278 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001279 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001280 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001281 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001282 // Okay, this has a controlling macro, remember in PerFileInfo.
1283 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001284 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001285 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001286 }
1287 }
1288
Chris Lattner22eb9722006-06-18 05:43:12 +00001289 // If this is a #include'd file, pop it off the include stack and continue
1290 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001291 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001292 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001293 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001294
1295 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001296 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001297 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1298
1299 // Get the file entry for the current file.
1300 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001301 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001302 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001303
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001304 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1305 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001306 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001307
1308 // Client should lex another token.
1309 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 }
Chris Lattner9046dc12008-01-25 00:00:30 +00001311
1312 // If the file ends with a newline, form the EOF token on the newline itself,
1313 // rather than "on the line following it", which doesn't exist. This makes
1314 // diagnostics relating to the end of file include the last file that the user
1315 // actually typed, which is goodness.
1316 const char *EndPos = CurLexer->BufferEnd;
1317 if (EndPos != CurLexer->BufferStart &&
1318 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
1319 --EndPos;
1320
1321 // Handle \n\r and \r\n:
1322 if (EndPos != CurLexer->BufferStart &&
1323 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
1324 EndPos[-1] != EndPos[0])
1325 --EndPos;
1326 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001327
Chris Lattner8c204872006-10-14 05:19:21 +00001328 Result.startToken();
Chris Lattner9046dc12008-01-25 00:00:30 +00001329 CurLexer->BufferPtr = EndPos;
1330 CurLexer->FormTokenWithChars(Result, EndPos);
Chris Lattner8c204872006-10-14 05:19:21 +00001331 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001332
1333 // We're done with the #included file.
1334 delete CurLexer;
1335 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001336
Chris Lattner03f83482006-07-10 06:16:26 +00001337 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001338 // diagnostic is enabled, look for macros that have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001339 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001340 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1341 Macros.begin(), E = Macros.end(); I != E; ++I) {
1342 if (!I->second->isUsed())
1343 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001344 }
1345 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001346 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001347}
1348
1349/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001350/// the current macro expansion or token stream expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001351bool Preprocessor::HandleEndOfMacro(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001352 assert(CurMacroExpander && !CurLexer &&
1353 "Ending a macro when currently in a #include file!");
1354
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001355 // Delete or cache the now-dead macro expander.
1356 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1357 delete CurMacroExpander;
1358 else
1359 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001360
Chris Lattner69772b02006-07-02 20:34:39 +00001361 // Handle this like a #include file being popped off the stack.
1362 CurMacroExpander = 0;
1363 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001364}
1365
Chris Lattner3b5054d2008-02-07 06:03:59 +00001366/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
1367/// comment (/##/) in microsoft mode, this method handles updating the current
1368/// state, returning the token on the next source line.
1369void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
1370 assert(CurMacroExpander && !CurLexer &&
1371 "Pasted comment can only be formed from macro");
1372
1373 // We handle this by scanning for the closest real lexer, switching it to
1374 // raw mode and preprocessor mode. This will cause it to return \n as an
1375 // explicit EOM token.
1376 Lexer *FoundLexer = 0;
1377 bool LexerWasInPPMode = false;
1378 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
1379 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
1380 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
1381
1382 // Once we find a real lexer, mark it as raw mode (disabling macro
1383 // expansions) and preprocessor mode (return EOM). We know that the lexer
1384 // was *not* in raw mode before, because the macro that the comment came
1385 // from was expanded. However, it could have already been in preprocessor
1386 // mode (#if COMMENT) in which case we have to return it to that mode and
1387 // return EOM.
1388 FoundLexer = ISI.TheLexer;
1389 FoundLexer->LexingRawMode = true;
1390 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
1391 FoundLexer->ParsingPreprocessorDirective = true;
1392 break;
1393 }
1394
1395 // Okay, we either found and switched over the lexer, or we didn't find a
1396 // lexer. In either case, finish off the macro the comment came from, getting
1397 // the next token.
1398 if (!HandleEndOfMacro(Tok)) Lex(Tok);
1399
1400 // Discarding comments as long as we don't have EOF or EOM. This 'comments
1401 // out' the rest of the line, including any tokens that came from other macros
1402 // that were active, as in:
1403 // #define submacro a COMMENT b
1404 // submacro c
1405 // which should lex to 'a' only: 'b' and 'c' should be removed.
1406 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
1407 Lex(Tok);
1408
1409 // If we got an eom token, then we successfully found the end of the line.
1410 if (Tok.is(tok::eom)) {
1411 assert(FoundLexer && "Can't get end of line without an active lexer");
1412 // Restore the lexer back to normal mode instead of raw mode.
1413 FoundLexer->LexingRawMode = false;
1414
1415 // If the lexer was already in preprocessor mode, just return the EOM token
1416 // to finish the preprocessor line.
1417 if (LexerWasInPPMode) return;
1418
1419 // Otherwise, switch out of PP mode and return the next lexed token.
1420 FoundLexer->ParsingPreprocessorDirective = false;
1421 return Lex(Tok);
1422 }
1423
1424 // If we got an EOF token, then we reached the end of the token stream but
1425 // didn't find an explicit \n. This can only happen if there was no lexer
1426 // active (an active lexer would return EOM at EOF if there was no \n in
1427 // preprocessor directive mode), so just return EOF as our token.
1428 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
1429 return;
1430}
Chris Lattner22eb9722006-06-18 05:43:12 +00001431
1432//===----------------------------------------------------------------------===//
1433// Utility Methods for Preprocessor Directive Handling.
1434//===----------------------------------------------------------------------===//
1435
1436/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1437/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001438void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner146762e2007-07-20 16:59:19 +00001439 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001440 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001441 LexUnexpandedToken(Tmp);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001442 } while (Tmp.isNot(tok::eom));
Chris Lattner22eb9722006-06-18 05:43:12 +00001443}
1444
Chris Lattner652c1692006-11-21 23:47:30 +00001445/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1446static bool isCXXNamedOperator(const std::string &Spelling) {
1447 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1448 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1449 Spelling == "or" || Spelling == "xor";
1450}
1451
Chris Lattner22eb9722006-06-18 05:43:12 +00001452/// ReadMacroName - Lex and validate a macro name, which occurs after a
1453/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001454/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1455/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001456/// else (e.g. #ifdef).
Chris Lattner146762e2007-07-20 16:59:19 +00001457void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001458 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001459 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001460
1461 // Missing macro name?
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001462 if (MacroNameTok.is(tok::eom))
Chris Lattner22eb9722006-06-18 05:43:12 +00001463 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1464
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001465 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1466 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001467 std::string Spelling = getSpelling(MacroNameTok);
1468 if (isCXXNamedOperator(Spelling))
1469 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1470 // except for their spellings.
1471 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1472 else
1473 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001474 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001475 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001476 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001477 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner259716a2007-10-07 08:04:56 +00001478 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001479 getMacroInfo(II)->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001480 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001481 if (isDefineUndef == 1)
1482 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1483 else
1484 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001485 } else {
1486 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001487 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001488 }
1489
Chris Lattner22eb9722006-06-18 05:43:12 +00001490 // Invalid macro name, read and discard the rest of the line. Then set the
1491 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001492 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001493 return DiscardUntilEndOfDirective();
1494}
1495
1496/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1497/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001498void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner146762e2007-07-20 16:59:19 +00001499 Token Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001500 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001501 // There should be no tokens after the directive, but we allow them as an
1502 // extension.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001503 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001504 Lex(Tmp);
1505
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001506 if (Tmp.isNot(tok::eom)) {
Chris Lattnercb283342006-06-18 06:48:37 +00001507 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1508 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001509 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001510}
1511
1512
1513
1514/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1515/// decided that the subsequent tokens are in the #if'd out portion of the
1516/// file. Lex the rest of the file, until we see an #endif. If
1517/// FoundNonSkipPortion is true, then we have already emitted code for part of
1518/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1519/// is true, then #else directives are ok, if not, then we have already seen one
1520/// so a #else directive is a duplicate. When this returns, the caller can lex
1521/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001522void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001523 bool FoundNonSkipPortion,
1524 bool FoundElse) {
1525 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001526 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001527 "Lexing a macro, not a file?");
1528
1529 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1530 FoundNonSkipPortion, FoundElse);
1531
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001532 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1533 // disabling warnings, etc.
1534 CurLexer->LexingRawMode = true;
Chris Lattner146762e2007-07-20 16:59:19 +00001535 Token Tok;
Chris Lattner22eb9722006-06-18 05:43:12 +00001536 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001537 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001538
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001539 // If this is the end of the buffer, we have an error.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001540 if (Tok.is(tok::eof)) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001541 // Emit errors for each unterminated conditional on the stack, including
1542 // the current one.
1543 while (!CurLexer->ConditionalStack.empty()) {
1544 Diag(CurLexer->ConditionalStack.back().IfLoc,
1545 diag::err_pp_unterminated_conditional);
1546 CurLexer->ConditionalStack.pop_back();
1547 }
1548
1549 // Just return and let the caller lex after this #include.
1550 break;
1551 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001552
1553 // If this token is not a preprocessor directive, just skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001554 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Chris Lattner22eb9722006-06-18 05:43:12 +00001555 continue;
1556
1557 // We just parsed a # character at the start of a line, so we're in
1558 // directive mode. Tell the lexer this so any newlines we see will be
1559 // converted into an EOM token (this terminates the macro).
1560 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001561 CurLexer->KeepCommentMode = false;
1562
Chris Lattner22eb9722006-06-18 05:43:12 +00001563
1564 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001565 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001566
1567 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1568 // something bogus), skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001569 if (Tok.isNot(tok::identifier)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001571 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001572 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001573 continue;
1574 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001575
Chris Lattner22eb9722006-06-18 05:43:12 +00001576 // If the first letter isn't i or e, it isn't intesting to us. We know that
1577 // this is safe in the face of spelling differences, because there is no way
1578 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001579 // allows us to avoid looking up the identifier info for #define/#undef and
1580 // other common directives.
1581 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1582 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001583 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1584 FirstChar != 'i' && FirstChar != 'e') {
1585 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001586 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001587 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001588 continue;
1589 }
1590
Chris Lattnere60165f2006-06-22 06:36:29 +00001591 // Get the identifier name without trigraphs or embedded newlines. Note
1592 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1593 // when skipping.
1594 // TODO: could do this with zero copies in the no-clean case by using
1595 // strncmp below.
1596 char Directive[20];
1597 unsigned IdLen;
1598 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1599 IdLen = Tok.getLength();
1600 memcpy(Directive, RawCharData, IdLen);
1601 Directive[IdLen] = 0;
1602 } else {
1603 std::string DirectiveStr = getSpelling(Tok);
1604 IdLen = DirectiveStr.size();
1605 if (IdLen >= 20) {
1606 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001607 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001608 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001609 continue;
1610 }
1611 memcpy(Directive, &DirectiveStr[0], IdLen);
1612 Directive[IdLen] = 0;
1613 }
1614
Chris Lattner22eb9722006-06-18 05:43:12 +00001615 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001616 if ((IdLen == 2) || // "if"
1617 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1618 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001619 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1620 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001621 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001622 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001623 /*foundnonskip*/false,
1624 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001625 }
1626 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001627 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001628 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001629 PPConditionalInfo CondInfo;
1630 CondInfo.WasSkipping = true; // Silence bogus warning.
1631 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001632 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001633 assert(!InCond && "Can't be skipping if not in a conditional!");
1634
1635 // If we popped the outermost skipping block, we're done skipping!
1636 if (!CondInfo.WasSkipping)
1637 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001638 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001639 // #else directive in a skipping conditional. If not in some other
1640 // skipping conditional, and if #else hasn't already been seen, enter it
1641 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001642 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001643 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1644
1645 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001646 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001647
1648 // Note that we've seen a #else in this conditional.
1649 CondInfo.FoundElse = true;
1650
1651 // If the conditional is at the top level, and the #if block wasn't
1652 // entered, enter the #else block now.
1653 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1654 CondInfo.FoundNonSkip = true;
1655 break;
1656 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001657 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001658 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1659
1660 bool ShouldEnter;
1661 // If this is in a skipping block or if we're already handled this #if
1662 // block, don't bother parsing the condition.
1663 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001664 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001665 ShouldEnter = false;
1666 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001667 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001668 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001669 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1670 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001671 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001672 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001673 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001674 }
1675
1676 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001677 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001678
1679 // If this condition is true, enter it!
1680 if (ShouldEnter) {
1681 CondInfo.FoundNonSkip = true;
1682 break;
1683 }
1684 }
1685 }
1686
1687 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001688 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001689 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001690 }
1691
1692 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1693 // of the file, just stop skipping and return to lexing whatever came after
1694 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001695 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001696}
1697
1698//===----------------------------------------------------------------------===//
1699// Preprocessor Directive Handling.
1700//===----------------------------------------------------------------------===//
1701
1702/// HandleDirective - This callback is invoked when the lexer sees a # token
1703/// at the start of a line. This consumes the directive, modifies the
1704/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1705/// read is the correct one.
Chris Lattner146762e2007-07-20 16:59:19 +00001706void Preprocessor::HandleDirective(Token &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001707 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001708
1709 // We just parsed a # character at the start of a line, so we're in directive
1710 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001711 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001712 CurLexer->ParsingPreprocessorDirective = true;
1713
1714 ++NumDirectives;
1715
Chris Lattner371ac8a2006-07-04 07:11:10 +00001716 // We are about to read a token. For the multiple-include optimization FA to
1717 // work, we have to remember if we had read any tokens *before* this
1718 // pp-directive.
1719 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1720
Chris Lattner78186052006-07-09 00:45:31 +00001721 // Read the next token, the directive flavor. This isn't expanded due to
1722 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001723 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001724
Chris Lattner78186052006-07-09 00:45:31 +00001725 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1726 // #define A(x) #x
1727 // A(abc
1728 // #warning blah
1729 // def)
1730 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001731 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001732 Diag(Result, diag::ext_embedded_directive);
1733
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001734TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001735 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001736 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001737 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001738 case tok::comment:
1739 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1740 LexUnexpandedToken(Result);
1741 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001742
Chris Lattner22eb9722006-06-18 05:43:12 +00001743 case tok::numeric_constant:
1744 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001745 DiscardUntilEndOfDirective();
1746 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001747 default:
1748 IdentifierInfo *II = Result.getIdentifierInfo();
1749 if (II == 0) break; // Not an identifier.
1750
1751 // Ask what the preprocessor keyword ID is.
1752 switch (II->getPPKeywordID()) {
1753 default: break;
1754 // C99 6.10.1 - Conditional Inclusion.
1755 case tok::pp_if:
1756 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1757 case tok::pp_ifdef:
1758 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1759 case tok::pp_ifndef:
1760 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1761 case tok::pp_elif:
1762 return HandleElifDirective(Result);
1763 case tok::pp_else:
1764 return HandleElseDirective(Result);
1765 case tok::pp_endif:
1766 return HandleEndifDirective(Result);
1767
1768 // C99 6.10.2 - Source File Inclusion.
1769 case tok::pp_include:
1770 return HandleIncludeDirective(Result); // Handle #include.
1771
1772 // C99 6.10.3 - Macro Replacement.
1773 case tok::pp_define:
1774 return HandleDefineDirective(Result, false);
1775 case tok::pp_undef:
1776 return HandleUndefDirective(Result);
1777
1778 // C99 6.10.4 - Line Control.
1779 case tok::pp_line:
1780 // FIXME: implement #line
1781 DiscardUntilEndOfDirective();
1782 return;
1783
1784 // C99 6.10.5 - Error Directive.
1785 case tok::pp_error:
1786 return HandleUserDiagnosticDirective(Result, false);
1787
1788 // C99 6.10.6 - Pragma Directive.
1789 case tok::pp_pragma:
1790 return HandlePragmaDirective();
1791
1792 // GNU Extensions.
1793 case tok::pp_import:
1794 return HandleImportDirective(Result);
1795 case tok::pp_include_next:
1796 return HandleIncludeNextDirective(Result);
1797
1798 case tok::pp_warning:
1799 Diag(Result, diag::ext_pp_warning_directive);
1800 return HandleUserDiagnosticDirective(Result, true);
1801 case tok::pp_ident:
1802 return HandleIdentSCCSDirective(Result);
1803 case tok::pp_sccs:
1804 return HandleIdentSCCSDirective(Result);
1805 case tok::pp_assert:
1806 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001807 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001808 case tok::pp_unassert:
1809 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001810 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001811
1812 // clang extensions.
1813 case tok::pp_define_target:
1814 return HandleDefineDirective(Result, true);
1815 case tok::pp_define_other_target:
1816 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001817 }
1818 break;
1819 }
1820
1821 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001822 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001823
1824 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001825 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001826
1827 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001828}
1829
Chris Lattner146762e2007-07-20 16:59:19 +00001830void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001831 bool isWarning) {
1832 // Read the rest of the line raw. We do this because we don't want macros
1833 // to be expanded and we don't require that the tokens be valid preprocessing
1834 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1835 // collapse multiple consequtive white space between tokens, but this isn't
1836 // specified by the standard.
1837 std::string Message = CurLexer->ReadToEndOfLine();
1838
1839 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001840 return Diag(Tok, DiagID, Message);
1841}
1842
1843/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1844///
Chris Lattner146762e2007-07-20 16:59:19 +00001845void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001846 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001847 Diag(Tok, diag::ext_pp_ident_directive);
1848
Chris Lattner371ac8a2006-07-04 07:11:10 +00001849 // Read the string argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001850 Token StrTok;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001851 Lex(StrTok);
1852
1853 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001854 if (StrTok.isNot(tok::string_literal) &&
1855 StrTok.isNot(tok::wide_string_literal))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001856 return Diag(StrTok, diag::err_pp_malformed_ident);
1857
1858 // Verify that there is nothing after the string, other than EOM.
1859 CheckEndOfDirective("#ident");
1860
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001861 if (Callbacks)
1862 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001863}
1864
Chris Lattnerb8761832006-06-24 21:31:03 +00001865//===----------------------------------------------------------------------===//
1866// Preprocessor Include Directive Handling.
1867//===----------------------------------------------------------------------===//
1868
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001869/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1870/// checked and spelled filename, e.g. as an operand of #include. This returns
1871/// true if the input filename was in <>'s or false if it were in ""'s. The
1872/// caller is expected to provide a buffer that is large enough to hold the
1873/// spelling of the filename, but is also expected to handle the case when
1874/// this method decides to use a different buffer.
Chris Lattner93ab9f12007-07-23 04:15:27 +00001875bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001876 const char *&BufStart,
1877 const char *&BufEnd) {
1878 // Get the text form of the filename.
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001879 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1880
1881 // Make sure the filename is <x> or "x".
1882 bool isAngled;
1883 if (BufStart[0] == '<') {
1884 if (BufEnd[-1] != '>') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001885 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001886 BufStart = 0;
1887 return true;
1888 }
1889 isAngled = true;
1890 } else if (BufStart[0] == '"') {
1891 if (BufEnd[-1] != '"') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001892 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001893 BufStart = 0;
1894 return true;
1895 }
1896 isAngled = false;
1897 } else {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001898 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001899 BufStart = 0;
1900 return true;
1901 }
1902
1903 // Diagnose #include "" as invalid.
1904 if (BufEnd-BufStart <= 2) {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001905 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001906 BufStart = 0;
1907 return "";
1908 }
1909
1910 // Skip the brackets.
1911 ++BufStart;
1912 --BufEnd;
1913 return isAngled;
1914}
1915
Chris Lattner43eafb42007-07-23 04:56:47 +00001916/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1917/// from a macro as multiple tokens, which need to be glued together. This
1918/// occurs for code like:
1919/// #define FOO <a/b.h>
1920/// #include FOO
1921/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1922///
1923/// This code concatenates and consumes tokens up to the '>' token. It returns
1924/// false if the > was found, otherwise it returns true if it finds and consumes
1925/// the EOM marker.
1926static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1927 Preprocessor &PP) {
1928 Token CurTok;
1929
1930 PP.Lex(CurTok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001931 while (CurTok.isNot(tok::eom)) {
Chris Lattner43eafb42007-07-23 04:56:47 +00001932 // Append the spelling of this token to the buffer. If there was a space
1933 // before it, add it now.
1934 if (CurTok.hasLeadingSpace())
1935 FilenameBuffer.push_back(' ');
1936
1937 // Get the spelling of the token, directly into FilenameBuffer if possible.
1938 unsigned PreAppendSize = FilenameBuffer.size();
1939 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1940
1941 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1942 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1943
1944 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1945 if (BufPtr != &FilenameBuffer[PreAppendSize])
1946 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1947
1948 // Resize FilenameBuffer to the correct size.
1949 if (CurTok.getLength() != ActualLen)
1950 FilenameBuffer.resize(PreAppendSize+ActualLen);
1951
1952 // If we found the '>' marker, return success.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001953 if (CurTok.is(tok::greater))
Chris Lattner43eafb42007-07-23 04:56:47 +00001954 return false;
1955
1956 PP.Lex(CurTok);
1957 }
1958
1959 // If we hit the eom marker, emit an error and return true so that the caller
1960 // knows the EOM has been read.
1961 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1962 return true;
1963}
1964
Chris Lattner22eb9722006-06-18 05:43:12 +00001965/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1966/// file to be included from the lexer, then include it! This is a common
1967/// routine with functionality shared between #include, #include_next and
1968/// #import.
Chris Lattner146762e2007-07-20 16:59:19 +00001969void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001970 const DirectoryLookup *LookupFrom,
1971 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001972
Chris Lattner146762e2007-07-20 16:59:19 +00001973 Token FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001974 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001975
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001976 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001977 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner43eafb42007-07-23 04:56:47 +00001978 const char *FilenameStart, *FilenameEnd;
1979
1980 switch (FilenameTok.getKind()) {
1981 case tok::eom:
1982 // If the token kind is EOM, the error has already been diagnosed.
1983 return;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001984
Chris Lattner43eafb42007-07-23 04:56:47 +00001985 case tok::angle_string_literal:
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001986 case tok::string_literal: {
Chris Lattner43eafb42007-07-23 04:56:47 +00001987 FilenameBuffer.resize(FilenameTok.getLength());
1988 FilenameStart = &FilenameBuffer[0];
1989 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1990 FilenameEnd = FilenameStart+Len;
1991 break;
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001992 }
Chris Lattner43eafb42007-07-23 04:56:47 +00001993
1994 case tok::less:
1995 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1996 // case, glue the tokens together into FilenameBuffer and interpret those.
1997 FilenameBuffer.push_back('<');
1998 if (ConcatenateIncludeName(FilenameBuffer, *this))
1999 return; // Found <eom> but no ">"? Diagnostic already emitted.
2000 FilenameStart = &FilenameBuffer[0];
2001 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
2002 break;
2003 default:
2004 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
2005 DiscardUntilEndOfDirective();
2006 return;
2007 }
2008
Chris Lattner93ab9f12007-07-23 04:15:27 +00002009 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002010 FilenameStart, FilenameEnd);
2011 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
2012 // error.
Chris Lattner43eafb42007-07-23 04:56:47 +00002013 if (FilenameStart == 0) {
2014 DiscardUntilEndOfDirective();
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002015 return;
Chris Lattner43eafb42007-07-23 04:56:47 +00002016 }
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002017
Chris Lattner269c2322006-06-25 06:23:00 +00002018 // Verify that there is nothing after the filename, other than EOM. Use the
2019 // preprocessor to lex this in case lexing the filename entered a macro.
2020 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00002021
2022 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00002023 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00002024 return Diag(FilenameTok, diag::err_pp_include_too_deep);
2025
Chris Lattner22eb9722006-06-18 05:43:12 +00002026 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00002027 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002028 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00002029 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00002030 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00002031 return Diag(FilenameTok, diag::err_pp_file_not_found,
2032 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00002033
Chris Lattner59a9ebd2006-10-18 05:34:33 +00002034 // Ask HeaderInfo if we should enter this #include file.
2035 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
2036 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00002037 return;
2038 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002039
2040 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002041 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00002042 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00002043 return Diag(FilenameTok, diag::err_pp_file_not_found,
2044 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00002045
2046 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00002047 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00002048}
2049
2050/// HandleIncludeNextDirective - Implements #include_next.
2051///
Chris Lattner146762e2007-07-20 16:59:19 +00002052void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00002053 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00002054
2055 // #include_next is like #include, except that we start searching after
2056 // the current found directory. If we can't do this, issue a
2057 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00002058 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00002059 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002060 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00002061 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00002062 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00002063 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00002064 } else {
2065 // Start looking up in the next directory.
2066 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00002067 }
2068
2069 return HandleIncludeDirective(IncludeNextTok, Lookup);
2070}
2071
2072/// HandleImportDirective - Implements #import.
2073///
Chris Lattner146762e2007-07-20 16:59:19 +00002074void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00002075 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00002076
2077 return HandleIncludeDirective(ImportTok, 0, true);
2078}
2079
Chris Lattnerb8761832006-06-24 21:31:03 +00002080//===----------------------------------------------------------------------===//
2081// Preprocessor Macro Directive Handling.
2082//===----------------------------------------------------------------------===//
2083
Chris Lattnercefc7682006-07-08 08:28:12 +00002084/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
2085/// definition has just been read. Lex the rest of the arguments and the
2086/// closing ), updating MI with what we learn. Return true if an error occurs
2087/// parsing the arg list.
2088bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00002089 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
2090
Chris Lattner146762e2007-07-20 16:59:19 +00002091 Token Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00002092 while (1) {
2093 LexUnexpandedToken(Tok);
2094 switch (Tok.getKind()) {
2095 case tok::r_paren:
2096 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00002097 if (Arguments.empty()) { // #define FOO()
2098 MI->setArgumentList(Arguments.begin(), Arguments.end());
2099 return false;
2100 }
Chris Lattnercefc7682006-07-08 08:28:12 +00002101 // Otherwise we have #define FOO(A,)
2102 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2103 return true;
2104 case tok::ellipsis: // #define X(... -> C99 varargs
2105 // Warn if use of C99 feature in non-C99 mode.
2106 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
2107
2108 // Lex the token after the identifier.
2109 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002110 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002111 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2112 return true;
2113 }
Chris Lattner95a06b32006-07-30 08:40:43 +00002114 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00002115 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00002116 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00002117 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002118 return false;
2119 case tok::eom: // #define X(
2120 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2121 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00002122 default:
2123 // Handle keywords and identifiers here to accept things like
2124 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002125 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00002126 if (II == 0) {
2127 // #define X(1
2128 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2129 return true;
2130 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002131
2132 // If this is already used as an argument, it is used multiple times (e.g.
2133 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00002134 if (std::find(Arguments.begin(), Arguments.end(), II) !=
2135 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002136 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
2137 return true;
2138 }
2139
2140 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00002141 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00002142
2143 // Lex the token after the identifier.
2144 LexUnexpandedToken(Tok);
2145
2146 switch (Tok.getKind()) {
2147 default: // #define X(A B
2148 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2149 return true;
2150 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00002151 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002152 return false;
2153 case tok::comma: // #define X(A,
2154 break;
2155 case tok::ellipsis: // #define X(A... -> GCC extension
2156 // Diagnose extension.
2157 Diag(Tok, diag::ext_named_variadic_macro);
2158
2159 // Lex the token after the identifier.
2160 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002161 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002162 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2163 return true;
2164 }
2165
2166 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00002167 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002168 return false;
2169 }
2170 }
2171 }
2172}
2173
Chris Lattner22eb9722006-06-18 05:43:12 +00002174/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00002175/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2176/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00002177///
Chris Lattner146762e2007-07-20 16:59:19 +00002178void Preprocessor::HandleDefineDirective(Token &DefineTok,
Chris Lattner81278c62006-10-14 19:03:49 +00002179 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002180 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002181
Chris Lattner146762e2007-07-20 16:59:19 +00002182 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002183 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00002184
2185 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002186 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002187 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00002188
Chris Lattner457fc152006-07-29 06:30:25 +00002189 // If we are supposed to keep comments in #defines, reenable comment saving
2190 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00002191 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00002192
Chris Lattner063400e2006-10-14 19:54:15 +00002193 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00002194 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00002195 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00002196
Chris Lattner063400e2006-10-14 19:54:15 +00002197 // If the identifier is an 'other target' macro, clear this bit.
2198 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2199
2200
Chris Lattner146762e2007-07-20 16:59:19 +00002201 Token Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00002202 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002203
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002204 // If this is a function-like macro definition, parse the argument list,
2205 // marking each of the identifiers as being used as macro arguments. Also,
2206 // check other constraints on the first token of the macro body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002207 if (Tok.is(tok::eom)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002208 // If there is no body to this macro, we have no special handling here.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002209 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002210 // This is a function-like macro definition. Read the argument list.
2211 MI->setIsFunctionLike();
2212 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002213 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00002214 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002215 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00002216 if (CurLexer->ParsingPreprocessorDirective)
2217 DiscardUntilEndOfDirective();
2218 return;
2219 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002220
Chris Lattner815a1f92006-07-08 20:48:04 +00002221 // Read the first token after the arg list for down below.
2222 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002223 } else if (!Tok.hasLeadingSpace()) {
2224 // C99 requires whitespace between the macro definition and the body. Emit
2225 // a diagnostic for something like "#define X+".
2226 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00002227 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00002228 } else {
2229 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2230 // one in some cases!
2231 }
2232 } else {
2233 // This is a normal token with leading space. Clear the leading space
2234 // marker on the first token to get proper expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00002235 Tok.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002236 }
2237
Chris Lattner7e374832006-07-29 03:46:57 +00002238 // If this is a definition of a variadic C99 function-like macro, not using
2239 // the GNU named varargs extension, enabled __VA_ARGS__.
2240
2241 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2242 // This gets unpoisoned where it is allowed.
2243 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2244 if (MI->isC99Varargs())
2245 Ident__VA_ARGS__->setIsPoisoned(false);
2246
Chris Lattner22eb9722006-06-18 05:43:12 +00002247 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00002248 if (MI->isObjectLike()) {
2249 // Object-like macros are very simple, just read their body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002250 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002251 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002252 // Get the next token of the macro.
2253 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002254 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002255
Chris Lattnera3834342007-07-14 21:54:03 +00002256 } else {
2257 // Otherwise, read the body of a function-like macro. This has to validate
2258 // the # (stringize) operator.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002259 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002260 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002261
Chris Lattnera3834342007-07-14 21:54:03 +00002262 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2263 // parameters in function-like macro expansions.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002264 if (Tok.isNot(tok::hash)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002265 // Get the next token of the macro.
2266 LexUnexpandedToken(Tok);
2267 continue;
2268 }
2269
2270 // Get the next token of the macro.
2271 LexUnexpandedToken(Tok);
2272
2273 // Not a macro arg identifier?
2274 if (!Tok.getIdentifierInfo() ||
2275 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2276 Diag(Tok, diag::err_pp_stringize_not_parameter);
2277 delete MI;
2278
2279 // Disable __VA_ARGS__ again.
2280 Ident__VA_ARGS__->setIsPoisoned(true);
2281 return;
2282 }
2283
2284 // Things look ok, add the param name token to the macro.
2285 MI->AddTokenToBody(Tok);
2286
2287 // Get the next token of the macro.
2288 LexUnexpandedToken(Tok);
2289 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002290 }
Chris Lattner7e374832006-07-29 03:46:57 +00002291
Chris Lattnerf40fe992007-07-14 22:11:41 +00002292
Chris Lattner7e374832006-07-29 03:46:57 +00002293 // Disable __VA_ARGS__ again.
2294 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002295
Chris Lattnerbff18d52006-07-06 04:49:18 +00002296 // Check that there is no paste (##) operator at the begining or end of the
2297 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00002298 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00002299 if (NumTokens != 0) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002300 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002301 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002302 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002303 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002304 }
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002305 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002306 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002307 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002308 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002309 }
2310 }
2311
Chris Lattner13044d92006-07-03 05:16:44 +00002312 // If this is the primary source file, remember that this macro hasn't been
2313 // used yet.
2314 if (isInPrimaryFile())
2315 MI->setIsUsed(false);
2316
Chris Lattner22eb9722006-06-18 05:43:12 +00002317 // Finally, if this identifier already had a macro defined for it, verify that
2318 // the macro bodies are identical and free the old definition.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002319 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner13044d92006-07-03 05:16:44 +00002320 if (!OtherMI->isUsed())
2321 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2322
Chris Lattner22eb9722006-06-18 05:43:12 +00002323 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00002324 // must be the same. C99 6.10.3.2.
2325 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00002326 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2327 MacroNameTok.getIdentifierInfo()->getName());
2328 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2329 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002330 delete OtherMI;
2331 }
2332
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002333 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00002334}
2335
Chris Lattner063400e2006-10-14 19:54:15 +00002336/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattner146762e2007-07-20 16:59:19 +00002337void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2338 Token MacroNameTok;
Chris Lattner063400e2006-10-14 19:54:15 +00002339 ReadMacroName(MacroNameTok, 1);
2340
2341 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002342 if (MacroNameTok.is(tok::eom))
Chris Lattner063400e2006-10-14 19:54:15 +00002343 return;
2344
2345 // Check to see if this is the last token on the #undef line.
2346 CheckEndOfDirective("#define_other_target");
2347
2348 // If there is already a macro defined by this name, turn it into a
2349 // target-specific define.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002350 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner063400e2006-10-14 19:54:15 +00002351 MI->setIsTargetSpecific(true);
2352 return;
2353 }
2354
2355 // Mark the identifier as being a macro on some other target.
2356 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2357}
2358
Chris Lattner22eb9722006-06-18 05:43:12 +00002359
2360/// HandleUndefDirective - Implements #undef.
2361///
Chris Lattner146762e2007-07-20 16:59:19 +00002362void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002363 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002364
Chris Lattner146762e2007-07-20 16:59:19 +00002365 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002366 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002367
2368 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002369 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002370 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002371
2372 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002373 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002374
2375 // Okay, we finally have a valid identifier to undef.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002376 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Chris Lattner22eb9722006-06-18 05:43:12 +00002377
Chris Lattner063400e2006-10-14 19:54:15 +00002378 // #undef untaints an identifier if it were marked by define_other_target.
2379 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2380
Chris Lattner22eb9722006-06-18 05:43:12 +00002381 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002382 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002383
Chris Lattner13044d92006-07-03 05:16:44 +00002384 if (!MI->isUsed())
2385 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002386
2387 // Free macro definition.
2388 delete MI;
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002389 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002390}
2391
2392
Chris Lattnerb8761832006-06-24 21:31:03 +00002393//===----------------------------------------------------------------------===//
2394// Preprocessor Conditional Directive Handling.
2395//===----------------------------------------------------------------------===//
2396
Chris Lattner22eb9722006-06-18 05:43:12 +00002397/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002398/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2399/// if any tokens have been returned or pp-directives activated before this
2400/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002401///
Chris Lattner146762e2007-07-20 16:59:19 +00002402void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Chris Lattner371ac8a2006-07-04 07:11:10 +00002403 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002404 ++NumIf;
Chris Lattner146762e2007-07-20 16:59:19 +00002405 Token DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002406
Chris Lattner146762e2007-07-20 16:59:19 +00002407 Token MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002408 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002409
2410 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002411 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002412 // Skip code until we get to #endif. This helps with recovery by not
2413 // emitting an error when the #endif is reached.
2414 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2415 /*Foundnonskip*/false, /*FoundElse*/false);
Chris Lattnercb283342006-06-18 06:48:37 +00002416 return;
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002417 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002418
2419 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002420 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2421
2422 // If the start of a top-level #ifdef, inform MIOpt.
2423 if (!ReadAnyTokensBeforeDirective &&
2424 CurLexer->getConditionalStackDepth() == 0) {
2425 assert(isIfndef && "#ifdef shouldn't reach here");
2426 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2427 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002428
Chris Lattner063400e2006-10-14 19:54:15 +00002429 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002430 MacroInfo *MI = getMacroInfo(MII);
Chris Lattnera78a97e2006-07-03 05:42:18 +00002431
Chris Lattner81278c62006-10-14 19:03:49 +00002432 // If there is a macro, process it.
2433 if (MI) {
2434 // Mark it used.
2435 MI->setIsUsed(true);
2436
2437 // If this is the first use of a target-specific macro, warn about it.
2438 if (MI->isTargetSpecific()) {
2439 MI->setIsTargetSpecific(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00002440 getTargetInfo().DiagnoseNonPortability(
2441 getFullLoc(MacroNameTok.getLocation()),
2442 diag::port_target_macro_use);
Chris Lattner81278c62006-10-14 19:03:49 +00002443 }
Chris Lattner063400e2006-10-14 19:54:15 +00002444 } else {
2445 // Use of a target-specific macro for some other target? If so, warn.
2446 if (MII->isOtherTargetMacro()) {
2447 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00002448 getTargetInfo().DiagnoseNonPortability(
2449 getFullLoc(MacroNameTok.getLocation()),
2450 diag::port_target_macro_use);
Chris Lattner063400e2006-10-14 19:54:15 +00002451 }
Chris Lattner81278c62006-10-14 19:03:49 +00002452 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002453
Chris Lattner22eb9722006-06-18 05:43:12 +00002454 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002455 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002456 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002457 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002458 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002459 } else {
2460 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002461 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002462 /*Foundnonskip*/false,
2463 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002464 }
2465}
2466
2467/// HandleIfDirective - Implements the #if directive.
2468///
Chris Lattner146762e2007-07-20 16:59:19 +00002469void Preprocessor::HandleIfDirective(Token &IfToken,
Chris Lattnera8654ca2006-07-04 17:42:08 +00002470 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002471 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002472
Chris Lattner371ac8a2006-07-04 07:11:10 +00002473 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002474 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002475 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002476
2477 // Should we include the stuff contained by this directive?
2478 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002479 // If this condition is equivalent to #ifndef X, and if this is the first
2480 // directive seen, handle it for the multiple-include optimization.
2481 if (!ReadAnyTokensBeforeDirective &&
2482 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2483 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2484
Chris Lattner22eb9722006-06-18 05:43:12 +00002485 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002486 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002487 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002488 } else {
2489 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002490 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002491 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002492 }
2493}
2494
2495/// HandleEndifDirective - Implements the #endif directive.
2496///
Chris Lattner146762e2007-07-20 16:59:19 +00002497void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002498 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002499
Chris Lattner22eb9722006-06-18 05:43:12 +00002500 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002501 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002502
2503 PPConditionalInfo CondInfo;
2504 if (CurLexer->popConditionalLevel(CondInfo)) {
2505 // No conditionals on the stack: this is an #endif without an #if.
2506 return Diag(EndifToken, diag::err_pp_endif_without_if);
2507 }
2508
Chris Lattner371ac8a2006-07-04 07:11:10 +00002509 // If this the end of a top-level #endif, inform MIOpt.
2510 if (CurLexer->getConditionalStackDepth() == 0)
2511 CurLexer->MIOpt.ExitTopLevelConditional();
2512
Chris Lattner538d7f32006-07-20 04:31:52 +00002513 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002514 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002515}
2516
2517
Chris Lattner146762e2007-07-20 16:59:19 +00002518void Preprocessor::HandleElseDirective(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002519 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002520
Chris Lattner22eb9722006-06-18 05:43:12 +00002521 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002522 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002523
2524 PPConditionalInfo CI;
2525 if (CurLexer->popConditionalLevel(CI))
2526 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002527
2528 // If this is a top-level #else, inform the MIOpt.
2529 if (CurLexer->getConditionalStackDepth() == 0)
2530 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002531
2532 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002533 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002534
2535 // Finally, skip the rest of the contents of this block and return the first
2536 // token after it.
2537 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2538 /*FoundElse*/true);
2539}
2540
Chris Lattner146762e2007-07-20 16:59:19 +00002541void Preprocessor::HandleElifDirective(Token &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002542 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002543
Chris Lattner22eb9722006-06-18 05:43:12 +00002544 // #elif directive in a non-skipping conditional... start skipping.
2545 // We don't care what the condition is, because we will always skip it (since
2546 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002547 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002548
2549 PPConditionalInfo CI;
2550 if (CurLexer->popConditionalLevel(CI))
2551 return Diag(ElifToken, diag::pp_err_elif_without_if);
2552
Chris Lattner371ac8a2006-07-04 07:11:10 +00002553 // If this is a top-level #elif, inform the MIOpt.
2554 if (CurLexer->getConditionalStackDepth() == 0)
2555 CurLexer->MIOpt.FoundTopLevelElse();
2556
Chris Lattner22eb9722006-06-18 05:43:12 +00002557 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002558 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002559
2560 // Finally, skip the rest of the contents of this block and return the first
2561 // token after it.
2562 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2563 /*FoundElse*/CI.FoundElse);
2564}
Chris Lattnerb8761832006-06-24 21:31:03 +00002565