blob: 2fe08c6715d8aa738f986da642e94a574cb1bbcc [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=");
432 DefineBuiltinMacro(Buf, "__forceinline=");
Steve Naroff6936a082008-02-07 15:26:07 +0000433 DefineBuiltinMacro(Buf, "__int8=char");
434 DefineBuiltinMacro(Buf, "__int16=short");
435 DefineBuiltinMacro(Buf, "__int32=int");
436 DefineBuiltinMacro(Buf, "__int64=long");
Steve Naroffb2c80c72008-02-07 03:50:06 +0000437 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000438 // FIXME: Should emit a #line directive here.
439}
440
441
442/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000443/// which implicitly adds the builtin defines etc.
Ted Kremenek230bd912007-12-19 22:51:13 +0000444void Preprocessor::EnterMainSourceFile() {
445
446 unsigned MainFileID = SourceMgr.getMainFileID();
447
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000448 // Enter the main file source buffer.
449 EnterSourceFile(MainFileID, 0);
450
Chris Lattner609d4132007-11-15 19:07:47 +0000451 // Tell the header info that the main file was entered. If the file is later
452 // #imported, it won't be re-entered.
453 if (const FileEntry *FE =
454 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
455 HeaderInfo.IncrementIncludeCount(FE);
456
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000457 std::vector<char> PrologFile;
458 PrologFile.reserve(4080);
459
460 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
461 InitializePredefinedMacros(*this, PrologFile);
462
463 // Add on the predefines from the driver.
464 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
465
466 // Memory buffer must end with a null byte!
467 PrologFile.push_back(0);
468
469 // Now that we have emitted the predefined macros, #includes, etc into
470 // PrologFile, preprocess it to populate the initial preprocessor state.
471 llvm::MemoryBuffer *SB =
472 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
473 "<predefines>");
474 assert(SB && "Cannot fail to create predefined source buffer");
475 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
476 assert(FileID && "Could not create FileID for predefines?");
477
478 // Start parsing the predefines.
479 EnterSourceFile(FileID, 0);
480}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000481
Chris Lattnerd01e2912006-06-18 16:22:51 +0000482//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000483// Source File Location Methods.
484//===----------------------------------------------------------------------===//
485
Chris Lattner22eb9722006-06-18 05:43:12 +0000486/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
487/// return null on failure. isAngled indicates whether the file reference is
488/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000489const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
490 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000491 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000492 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000493 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000494 // If the header lookup mechanism may be relative to the current file, pass in
495 // info about where the current file is.
496 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000497 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000498 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
499 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000500 }
501
Chris Lattner63dd32b2006-10-20 04:42:40 +0000502 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000503 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000504 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000505 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
506 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000507 if (FE) return FE;
508
509 // Otherwise, see if this is a subframework header. If so, this is relative
510 // to one of the headers on the #include stack. Walk the list of the current
511 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000512 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner12261882008-02-01 05:34:02 +0000513 if ((CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc())))
514 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
515 CurFileEnt)))
516 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000517 }
518
519 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
520 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000521 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner12261882008-02-01 05:34:02 +0000522 if ((CurFileEnt =
523 SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc())))
524 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
525 FilenameEnd, CurFileEnt)))
526 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000527 }
528 }
529
530 // Otherwise, we really couldn't find the file.
531 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000532}
533
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000534/// isInPrimaryFile - Return true if we're in the top-level file, not in a
535/// #include.
536bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000537 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000538 return IncludeMacroStack.empty();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000539
Chris Lattner13044d92006-07-03 05:16:44 +0000540 // If there are any stacked lexers, we're in a #include.
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000541 assert(IncludeMacroStack[0].TheLexer &&
542 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
543 "Top level include stack isn't our primary lexer?");
544 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000545 if (IncludeMacroStack[i].TheLexer &&
546 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000547 return false;
548 return true;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000549}
550
551/// getCurrentLexer - Return the current file lexer being lexed from. Note
552/// that this ignores any potentially active macro expansions and _Pragma
553/// expansions going on at the time.
554Lexer *Preprocessor::getCurrentFileLexer() const {
555 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
556
557 // Look for a stacked lexer.
558 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000559 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000560 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
561 return L;
562 }
563 return 0;
564}
565
566
Chris Lattner22eb9722006-06-18 05:43:12 +0000567/// EnterSourceFile - Add a source file to the top of the include stack and
568/// start lexing tokens from it instead of the current buffer. Return true
569/// on failure.
570void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000571 const DirectoryLookup *CurDir) {
Chris Lattner69772b02006-07-02 20:34:39 +0000572 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000573 ++NumEnteredSourceFiles;
574
Chris Lattner69772b02006-07-02 20:34:39 +0000575 if (MaxIncludeStackDepth < IncludeMacroStack.size())
576 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000577
Chris Lattner77e9de52007-07-20 16:52:03 +0000578 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Chris Lattner69772b02006-07-02 20:34:39 +0000579 EnterSourceFileWithLexer(TheLexer, CurDir);
580}
Chris Lattner22eb9722006-06-18 05:43:12 +0000581
Chris Lattner69772b02006-07-02 20:34:39 +0000582/// EnterSourceFile - Add a source file to the top of the include stack and
583/// start lexing tokens from it instead of the current buffer.
584void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
585 const DirectoryLookup *CurDir) {
586
587 // Add the current lexer to the include stack.
588 if (CurLexer || CurMacroExpander)
589 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
590 CurMacroExpander));
591
592 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000593 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000594 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000595
596 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000597 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000598 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
599
600 // Get the file entry for the current file.
601 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000602 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000603 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000604
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000605 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000606 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000607 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000608}
609
Chris Lattner69772b02006-07-02 20:34:39 +0000610
611
Chris Lattner22eb9722006-06-18 05:43:12 +0000612/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000613/// tokens from it instead of the current buffer.
Chris Lattner146762e2007-07-20 16:59:19 +0000614void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000615 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
616 CurMacroExpander));
617 CurLexer = 0;
618 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000619
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000620 if (NumCachedMacroExpanders == 0) {
621 CurMacroExpander = new MacroExpander(Tok, Args, *this);
622 } else {
623 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
624 CurMacroExpander->Init(Tok, Args);
625 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000626}
627
Chris Lattner7667d0d2006-07-16 18:16:58 +0000628/// EnterTokenStream - Add a "macro" context to the top of the include stack,
629/// which will cause the lexer to start returning the specified tokens. Note
630/// that these tokens will be re-macro-expanded when/if expansion is enabled.
631/// This method assumes that the specified stream of tokens has a permanent
632/// owner somewhere, so they do not need to be copied.
Chris Lattner146762e2007-07-20 16:59:19 +0000633void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000634 // Save our current state.
635 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
636 CurMacroExpander));
637 CurLexer = 0;
638 CurDirLookup = 0;
639
640 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000641 if (NumCachedMacroExpanders == 0) {
642 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
643 } else {
644 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
645 CurMacroExpander->Init(Toks, NumToks);
646 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000647}
648
649/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
650/// lexer stack. This should only be used in situations where the current
651/// state of the top-of-stack lexer is known.
652void Preprocessor::RemoveTopOfLexerStack() {
653 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000654
655 if (CurMacroExpander) {
656 // Delete or cache the now-dead macro expander.
657 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
658 delete CurMacroExpander;
659 else
660 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
661 } else {
662 delete CurLexer;
663 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000664 CurLexer = IncludeMacroStack.back().TheLexer;
665 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
666 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
667 IncludeMacroStack.pop_back();
668}
669
Chris Lattner22eb9722006-06-18 05:43:12 +0000670//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000671// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000672//===----------------------------------------------------------------------===//
673
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000674/// setMacroInfo - Specify a macro for this identifier.
675///
676void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
677 if (MI == 0) {
678 if (II->hasMacroDefinition()) {
679 Macros.erase(II);
680 II->setHasMacroDefinition(false);
681 }
682 } else {
683 Macros[II] = MI;
684 II->setHasMacroDefinition(true);
685 }
686}
687
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000688/// RegisterBuiltinMacro - Register the specified identifier in the identifier
689/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000690IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000691 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000692 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000693
694 // Mark it as being a macro that is builtin.
695 MacroInfo *MI = new MacroInfo(SourceLocation());
696 MI->setIsBuiltinMacro();
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000697 setMacroInfo(Id, MI);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000698 return Id;
699}
700
701
Chris Lattner677757a2006-06-28 05:26:32 +0000702/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
703/// identifier table.
704void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000705 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000706 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000707 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
708 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000709 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000710
711 // GCC Extensions.
712 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
713 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000714 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000715}
716
Chris Lattnerc2395832006-07-09 00:57:04 +0000717/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
718/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000719static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000720 const IdentifierInfo *MacroIdent,
721 Preprocessor &PP) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000722 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
723
724 // If the token isn't an identifier, it's always literally expanded.
725 if (II == 0) return true;
726
727 // If the identifier is a macro, and if that macro is enabled, it may be
728 // expanded so it's not a trivial expansion.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000729 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000730 // Fast expanding "#define X X" is ok, because X would be disabled.
731 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000732 return false;
733
734 // If this is an object-like macro invocation, it is safe to trivially expand
735 // it.
736 if (MI->isObjectLike()) return true;
737
738 // If this is a function-like macro invocation, it's safe to trivially expand
739 // as long as the identifier is not a macro argument.
740 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
741 I != E; ++I)
742 if (*I == II)
743 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000744
Chris Lattnerc2395832006-07-09 00:57:04 +0000745 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000746}
747
Chris Lattnerc2395832006-07-09 00:57:04 +0000748
Chris Lattnerafe603f2006-07-11 04:02:46 +0000749/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
750/// lexed is a '('. If so, consume the token and return true, if not, this
751/// method should have no observable side-effect on the lexed tokens.
752bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000753 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000754 unsigned Val;
755 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000756 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000757 else
758 Val = CurMacroExpander->isNextTokenLParen();
759
760 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000761 // We have run off the end. If it's a source file we don't
762 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
763 // macro stack.
764 if (CurLexer)
765 return false;
766 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000767 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
768 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000769 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000770 else
771 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000772
773 if (Val != 2)
774 break;
775
776 // Ran off the end of a source file?
777 if (Entry.TheLexer)
778 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000779 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000780 }
781
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000782 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
783 // have found something that isn't a '(' or we found the end of the
784 // translation unit. In either case, return false.
785 if (Val != 1)
786 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000787
Chris Lattner146762e2007-07-20 16:59:19 +0000788 Token Tok;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000789 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000790 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000791 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000792}
Chris Lattner677757a2006-06-28 05:26:32 +0000793
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000794/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
795/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner146762e2007-07-20 16:59:19 +0000796bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000797 MacroInfo *MI) {
Chris Lattnera30be592008-01-07 19:50:27 +0000798 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
799 // then the macro could expand to different things in other contexts, we need
800 // to disable the optimization in this case.
801 if (CurLexer) CurLexer->MIOpt.ExpandedMacro();
Chris Lattner78186052006-07-09 00:45:31 +0000802
803 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
804 if (MI->isBuiltinMacro()) {
805 ExpandBuiltinMacro(Identifier);
806 return false;
807 }
808
Chris Lattner81278c62006-10-14 19:03:49 +0000809 // If this is the first use of a target-specific macro, warn about it.
810 if (MI->isTargetSpecific()) {
811 MI->setIsTargetSpecific(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +0000812 getTargetInfo().DiagnoseNonPortability(getFullLoc(Identifier.getLocation()),
Chris Lattner81278c62006-10-14 19:03:49 +0000813 diag::port_target_macro_use);
814 }
815
Chris Lattneree8760b2006-07-15 07:42:55 +0000816 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000817 /// for each macro argument, the list of tokens that were provided to the
818 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000819 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000820
821 // If this is a function-like macro, read the arguments.
822 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000823 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000824 // name isn't a '(', this macro should not be expanded. Otherwise, consume
825 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000826 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000827 return true;
828
Chris Lattner78186052006-07-09 00:45:31 +0000829 // Remember that we are now parsing the arguments to a macro invocation.
830 // Preprocessor directives used inside macro arguments are not portable, and
831 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000832 InMacroArgs = true;
833 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000834
835 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000836 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000837
838 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000839 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000840
841 ++NumFnMacroExpanded;
842 } else {
843 ++NumMacroExpanded;
844 }
Chris Lattner13044d92006-07-03 05:16:44 +0000845
846 // Notice that this macro has been used.
847 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000848
849 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000850
851 // If this macro expands to no tokens, don't bother to push it onto the
852 // expansion stack, only to take it right back off.
853 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000854 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000855 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000856
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000857 // Ignore this macro use, just return the next token in the current
858 // buffer.
859 bool HadLeadingSpace = Identifier.hasLeadingSpace();
860 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
861
862 Lex(Identifier);
863
864 // If the identifier isn't on some OTHER line, inherit the leading
865 // whitespace/first-on-a-line property of this token. This handles
866 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
867 // empty.
868 if (!Identifier.isAtStartOfLine()) {
Chris Lattner146762e2007-07-20 16:59:19 +0000869 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
870 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000871 }
872 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000873 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000874
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000875 } else if (MI->getNumTokens() == 1 &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000876 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
877 *this)){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000878 // Otherwise, if this macro expands into a single trivially-expanded
879 // token: expand it now. This handles common cases like
880 // "#define VAL 42".
881
882 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
883 // identifier to the expanded token.
884 bool isAtStartOfLine = Identifier.isAtStartOfLine();
885 bool hasLeadingSpace = Identifier.hasLeadingSpace();
886
887 // Remember where the token is instantiated.
888 SourceLocation InstantiateLoc = Identifier.getLocation();
889
890 // Replace the result token.
891 Identifier = MI->getReplacementToken(0);
892
893 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner146762e2007-07-20 16:59:19 +0000894 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
895 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000896
897 // Update the tokens location to include both its logical and physical
898 // locations.
899 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000900 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000901 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000902
Chris Lattner6e4bf522006-07-27 06:59:25 +0000903 // If this is #define X X, we must mark the result as unexpandible.
904 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000905 if (getMacroInfo(NewII) == MI)
Chris Lattner146762e2007-07-20 16:59:19 +0000906 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000907
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000908 // Since this is not an identifier token, it can't be macro expanded, so
909 // we're done.
910 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000911 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000912 }
913
Chris Lattner78186052006-07-09 00:45:31 +0000914 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000915 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000916
917 // Now that the macro is at the top of the include stack, ask the
918 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000919 Lex(Identifier);
920 return false;
921}
922
Chris Lattneree8760b2006-07-15 07:42:55 +0000923/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000924/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000925/// invocation. This returns null on error.
Chris Lattner146762e2007-07-20 16:59:19 +0000926MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattneree8760b2006-07-15 07:42:55 +0000927 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000928 // The number of fixed arguments to parse.
929 unsigned NumFixedArgsLeft = MI->getNumArgs();
930 bool isVariadic = MI->isVariadic();
931
Chris Lattner78186052006-07-09 00:45:31 +0000932 // Outer loop, while there are more arguments, keep reading them.
Chris Lattner146762e2007-07-20 16:59:19 +0000933 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000934 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000935 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000936
937 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000938 // argument is separated by an EOF token. Use a SmallVector so we can avoid
939 // heap allocations in the common case.
Chris Lattner146762e2007-07-20 16:59:19 +0000940 llvm::SmallVector<Token, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000941
942 unsigned NumActuals = 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000943 while (Tok.is(tok::comma)) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000944 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
945 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000946 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000947
Chris Lattner78186052006-07-09 00:45:31 +0000948 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000949 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
950 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000951 LexUnexpandedToken(Tok);
952
Chris Lattner97ff7762008-01-22 19:34:51 +0000953 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
Chris Lattner78186052006-07-09 00:45:31 +0000954 Diag(MacroName, diag::err_unterm_macro_invoc);
Chris Lattner97ff7762008-01-22 19:34:51 +0000955 // Do not lose the EOF/EOM. Return it to the client.
Chris Lattner78186052006-07-09 00:45:31 +0000956 MacroName = Tok;
957 return 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000958 } else if (Tok.is(tok::r_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000959 // If we found the ) token, the macro arg list is done.
960 if (NumParens-- == 0)
961 break;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000962 } else if (Tok.is(tok::l_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000963 ++NumParens;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000964 } else if (Tok.is(tok::comma) && NumParens == 0) {
Chris Lattner78186052006-07-09 00:45:31 +0000965 // Comma ends this argument if there are more fixed arguments expected.
966 if (NumFixedArgsLeft)
967 break;
968
Chris Lattner2ada5d32006-07-15 07:51:24 +0000969 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000970 if (!isVariadic) {
971 // Emit the diagnostic at the macro name in case there is a missing ).
972 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000973 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000974 return 0;
975 }
976 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000977 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000978 // If this is a comment token in the argument list and we're just in
979 // -C mode (not -CC mode), discard the comment.
980 continue;
Chris Lattner9fcdc522007-11-23 06:50:21 +0000981 } else if (Tok.is(tok::identifier)) {
982 // Reading macro arguments can cause macros that we are currently
983 // expanding from to be popped off the expansion stack. Doing so causes
984 // them to be reenabled for expansion. Here we record whether any
985 // identifiers we lex as macro arguments correspond to disabled macros.
986 // If so, we mark the token as noexpand. This is a subtle aspect of
987 // C99 6.10.3.4p2.
988 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
989 if (!MI->isEnabled())
990 Tok.setFlag(Token::DisableExpand);
Chris Lattner78186052006-07-09 00:45:31 +0000991 }
992
993 ArgTokens.push_back(Tok);
994 }
995
Chris Lattnera12dd152006-07-11 04:09:02 +0000996 // Empty arguments are standard in C99 and supported as an extension in
997 // other modes.
998 if (ArgTokens.empty() && !Features.C99)
999 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +00001000
Chris Lattner36b6e812006-07-21 06:38:30 +00001001 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001002 Token EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +00001003 EOFTok.startToken();
1004 EOFTok.setKind(tok::eof);
1005 EOFTok.setLocation(Tok.getLocation());
1006 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +00001007 ArgTokens.push_back(EOFTok);
1008 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +00001009 --NumFixedArgsLeft;
1010 };
1011
1012 // Okay, we either found the r_paren. Check to see if we parsed too few
1013 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +00001014 unsigned MinArgsExpected = MI->getNumArgs();
1015
Chris Lattner775d8322006-07-29 04:39:41 +00001016 // See MacroArgs instance var for description of this.
1017 bool isVarargsElided = false;
1018
Chris Lattner2ada5d32006-07-15 07:51:24 +00001019 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +00001020 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +00001021 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +00001022 // Varargs where the named vararg parameter is missing: ok as extension.
1023 // #define A(x, ...)
1024 // A("blah")
1025 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +00001026
1027 // Remember this occurred if this is a C99 macro invocation with at least
1028 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +00001029 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +00001030 } else if (MI->getNumArgs() == 1) {
1031 // #define A(x)
1032 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +00001033 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +00001034
1035 // Empty arguments are standard in C99 and supported as an extension in
1036 // other modes.
1037 if (ArgTokens.empty() && !Features.C99)
1038 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +00001039 } else {
1040 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +00001041 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +00001042 return 0;
1043 }
Chris Lattnere7a51302006-07-29 01:25:12 +00001044
1045 // Add a marker EOF token to the end of the token list for this argument.
1046 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +00001047 Tok.startToken();
1048 Tok.setKind(tok::eof);
1049 Tok.setLocation(EndLoc);
1050 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +00001051 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +00001052 }
1053
Chris Lattner775d8322006-07-29 04:39:41 +00001054 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +00001055}
1056
Chris Lattnerc673f902006-06-30 06:10:41 +00001057/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1058/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1059/// the identifier tokens inserted.
1060static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001061 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001062 time_t TT = time(0);
1063 struct tm *TM = localtime(&TT);
1064
1065 static const char * const Months[] = {
1066 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1067 };
1068
1069 char TmpBuffer[100];
1070 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1071 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001072 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001073
1074 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001075 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001076}
1077
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001078/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1079/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +00001080void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001081 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001082 IdentifierInfo *II = Tok.getIdentifierInfo();
1083 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +00001084
1085 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1086 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001087 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +00001088 return Handle_Pragma(Tok);
1089
Chris Lattner78186052006-07-09 00:45:31 +00001090 ++NumBuiltinMacroExpanded;
1091
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001092 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +00001093
1094 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +00001095 Tok.setIdentifierInfo(0);
Chris Lattner146762e2007-07-20 16:59:19 +00001096 Tok.clearFlag(Token::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +00001097
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001098 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001099 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001100 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001101 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001102 Tok.setKind(tok::numeric_constant);
1103 Tok.setLength(Length);
1104 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001105 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001106 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001107 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001108 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001109 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1110 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001111 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001112 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001113 }
1114 }
1115
Chris Lattner0766e592006-07-03 01:07:01 +00001116 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001117 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +00001118 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +00001119 Tok.setKind(tok::string_literal);
1120 Tok.setLength(FN.size());
1121 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001122 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001123 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001124 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001125 Tok.setKind(tok::string_literal);
1126 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1127 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001128 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001129 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001130 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001131 Tok.setKind(tok::string_literal);
1132 Tok.setLength(strlen("\"hh:mm:ss\""));
1133 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001134 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001135 Diag(Tok, diag::ext_pp_include_level);
1136
1137 // Compute the include depth of this token.
1138 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001139 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1140 for (; Loc.isValid(); ++Depth)
1141 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001142
1143 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1144 sprintf(TmpBuffer, "%u", Depth);
1145 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001146 Tok.setKind(tok::numeric_constant);
1147 Tok.setLength(Length);
1148 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001149 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +00001150 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1151 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1152 Diag(Tok, diag::ext_pp_timestamp);
1153
1154 // Get the file that we are lexing out of. If we're currently lexing from
1155 // a macro, dig into the include stack.
1156 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +00001157 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +00001158
1159 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001160 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +00001161
1162 // If this file is older than the file it depends on, emit a diagnostic.
1163 const char *Result;
1164 if (CurFile) {
1165 time_t TT = CurFile->getModificationTime();
1166 struct tm *TM = localtime(&TT);
1167 Result = asctime(TM);
1168 } else {
1169 Result = "??? ??? ?? ??:??:?? ????\n";
1170 }
1171 TmpBuffer[0] = '"';
1172 strcpy(TmpBuffer+1, Result);
1173 unsigned Len = strlen(TmpBuffer);
1174 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +00001175 Tok.setKind(tok::string_literal);
1176 Tok.setLength(Len);
1177 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001178 } else {
1179 assert(0 && "Unknown identifier!");
Chris Lattner615315f2007-12-09 20:31:55 +00001180 }
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001181}
Chris Lattner677757a2006-06-28 05:26:32 +00001182
1183//===----------------------------------------------------------------------===//
1184// Lexer Event Handling.
1185//===----------------------------------------------------------------------===//
1186
Chris Lattnercefc7682006-07-08 08:28:12 +00001187/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1188/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +00001189IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +00001190 const char *BufPtr) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001191 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattnercefc7682006-07-08 08:28:12 +00001192 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1193
1194 // Look up this token, see if it is a macro, or if it is a language keyword.
1195 IdentifierInfo *II;
1196 if (BufPtr && !Identifier.needsCleaning()) {
1197 // No cleaning needed, just use the characters from the lexed buffer.
1198 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1199 } else {
1200 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +00001201 llvm::SmallVector<char, 64> IdentifierBuffer;
1202 IdentifierBuffer.resize(Identifier.getLength());
1203 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +00001204 unsigned Size = getSpelling(Identifier, TmpBuf);
1205 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1206 }
Chris Lattner8c204872006-10-14 05:19:21 +00001207 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001208 return II;
1209}
1210
1211
Chris Lattner677757a2006-06-28 05:26:32 +00001212/// HandleIdentifier - This callback is invoked when the lexer reads an
1213/// identifier. This callback looks up the identifier in the map and/or
1214/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +00001215void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001216 assert(Identifier.getIdentifierInfo() &&
1217 "Can't handle identifiers without identifier info!");
1218
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001219 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001220
1221 // If this identifier was poisoned, and if it was not produced from a macro
1222 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001223 if (II.isPoisoned() && CurLexer) {
1224 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1225 Diag(Identifier, diag::err_pp_used_poisoned_id);
1226 else
1227 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1228 }
Chris Lattner677757a2006-06-28 05:26:32 +00001229
Chris Lattner78186052006-07-09 00:45:31 +00001230 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001231 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001232 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1233 if (MI->isEnabled()) {
1234 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1235 return;
1236 } else {
1237 // C99 6.10.3.4p2 says that a disabled macro may never again be
1238 // expanded, even if it's in a context where it could be expanded in the
1239 // future.
Chris Lattner146762e2007-07-20 16:59:19 +00001240 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001241 }
1242 }
Chris Lattner063400e2006-10-14 19:54:15 +00001243 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1244 // If this identifier is a macro on some other target, emit a diagnostic.
1245 // This diagnosic is only emitted when macro expansion is enabled, because
1246 // the macro would not have been expanded for the other target either.
1247 II.setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001248 getTargetInfo().DiagnoseNonPortability(getFullLoc(Identifier.getLocation()),
Chris Lattner063400e2006-10-14 19:54:15 +00001249 diag::port_target_macro_use);
1250
1251 }
Chris Lattner677757a2006-06-28 05:26:32 +00001252
Chris Lattner5b9f4892006-11-21 17:23:33 +00001253 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1254 // then we act as if it is the actual operator and not the textual
1255 // representation of it.
1256 if (II.isCPlusPlusOperatorKeyword())
1257 Identifier.setIdentifierInfo(0);
1258
Chris Lattner677757a2006-06-28 05:26:32 +00001259 // Change the kind of this identifier to the appropriate token kind, e.g.
1260 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001261 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001262
1263 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001264 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1265 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001266 if (II.isExtensionToken() && Features.C99)
1267 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001268}
1269
Chris Lattner22eb9722006-06-18 05:43:12 +00001270/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1271/// the current file. This either returns the EOF token or pops a level off
1272/// the include stack and keeps going.
Chris Lattner146762e2007-07-20 16:59:19 +00001273bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001274 assert(!CurMacroExpander &&
1275 "Ending a file when currently in a macro!");
1276
Chris Lattner371ac8a2006-07-04 07:11:10 +00001277 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001278 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001279 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001280 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001281 // Okay, this has a controlling macro, remember in PerFileInfo.
1282 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001283 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001284 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001285 }
1286 }
1287
Chris Lattner22eb9722006-06-18 05:43:12 +00001288 // If this is a #include'd file, pop it off the include stack and continue
1289 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001290 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001291 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001292 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001293
1294 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001295 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001296 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1297
1298 // Get the file entry for the current file.
1299 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001300 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001301 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001302
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001303 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1304 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001305 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001306
1307 // Client should lex another token.
1308 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001309 }
Chris Lattner9046dc12008-01-25 00:00:30 +00001310
1311 // If the file ends with a newline, form the EOF token on the newline itself,
1312 // rather than "on the line following it", which doesn't exist. This makes
1313 // diagnostics relating to the end of file include the last file that the user
1314 // actually typed, which is goodness.
1315 const char *EndPos = CurLexer->BufferEnd;
1316 if (EndPos != CurLexer->BufferStart &&
1317 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
1318 --EndPos;
1319
1320 // Handle \n\r and \r\n:
1321 if (EndPos != CurLexer->BufferStart &&
1322 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
1323 EndPos[-1] != EndPos[0])
1324 --EndPos;
1325 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001326
Chris Lattner8c204872006-10-14 05:19:21 +00001327 Result.startToken();
Chris Lattner9046dc12008-01-25 00:00:30 +00001328 CurLexer->BufferPtr = EndPos;
1329 CurLexer->FormTokenWithChars(Result, EndPos);
Chris Lattner8c204872006-10-14 05:19:21 +00001330 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001331
1332 // We're done with the #included file.
1333 delete CurLexer;
1334 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001335
Chris Lattner03f83482006-07-10 06:16:26 +00001336 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001337 // diagnostic is enabled, look for macros that have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001338 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001339 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1340 Macros.begin(), E = Macros.end(); I != E; ++I) {
1341 if (!I->second->isUsed())
1342 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001343 }
1344 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001345 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001346}
1347
1348/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001349/// the current macro expansion or token stream expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001350bool Preprocessor::HandleEndOfMacro(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001351 assert(CurMacroExpander && !CurLexer &&
1352 "Ending a macro when currently in a #include file!");
1353
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001354 // Delete or cache the now-dead macro expander.
1355 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1356 delete CurMacroExpander;
1357 else
1358 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001359
Chris Lattner69772b02006-07-02 20:34:39 +00001360 // Handle this like a #include file being popped off the stack.
1361 CurMacroExpander = 0;
1362 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001363}
1364
Chris Lattner3b5054d2008-02-07 06:03:59 +00001365/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
1366/// comment (/##/) in microsoft mode, this method handles updating the current
1367/// state, returning the token on the next source line.
1368void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
1369 assert(CurMacroExpander && !CurLexer &&
1370 "Pasted comment can only be formed from macro");
1371
1372 // We handle this by scanning for the closest real lexer, switching it to
1373 // raw mode and preprocessor mode. This will cause it to return \n as an
1374 // explicit EOM token.
1375 Lexer *FoundLexer = 0;
1376 bool LexerWasInPPMode = false;
1377 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
1378 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
1379 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
1380
1381 // Once we find a real lexer, mark it as raw mode (disabling macro
1382 // expansions) and preprocessor mode (return EOM). We know that the lexer
1383 // was *not* in raw mode before, because the macro that the comment came
1384 // from was expanded. However, it could have already been in preprocessor
1385 // mode (#if COMMENT) in which case we have to return it to that mode and
1386 // return EOM.
1387 FoundLexer = ISI.TheLexer;
1388 FoundLexer->LexingRawMode = true;
1389 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
1390 FoundLexer->ParsingPreprocessorDirective = true;
1391 break;
1392 }
1393
1394 // Okay, we either found and switched over the lexer, or we didn't find a
1395 // lexer. In either case, finish off the macro the comment came from, getting
1396 // the next token.
1397 if (!HandleEndOfMacro(Tok)) Lex(Tok);
1398
1399 // Discarding comments as long as we don't have EOF or EOM. This 'comments
1400 // out' the rest of the line, including any tokens that came from other macros
1401 // that were active, as in:
1402 // #define submacro a COMMENT b
1403 // submacro c
1404 // which should lex to 'a' only: 'b' and 'c' should be removed.
1405 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
1406 Lex(Tok);
1407
1408 // If we got an eom token, then we successfully found the end of the line.
1409 if (Tok.is(tok::eom)) {
1410 assert(FoundLexer && "Can't get end of line without an active lexer");
1411 // Restore the lexer back to normal mode instead of raw mode.
1412 FoundLexer->LexingRawMode = false;
1413
1414 // If the lexer was already in preprocessor mode, just return the EOM token
1415 // to finish the preprocessor line.
1416 if (LexerWasInPPMode) return;
1417
1418 // Otherwise, switch out of PP mode and return the next lexed token.
1419 FoundLexer->ParsingPreprocessorDirective = false;
1420 return Lex(Tok);
1421 }
1422
1423 // If we got an EOF token, then we reached the end of the token stream but
1424 // didn't find an explicit \n. This can only happen if there was no lexer
1425 // active (an active lexer would return EOM at EOF if there was no \n in
1426 // preprocessor directive mode), so just return EOF as our token.
1427 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
1428 return;
1429}
Chris Lattner22eb9722006-06-18 05:43:12 +00001430
1431//===----------------------------------------------------------------------===//
1432// Utility Methods for Preprocessor Directive Handling.
1433//===----------------------------------------------------------------------===//
1434
1435/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1436/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001437void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner146762e2007-07-20 16:59:19 +00001438 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001439 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001440 LexUnexpandedToken(Tmp);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001441 } while (Tmp.isNot(tok::eom));
Chris Lattner22eb9722006-06-18 05:43:12 +00001442}
1443
Chris Lattner652c1692006-11-21 23:47:30 +00001444/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1445static bool isCXXNamedOperator(const std::string &Spelling) {
1446 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1447 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1448 Spelling == "or" || Spelling == "xor";
1449}
1450
Chris Lattner22eb9722006-06-18 05:43:12 +00001451/// ReadMacroName - Lex and validate a macro name, which occurs after a
1452/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001453/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1454/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001455/// else (e.g. #ifdef).
Chris Lattner146762e2007-07-20 16:59:19 +00001456void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001457 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001458 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001459
1460 // Missing macro name?
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001461 if (MacroNameTok.is(tok::eom))
Chris Lattner22eb9722006-06-18 05:43:12 +00001462 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1463
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001464 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1465 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001466 std::string Spelling = getSpelling(MacroNameTok);
1467 if (isCXXNamedOperator(Spelling))
1468 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1469 // except for their spellings.
1470 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1471 else
1472 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001473 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001474 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001475 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001476 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner259716a2007-10-07 08:04:56 +00001477 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001478 getMacroInfo(II)->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001479 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001480 if (isDefineUndef == 1)
1481 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1482 else
1483 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001484 } else {
1485 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001486 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001487 }
1488
Chris Lattner22eb9722006-06-18 05:43:12 +00001489 // Invalid macro name, read and discard the rest of the line. Then set the
1490 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001491 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001492 return DiscardUntilEndOfDirective();
1493}
1494
1495/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1496/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001497void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner146762e2007-07-20 16:59:19 +00001498 Token Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001499 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001500 // There should be no tokens after the directive, but we allow them as an
1501 // extension.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001502 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001503 Lex(Tmp);
1504
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001505 if (Tmp.isNot(tok::eom)) {
Chris Lattnercb283342006-06-18 06:48:37 +00001506 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1507 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001508 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001509}
1510
1511
1512
1513/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1514/// decided that the subsequent tokens are in the #if'd out portion of the
1515/// file. Lex the rest of the file, until we see an #endif. If
1516/// FoundNonSkipPortion is true, then we have already emitted code for part of
1517/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1518/// is true, then #else directives are ok, if not, then we have already seen one
1519/// so a #else directive is a duplicate. When this returns, the caller can lex
1520/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001521void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001522 bool FoundNonSkipPortion,
1523 bool FoundElse) {
1524 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001525 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001526 "Lexing a macro, not a file?");
1527
1528 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1529 FoundNonSkipPortion, FoundElse);
1530
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001531 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1532 // disabling warnings, etc.
1533 CurLexer->LexingRawMode = true;
Chris Lattner146762e2007-07-20 16:59:19 +00001534 Token Tok;
Chris Lattner22eb9722006-06-18 05:43:12 +00001535 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001536 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001537
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001538 // If this is the end of the buffer, we have an error.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001539 if (Tok.is(tok::eof)) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001540 // Emit errors for each unterminated conditional on the stack, including
1541 // the current one.
1542 while (!CurLexer->ConditionalStack.empty()) {
1543 Diag(CurLexer->ConditionalStack.back().IfLoc,
1544 diag::err_pp_unterminated_conditional);
1545 CurLexer->ConditionalStack.pop_back();
1546 }
1547
1548 // Just return and let the caller lex after this #include.
1549 break;
1550 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001551
1552 // If this token is not a preprocessor directive, just skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001553 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Chris Lattner22eb9722006-06-18 05:43:12 +00001554 continue;
1555
1556 // We just parsed a # character at the start of a line, so we're in
1557 // directive mode. Tell the lexer this so any newlines we see will be
1558 // converted into an EOM token (this terminates the macro).
1559 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001560 CurLexer->KeepCommentMode = false;
1561
Chris Lattner22eb9722006-06-18 05:43:12 +00001562
1563 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001564 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001565
1566 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1567 // something bogus), skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001568 if (Tok.isNot(tok::identifier)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001569 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001570 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001571 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001572 continue;
1573 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001574
Chris Lattner22eb9722006-06-18 05:43:12 +00001575 // If the first letter isn't i or e, it isn't intesting to us. We know that
1576 // this is safe in the face of spelling differences, because there is no way
1577 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001578 // allows us to avoid looking up the identifier info for #define/#undef and
1579 // other common directives.
1580 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1581 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001582 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1583 FirstChar != 'i' && FirstChar != 'e') {
1584 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001585 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001586 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001587 continue;
1588 }
1589
Chris Lattnere60165f2006-06-22 06:36:29 +00001590 // Get the identifier name without trigraphs or embedded newlines. Note
1591 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1592 // when skipping.
1593 // TODO: could do this with zero copies in the no-clean case by using
1594 // strncmp below.
1595 char Directive[20];
1596 unsigned IdLen;
1597 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1598 IdLen = Tok.getLength();
1599 memcpy(Directive, RawCharData, IdLen);
1600 Directive[IdLen] = 0;
1601 } else {
1602 std::string DirectiveStr = getSpelling(Tok);
1603 IdLen = DirectiveStr.size();
1604 if (IdLen >= 20) {
1605 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001606 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001607 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001608 continue;
1609 }
1610 memcpy(Directive, &DirectiveStr[0], IdLen);
1611 Directive[IdLen] = 0;
1612 }
1613
Chris Lattner22eb9722006-06-18 05:43:12 +00001614 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001615 if ((IdLen == 2) || // "if"
1616 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1617 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001618 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1619 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001620 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001621 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001622 /*foundnonskip*/false,
1623 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001624 }
1625 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001626 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001627 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001628 PPConditionalInfo CondInfo;
1629 CondInfo.WasSkipping = true; // Silence bogus warning.
1630 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001631 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001632 assert(!InCond && "Can't be skipping if not in a conditional!");
1633
1634 // If we popped the outermost skipping block, we're done skipping!
1635 if (!CondInfo.WasSkipping)
1636 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001637 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001638 // #else directive in a skipping conditional. If not in some other
1639 // skipping conditional, and if #else hasn't already been seen, enter it
1640 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001641 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001642 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1643
1644 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001645 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001646
1647 // Note that we've seen a #else in this conditional.
1648 CondInfo.FoundElse = true;
1649
1650 // If the conditional is at the top level, and the #if block wasn't
1651 // entered, enter the #else block now.
1652 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1653 CondInfo.FoundNonSkip = true;
1654 break;
1655 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001656 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001657 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1658
1659 bool ShouldEnter;
1660 // If this is in a skipping block or if we're already handled this #if
1661 // block, don't bother parsing the condition.
1662 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001663 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001664 ShouldEnter = false;
1665 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001666 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001667 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001668 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1669 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001670 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001671 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001672 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001673 }
1674
1675 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001676 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001677
1678 // If this condition is true, enter it!
1679 if (ShouldEnter) {
1680 CondInfo.FoundNonSkip = true;
1681 break;
1682 }
1683 }
1684 }
1685
1686 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001687 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001688 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001689 }
1690
1691 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1692 // of the file, just stop skipping and return to lexing whatever came after
1693 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001694 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001695}
1696
1697//===----------------------------------------------------------------------===//
1698// Preprocessor Directive Handling.
1699//===----------------------------------------------------------------------===//
1700
1701/// HandleDirective - This callback is invoked when the lexer sees a # token
1702/// at the start of a line. This consumes the directive, modifies the
1703/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1704/// read is the correct one.
Chris Lattner146762e2007-07-20 16:59:19 +00001705void Preprocessor::HandleDirective(Token &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001706 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001707
1708 // We just parsed a # character at the start of a line, so we're in directive
1709 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001710 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001711 CurLexer->ParsingPreprocessorDirective = true;
1712
1713 ++NumDirectives;
1714
Chris Lattner371ac8a2006-07-04 07:11:10 +00001715 // We are about to read a token. For the multiple-include optimization FA to
1716 // work, we have to remember if we had read any tokens *before* this
1717 // pp-directive.
1718 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1719
Chris Lattner78186052006-07-09 00:45:31 +00001720 // Read the next token, the directive flavor. This isn't expanded due to
1721 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001722 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001723
Chris Lattner78186052006-07-09 00:45:31 +00001724 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1725 // #define A(x) #x
1726 // A(abc
1727 // #warning blah
1728 // def)
1729 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001730 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001731 Diag(Result, diag::ext_embedded_directive);
1732
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001733TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001734 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001735 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001736 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001737 case tok::comment:
1738 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1739 LexUnexpandedToken(Result);
1740 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001741
Chris Lattner22eb9722006-06-18 05:43:12 +00001742 case tok::numeric_constant:
1743 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001744 DiscardUntilEndOfDirective();
1745 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001746 default:
1747 IdentifierInfo *II = Result.getIdentifierInfo();
1748 if (II == 0) break; // Not an identifier.
1749
1750 // Ask what the preprocessor keyword ID is.
1751 switch (II->getPPKeywordID()) {
1752 default: break;
1753 // C99 6.10.1 - Conditional Inclusion.
1754 case tok::pp_if:
1755 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1756 case tok::pp_ifdef:
1757 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1758 case tok::pp_ifndef:
1759 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1760 case tok::pp_elif:
1761 return HandleElifDirective(Result);
1762 case tok::pp_else:
1763 return HandleElseDirective(Result);
1764 case tok::pp_endif:
1765 return HandleEndifDirective(Result);
1766
1767 // C99 6.10.2 - Source File Inclusion.
1768 case tok::pp_include:
1769 return HandleIncludeDirective(Result); // Handle #include.
1770
1771 // C99 6.10.3 - Macro Replacement.
1772 case tok::pp_define:
1773 return HandleDefineDirective(Result, false);
1774 case tok::pp_undef:
1775 return HandleUndefDirective(Result);
1776
1777 // C99 6.10.4 - Line Control.
1778 case tok::pp_line:
1779 // FIXME: implement #line
1780 DiscardUntilEndOfDirective();
1781 return;
1782
1783 // C99 6.10.5 - Error Directive.
1784 case tok::pp_error:
1785 return HandleUserDiagnosticDirective(Result, false);
1786
1787 // C99 6.10.6 - Pragma Directive.
1788 case tok::pp_pragma:
1789 return HandlePragmaDirective();
1790
1791 // GNU Extensions.
1792 case tok::pp_import:
1793 return HandleImportDirective(Result);
1794 case tok::pp_include_next:
1795 return HandleIncludeNextDirective(Result);
1796
1797 case tok::pp_warning:
1798 Diag(Result, diag::ext_pp_warning_directive);
1799 return HandleUserDiagnosticDirective(Result, true);
1800 case tok::pp_ident:
1801 return HandleIdentSCCSDirective(Result);
1802 case tok::pp_sccs:
1803 return HandleIdentSCCSDirective(Result);
1804 case tok::pp_assert:
1805 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001806 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001807 case tok::pp_unassert:
1808 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001809 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001810
1811 // clang extensions.
1812 case tok::pp_define_target:
1813 return HandleDefineDirective(Result, true);
1814 case tok::pp_define_other_target:
1815 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001816 }
1817 break;
1818 }
1819
1820 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001821 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001822
1823 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001824 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001825
1826 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001827}
1828
Chris Lattner146762e2007-07-20 16:59:19 +00001829void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001830 bool isWarning) {
1831 // Read the rest of the line raw. We do this because we don't want macros
1832 // to be expanded and we don't require that the tokens be valid preprocessing
1833 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1834 // collapse multiple consequtive white space between tokens, but this isn't
1835 // specified by the standard.
1836 std::string Message = CurLexer->ReadToEndOfLine();
1837
1838 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001839 return Diag(Tok, DiagID, Message);
1840}
1841
1842/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1843///
Chris Lattner146762e2007-07-20 16:59:19 +00001844void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001845 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001846 Diag(Tok, diag::ext_pp_ident_directive);
1847
Chris Lattner371ac8a2006-07-04 07:11:10 +00001848 // Read the string argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001849 Token StrTok;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001850 Lex(StrTok);
1851
1852 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001853 if (StrTok.isNot(tok::string_literal) &&
1854 StrTok.isNot(tok::wide_string_literal))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001855 return Diag(StrTok, diag::err_pp_malformed_ident);
1856
1857 // Verify that there is nothing after the string, other than EOM.
1858 CheckEndOfDirective("#ident");
1859
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001860 if (Callbacks)
1861 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001862}
1863
Chris Lattnerb8761832006-06-24 21:31:03 +00001864//===----------------------------------------------------------------------===//
1865// Preprocessor Include Directive Handling.
1866//===----------------------------------------------------------------------===//
1867
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001868/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1869/// checked and spelled filename, e.g. as an operand of #include. This returns
1870/// true if the input filename was in <>'s or false if it were in ""'s. The
1871/// caller is expected to provide a buffer that is large enough to hold the
1872/// spelling of the filename, but is also expected to handle the case when
1873/// this method decides to use a different buffer.
Chris Lattner93ab9f12007-07-23 04:15:27 +00001874bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001875 const char *&BufStart,
1876 const char *&BufEnd) {
1877 // Get the text form of the filename.
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001878 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1879
1880 // Make sure the filename is <x> or "x".
1881 bool isAngled;
1882 if (BufStart[0] == '<') {
1883 if (BufEnd[-1] != '>') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001884 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001885 BufStart = 0;
1886 return true;
1887 }
1888 isAngled = true;
1889 } else if (BufStart[0] == '"') {
1890 if (BufEnd[-1] != '"') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001891 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001892 BufStart = 0;
1893 return true;
1894 }
1895 isAngled = false;
1896 } else {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001897 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001898 BufStart = 0;
1899 return true;
1900 }
1901
1902 // Diagnose #include "" as invalid.
1903 if (BufEnd-BufStart <= 2) {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001904 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001905 BufStart = 0;
1906 return "";
1907 }
1908
1909 // Skip the brackets.
1910 ++BufStart;
1911 --BufEnd;
1912 return isAngled;
1913}
1914
Chris Lattner43eafb42007-07-23 04:56:47 +00001915/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1916/// from a macro as multiple tokens, which need to be glued together. This
1917/// occurs for code like:
1918/// #define FOO <a/b.h>
1919/// #include FOO
1920/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1921///
1922/// This code concatenates and consumes tokens up to the '>' token. It returns
1923/// false if the > was found, otherwise it returns true if it finds and consumes
1924/// the EOM marker.
1925static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1926 Preprocessor &PP) {
1927 Token CurTok;
1928
1929 PP.Lex(CurTok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001930 while (CurTok.isNot(tok::eom)) {
Chris Lattner43eafb42007-07-23 04:56:47 +00001931 // Append the spelling of this token to the buffer. If there was a space
1932 // before it, add it now.
1933 if (CurTok.hasLeadingSpace())
1934 FilenameBuffer.push_back(' ');
1935
1936 // Get the spelling of the token, directly into FilenameBuffer if possible.
1937 unsigned PreAppendSize = FilenameBuffer.size();
1938 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1939
1940 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1941 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1942
1943 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1944 if (BufPtr != &FilenameBuffer[PreAppendSize])
1945 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1946
1947 // Resize FilenameBuffer to the correct size.
1948 if (CurTok.getLength() != ActualLen)
1949 FilenameBuffer.resize(PreAppendSize+ActualLen);
1950
1951 // If we found the '>' marker, return success.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001952 if (CurTok.is(tok::greater))
Chris Lattner43eafb42007-07-23 04:56:47 +00001953 return false;
1954
1955 PP.Lex(CurTok);
1956 }
1957
1958 // If we hit the eom marker, emit an error and return true so that the caller
1959 // knows the EOM has been read.
1960 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1961 return true;
1962}
1963
Chris Lattner22eb9722006-06-18 05:43:12 +00001964/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1965/// file to be included from the lexer, then include it! This is a common
1966/// routine with functionality shared between #include, #include_next and
1967/// #import.
Chris Lattner146762e2007-07-20 16:59:19 +00001968void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001969 const DirectoryLookup *LookupFrom,
1970 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001971
Chris Lattner146762e2007-07-20 16:59:19 +00001972 Token FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001973 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001974
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001975 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001976 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner43eafb42007-07-23 04:56:47 +00001977 const char *FilenameStart, *FilenameEnd;
1978
1979 switch (FilenameTok.getKind()) {
1980 case tok::eom:
1981 // If the token kind is EOM, the error has already been diagnosed.
1982 return;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001983
Chris Lattner43eafb42007-07-23 04:56:47 +00001984 case tok::angle_string_literal:
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001985 case tok::string_literal: {
Chris Lattner43eafb42007-07-23 04:56:47 +00001986 FilenameBuffer.resize(FilenameTok.getLength());
1987 FilenameStart = &FilenameBuffer[0];
1988 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1989 FilenameEnd = FilenameStart+Len;
1990 break;
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001991 }
Chris Lattner43eafb42007-07-23 04:56:47 +00001992
1993 case tok::less:
1994 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1995 // case, glue the tokens together into FilenameBuffer and interpret those.
1996 FilenameBuffer.push_back('<');
1997 if (ConcatenateIncludeName(FilenameBuffer, *this))
1998 return; // Found <eom> but no ">"? Diagnostic already emitted.
1999 FilenameStart = &FilenameBuffer[0];
2000 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
2001 break;
2002 default:
2003 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
2004 DiscardUntilEndOfDirective();
2005 return;
2006 }
2007
Chris Lattner93ab9f12007-07-23 04:15:27 +00002008 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002009 FilenameStart, FilenameEnd);
2010 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
2011 // error.
Chris Lattner43eafb42007-07-23 04:56:47 +00002012 if (FilenameStart == 0) {
2013 DiscardUntilEndOfDirective();
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002014 return;
Chris Lattner43eafb42007-07-23 04:56:47 +00002015 }
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002016
Chris Lattner269c2322006-06-25 06:23:00 +00002017 // Verify that there is nothing after the filename, other than EOM. Use the
2018 // preprocessor to lex this in case lexing the filename entered a macro.
2019 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00002020
2021 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00002022 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00002023 return Diag(FilenameTok, diag::err_pp_include_too_deep);
2024
Chris Lattner22eb9722006-06-18 05:43:12 +00002025 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00002026 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002027 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00002028 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00002029 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00002030 return Diag(FilenameTok, diag::err_pp_file_not_found,
2031 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00002032
Chris Lattner59a9ebd2006-10-18 05:34:33 +00002033 // Ask HeaderInfo if we should enter this #include file.
2034 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
2035 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00002036 return;
2037 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002038
2039 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002040 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00002041 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00002042 return Diag(FilenameTok, diag::err_pp_file_not_found,
2043 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00002044
2045 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00002046 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00002047}
2048
2049/// HandleIncludeNextDirective - Implements #include_next.
2050///
Chris Lattner146762e2007-07-20 16:59:19 +00002051void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00002052 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00002053
2054 // #include_next is like #include, except that we start searching after
2055 // the current found directory. If we can't do this, issue a
2056 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00002057 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00002058 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002059 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00002060 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00002061 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00002062 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00002063 } else {
2064 // Start looking up in the next directory.
2065 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00002066 }
2067
2068 return HandleIncludeDirective(IncludeNextTok, Lookup);
2069}
2070
2071/// HandleImportDirective - Implements #import.
2072///
Chris Lattner146762e2007-07-20 16:59:19 +00002073void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00002074 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00002075
2076 return HandleIncludeDirective(ImportTok, 0, true);
2077}
2078
Chris Lattnerb8761832006-06-24 21:31:03 +00002079//===----------------------------------------------------------------------===//
2080// Preprocessor Macro Directive Handling.
2081//===----------------------------------------------------------------------===//
2082
Chris Lattnercefc7682006-07-08 08:28:12 +00002083/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
2084/// definition has just been read. Lex the rest of the arguments and the
2085/// closing ), updating MI with what we learn. Return true if an error occurs
2086/// parsing the arg list.
2087bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00002088 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
2089
Chris Lattner146762e2007-07-20 16:59:19 +00002090 Token Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00002091 while (1) {
2092 LexUnexpandedToken(Tok);
2093 switch (Tok.getKind()) {
2094 case tok::r_paren:
2095 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00002096 if (Arguments.empty()) { // #define FOO()
2097 MI->setArgumentList(Arguments.begin(), Arguments.end());
2098 return false;
2099 }
Chris Lattnercefc7682006-07-08 08:28:12 +00002100 // Otherwise we have #define FOO(A,)
2101 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2102 return true;
2103 case tok::ellipsis: // #define X(... -> C99 varargs
2104 // Warn if use of C99 feature in non-C99 mode.
2105 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
2106
2107 // Lex the token after the identifier.
2108 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002109 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002110 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2111 return true;
2112 }
Chris Lattner95a06b32006-07-30 08:40:43 +00002113 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00002114 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00002115 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00002116 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002117 return false;
2118 case tok::eom: // #define X(
2119 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2120 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00002121 default:
2122 // Handle keywords and identifiers here to accept things like
2123 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002124 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00002125 if (II == 0) {
2126 // #define X(1
2127 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2128 return true;
2129 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002130
2131 // If this is already used as an argument, it is used multiple times (e.g.
2132 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00002133 if (std::find(Arguments.begin(), Arguments.end(), II) !=
2134 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002135 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
2136 return true;
2137 }
2138
2139 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00002140 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00002141
2142 // Lex the token after the identifier.
2143 LexUnexpandedToken(Tok);
2144
2145 switch (Tok.getKind()) {
2146 default: // #define X(A B
2147 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2148 return true;
2149 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00002150 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002151 return false;
2152 case tok::comma: // #define X(A,
2153 break;
2154 case tok::ellipsis: // #define X(A... -> GCC extension
2155 // Diagnose extension.
2156 Diag(Tok, diag::ext_named_variadic_macro);
2157
2158 // Lex the token after the identifier.
2159 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002160 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002161 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2162 return true;
2163 }
2164
2165 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00002166 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002167 return false;
2168 }
2169 }
2170 }
2171}
2172
Chris Lattner22eb9722006-06-18 05:43:12 +00002173/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00002174/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2175/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00002176///
Chris Lattner146762e2007-07-20 16:59:19 +00002177void Preprocessor::HandleDefineDirective(Token &DefineTok,
Chris Lattner81278c62006-10-14 19:03:49 +00002178 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002179 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002180
Chris Lattner146762e2007-07-20 16:59:19 +00002181 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002182 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00002183
2184 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002185 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002186 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00002187
Chris Lattner457fc152006-07-29 06:30:25 +00002188 // If we are supposed to keep comments in #defines, reenable comment saving
2189 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00002190 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00002191
Chris Lattner063400e2006-10-14 19:54:15 +00002192 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00002193 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00002194 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00002195
Chris Lattner063400e2006-10-14 19:54:15 +00002196 // If the identifier is an 'other target' macro, clear this bit.
2197 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2198
2199
Chris Lattner146762e2007-07-20 16:59:19 +00002200 Token Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00002201 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002202
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002203 // If this is a function-like macro definition, parse the argument list,
2204 // marking each of the identifiers as being used as macro arguments. Also,
2205 // check other constraints on the first token of the macro body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002206 if (Tok.is(tok::eom)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002207 // If there is no body to this macro, we have no special handling here.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002208 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002209 // This is a function-like macro definition. Read the argument list.
2210 MI->setIsFunctionLike();
2211 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002212 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00002213 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002214 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00002215 if (CurLexer->ParsingPreprocessorDirective)
2216 DiscardUntilEndOfDirective();
2217 return;
2218 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002219
Chris Lattner815a1f92006-07-08 20:48:04 +00002220 // Read the first token after the arg list for down below.
2221 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002222 } else if (!Tok.hasLeadingSpace()) {
2223 // C99 requires whitespace between the macro definition and the body. Emit
2224 // a diagnostic for something like "#define X+".
2225 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00002226 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00002227 } else {
2228 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2229 // one in some cases!
2230 }
2231 } else {
2232 // This is a normal token with leading space. Clear the leading space
2233 // marker on the first token to get proper expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00002234 Tok.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002235 }
2236
Chris Lattner7e374832006-07-29 03:46:57 +00002237 // If this is a definition of a variadic C99 function-like macro, not using
2238 // the GNU named varargs extension, enabled __VA_ARGS__.
2239
2240 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2241 // This gets unpoisoned where it is allowed.
2242 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2243 if (MI->isC99Varargs())
2244 Ident__VA_ARGS__->setIsPoisoned(false);
2245
Chris Lattner22eb9722006-06-18 05:43:12 +00002246 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00002247 if (MI->isObjectLike()) {
2248 // Object-like macros are very simple, just read their body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002249 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002250 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002251 // Get the next token of the macro.
2252 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002253 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002254
Chris Lattnera3834342007-07-14 21:54:03 +00002255 } else {
2256 // Otherwise, read the body of a function-like macro. This has to validate
2257 // the # (stringize) operator.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002258 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002259 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002260
Chris Lattnera3834342007-07-14 21:54:03 +00002261 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2262 // parameters in function-like macro expansions.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002263 if (Tok.isNot(tok::hash)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002264 // Get the next token of the macro.
2265 LexUnexpandedToken(Tok);
2266 continue;
2267 }
2268
2269 // Get the next token of the macro.
2270 LexUnexpandedToken(Tok);
2271
2272 // Not a macro arg identifier?
2273 if (!Tok.getIdentifierInfo() ||
2274 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2275 Diag(Tok, diag::err_pp_stringize_not_parameter);
2276 delete MI;
2277
2278 // Disable __VA_ARGS__ again.
2279 Ident__VA_ARGS__->setIsPoisoned(true);
2280 return;
2281 }
2282
2283 // Things look ok, add the param name token to the macro.
2284 MI->AddTokenToBody(Tok);
2285
2286 // Get the next token of the macro.
2287 LexUnexpandedToken(Tok);
2288 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002289 }
Chris Lattner7e374832006-07-29 03:46:57 +00002290
Chris Lattnerf40fe992007-07-14 22:11:41 +00002291
Chris Lattner7e374832006-07-29 03:46:57 +00002292 // Disable __VA_ARGS__ again.
2293 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002294
Chris Lattnerbff18d52006-07-06 04:49:18 +00002295 // Check that there is no paste (##) operator at the begining or end of the
2296 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00002297 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00002298 if (NumTokens != 0) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002299 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002300 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002301 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002302 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002303 }
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002304 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002305 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002306 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002307 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002308 }
2309 }
2310
Chris Lattner13044d92006-07-03 05:16:44 +00002311 // If this is the primary source file, remember that this macro hasn't been
2312 // used yet.
2313 if (isInPrimaryFile())
2314 MI->setIsUsed(false);
2315
Chris Lattner22eb9722006-06-18 05:43:12 +00002316 // Finally, if this identifier already had a macro defined for it, verify that
2317 // the macro bodies are identical and free the old definition.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002318 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner13044d92006-07-03 05:16:44 +00002319 if (!OtherMI->isUsed())
2320 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2321
Chris Lattner22eb9722006-06-18 05:43:12 +00002322 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00002323 // must be the same. C99 6.10.3.2.
2324 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00002325 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2326 MacroNameTok.getIdentifierInfo()->getName());
2327 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2328 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002329 delete OtherMI;
2330 }
2331
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002332 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00002333}
2334
Chris Lattner063400e2006-10-14 19:54:15 +00002335/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattner146762e2007-07-20 16:59:19 +00002336void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2337 Token MacroNameTok;
Chris Lattner063400e2006-10-14 19:54:15 +00002338 ReadMacroName(MacroNameTok, 1);
2339
2340 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002341 if (MacroNameTok.is(tok::eom))
Chris Lattner063400e2006-10-14 19:54:15 +00002342 return;
2343
2344 // Check to see if this is the last token on the #undef line.
2345 CheckEndOfDirective("#define_other_target");
2346
2347 // If there is already a macro defined by this name, turn it into a
2348 // target-specific define.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002349 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner063400e2006-10-14 19:54:15 +00002350 MI->setIsTargetSpecific(true);
2351 return;
2352 }
2353
2354 // Mark the identifier as being a macro on some other target.
2355 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2356}
2357
Chris Lattner22eb9722006-06-18 05:43:12 +00002358
2359/// HandleUndefDirective - Implements #undef.
2360///
Chris Lattner146762e2007-07-20 16:59:19 +00002361void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002362 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002363
Chris Lattner146762e2007-07-20 16:59:19 +00002364 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002365 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002366
2367 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002368 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002369 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002370
2371 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002372 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002373
2374 // Okay, we finally have a valid identifier to undef.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002375 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Chris Lattner22eb9722006-06-18 05:43:12 +00002376
Chris Lattner063400e2006-10-14 19:54:15 +00002377 // #undef untaints an identifier if it were marked by define_other_target.
2378 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2379
Chris Lattner22eb9722006-06-18 05:43:12 +00002380 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002381 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002382
Chris Lattner13044d92006-07-03 05:16:44 +00002383 if (!MI->isUsed())
2384 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002385
2386 // Free macro definition.
2387 delete MI;
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002388 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002389}
2390
2391
Chris Lattnerb8761832006-06-24 21:31:03 +00002392//===----------------------------------------------------------------------===//
2393// Preprocessor Conditional Directive Handling.
2394//===----------------------------------------------------------------------===//
2395
Chris Lattner22eb9722006-06-18 05:43:12 +00002396/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002397/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2398/// if any tokens have been returned or pp-directives activated before this
2399/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002400///
Chris Lattner146762e2007-07-20 16:59:19 +00002401void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Chris Lattner371ac8a2006-07-04 07:11:10 +00002402 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002403 ++NumIf;
Chris Lattner146762e2007-07-20 16:59:19 +00002404 Token DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002405
Chris Lattner146762e2007-07-20 16:59:19 +00002406 Token MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002407 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002408
2409 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002410 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002411 // Skip code until we get to #endif. This helps with recovery by not
2412 // emitting an error when the #endif is reached.
2413 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2414 /*Foundnonskip*/false, /*FoundElse*/false);
Chris Lattnercb283342006-06-18 06:48:37 +00002415 return;
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002416 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002417
2418 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002419 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2420
2421 // If the start of a top-level #ifdef, inform MIOpt.
2422 if (!ReadAnyTokensBeforeDirective &&
2423 CurLexer->getConditionalStackDepth() == 0) {
2424 assert(isIfndef && "#ifdef shouldn't reach here");
2425 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2426 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002427
Chris Lattner063400e2006-10-14 19:54:15 +00002428 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002429 MacroInfo *MI = getMacroInfo(MII);
Chris Lattnera78a97e2006-07-03 05:42:18 +00002430
Chris Lattner81278c62006-10-14 19:03:49 +00002431 // If there is a macro, process it.
2432 if (MI) {
2433 // Mark it used.
2434 MI->setIsUsed(true);
2435
2436 // If this is the first use of a target-specific macro, warn about it.
2437 if (MI->isTargetSpecific()) {
2438 MI->setIsTargetSpecific(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00002439 getTargetInfo().DiagnoseNonPortability(
2440 getFullLoc(MacroNameTok.getLocation()),
2441 diag::port_target_macro_use);
Chris Lattner81278c62006-10-14 19:03:49 +00002442 }
Chris Lattner063400e2006-10-14 19:54:15 +00002443 } else {
2444 // Use of a target-specific macro for some other target? If so, warn.
2445 if (MII->isOtherTargetMacro()) {
2446 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00002447 getTargetInfo().DiagnoseNonPortability(
2448 getFullLoc(MacroNameTok.getLocation()),
2449 diag::port_target_macro_use);
Chris Lattner063400e2006-10-14 19:54:15 +00002450 }
Chris Lattner81278c62006-10-14 19:03:49 +00002451 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002452
Chris Lattner22eb9722006-06-18 05:43:12 +00002453 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002454 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002455 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002456 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002457 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002458 } else {
2459 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002460 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002461 /*Foundnonskip*/false,
2462 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002463 }
2464}
2465
2466/// HandleIfDirective - Implements the #if directive.
2467///
Chris Lattner146762e2007-07-20 16:59:19 +00002468void Preprocessor::HandleIfDirective(Token &IfToken,
Chris Lattnera8654ca2006-07-04 17:42:08 +00002469 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002470 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002471
Chris Lattner371ac8a2006-07-04 07:11:10 +00002472 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002473 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002474 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002475
2476 // Should we include the stuff contained by this directive?
2477 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002478 // If this condition is equivalent to #ifndef X, and if this is the first
2479 // directive seen, handle it for the multiple-include optimization.
2480 if (!ReadAnyTokensBeforeDirective &&
2481 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2482 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2483
Chris Lattner22eb9722006-06-18 05:43:12 +00002484 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002485 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002486 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002487 } else {
2488 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002489 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002490 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002491 }
2492}
2493
2494/// HandleEndifDirective - Implements the #endif directive.
2495///
Chris Lattner146762e2007-07-20 16:59:19 +00002496void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002497 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002498
Chris Lattner22eb9722006-06-18 05:43:12 +00002499 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002500 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002501
2502 PPConditionalInfo CondInfo;
2503 if (CurLexer->popConditionalLevel(CondInfo)) {
2504 // No conditionals on the stack: this is an #endif without an #if.
2505 return Diag(EndifToken, diag::err_pp_endif_without_if);
2506 }
2507
Chris Lattner371ac8a2006-07-04 07:11:10 +00002508 // If this the end of a top-level #endif, inform MIOpt.
2509 if (CurLexer->getConditionalStackDepth() == 0)
2510 CurLexer->MIOpt.ExitTopLevelConditional();
2511
Chris Lattner538d7f32006-07-20 04:31:52 +00002512 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002513 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002514}
2515
2516
Chris Lattner146762e2007-07-20 16:59:19 +00002517void Preprocessor::HandleElseDirective(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002518 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002519
Chris Lattner22eb9722006-06-18 05:43:12 +00002520 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002521 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002522
2523 PPConditionalInfo CI;
2524 if (CurLexer->popConditionalLevel(CI))
2525 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002526
2527 // If this is a top-level #else, inform the MIOpt.
2528 if (CurLexer->getConditionalStackDepth() == 0)
2529 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002530
2531 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002532 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002533
2534 // Finally, skip the rest of the contents of this block and return the first
2535 // token after it.
2536 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2537 /*FoundElse*/true);
2538}
2539
Chris Lattner146762e2007-07-20 16:59:19 +00002540void Preprocessor::HandleElifDirective(Token &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002541 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002542
Chris Lattner22eb9722006-06-18 05:43:12 +00002543 // #elif directive in a non-skipping conditional... start skipping.
2544 // We don't care what the condition is, because we will always skip it (since
2545 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002546 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002547
2548 PPConditionalInfo CI;
2549 if (CurLexer->popConditionalLevel(CI))
2550 return Diag(ElifToken, diag::pp_err_elif_without_if);
2551
Chris Lattner371ac8a2006-07-04 07:11:10 +00002552 // If this is a top-level #elif, inform the MIOpt.
2553 if (CurLexer->getConditionalStackDepth() == 0)
2554 CurLexer->MIOpt.FoundTopLevelElse();
2555
Chris Lattner22eb9722006-06-18 05:43:12 +00002556 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002557 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002558
2559 // Finally, skip the rest of the contents of this block and return the first
2560 // token after it.
2561 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2562 /*FoundElse*/CI.FoundElse);
2563}
Chris Lattnerb8761832006-06-24 21:31:03 +00002564