blob: a291fe35dfbabf74afc3c98d0ce9344c05ea9109 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner22eb9722006-06-18 05:43:12 +000016// -d[MDNI] - Dump various things.
17// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000029#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000030#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000031#include "clang/Lex/PPCallbacks.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000032#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000033#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000034#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000037#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000038#include "llvm/ADT/SmallVector.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000039#include "llvm/Support/MemoryBuffer.h"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +000040#include "llvm/Support/Streams.h"
Chris Lattnera2633932007-09-03 18:30:32 +000041#include <ctime>
Chris Lattner22eb9722006-06-18 05:43:12 +000042using namespace clang;
43
44//===----------------------------------------------------------------------===//
45
Chris Lattner02dffbd2006-10-14 07:50:21 +000046Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000047 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000048 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000049 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
50 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000051 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000052 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000053
Chris Lattner22eb9722006-06-18 05:43:12 +000054 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000055 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000056 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000057 NumEnteredSourceFiles = 0;
58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000059 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000060 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000061 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000062
63 // Default to discarding comments.
64 KeepComments = false;
65 KeepMacroComments = false;
66
Chris Lattner22eb9722006-06-18 05:43:12 +000067 // Macro expansion is enabled.
68 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000069 InMacroArgs = false;
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000070 NumCachedMacroExpanders = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000071
Chris Lattner8ff71992006-07-06 05:17:39 +000072 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
73 // This gets unpoisoned where it is allowed.
74 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
75
Chris Lattner1f1b0db2007-10-09 22:10:18 +000076 Predefines = 0;
77
Chris Lattnerb8761832006-06-24 21:31:03 +000078 // Initialize the pragma handlers.
79 PragmaHandlers = new PragmaNamespace(0);
80 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000081
82 // Initialize builtin macros like __LINE__ and friends.
83 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000084}
85
86Preprocessor::~Preprocessor() {
87 // Free any active lexers.
88 delete CurLexer;
89
Chris Lattner69772b02006-07-02 20:34:39 +000090 while (!IncludeMacroStack.empty()) {
91 delete IncludeMacroStack.back().TheLexer;
92 delete IncludeMacroStack.back().TheMacroExpander;
93 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000094 }
Chris Lattnerc43ddc82007-10-07 08:44:20 +000095
96 // Free any macro definitions.
97 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
98 Macros.begin(), E = Macros.end(); I != E; ++I) {
99 // Free the macro definition.
100 delete I->second;
101 I->second = 0;
102 I->first->setHasMacroDefinition(false);
103 }
Chris Lattnerb8761832006-06-24 21:31:03 +0000104
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000105 // Free any cached macro expanders.
106 for (unsigned i = 0, e = NumCachedMacroExpanders; i != e; ++i)
107 delete MacroExpanderCache[i];
108
Chris Lattnerb8761832006-06-24 21:31:03 +0000109 // Release pragma information.
110 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000111
112 // Delete the scratch buffer info.
113 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +0000114}
115
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000116PPCallbacks::~PPCallbacks() {
117}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000118
Chris Lattner22eb9722006-06-18 05:43:12 +0000119/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
Chris Lattner146762e2007-07-20 16:59:19 +0000120/// the specified Token's location, translating the token's start
Chris Lattner22eb9722006-06-18 05:43:12 +0000121/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattner36982e42007-05-16 17:49:37 +0000122void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +0000123 Diags.Report(getFullLoc(Loc), DiagID);
Chris Lattner36982e42007-05-16 17:49:37 +0000124}
125
Chris Lattnercb283342006-06-18 06:48:37 +0000126void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000127 const std::string &Msg) {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +0000128 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000129}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000130
Chris Lattner146762e2007-07-20 16:59:19 +0000131void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000132 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
133 << getSpelling(Tok) << "'";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000134
135 if (!DumpFlags) return;
Chris Lattner615315f2007-12-09 20:31:55 +0000136
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000137 llvm::cerr << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000138 if (Tok.isAtStartOfLine())
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000139 llvm::cerr << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000140 if (Tok.hasLeadingSpace())
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000141 llvm::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000142 if (Tok.isExpandDisabled())
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000143 llvm::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000144 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000145 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000146 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
147 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000148 }
Chris Lattner615315f2007-12-09 20:31:55 +0000149
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000150 llvm::cerr << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000151 DumpLocation(Tok.getLocation());
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000152 llvm::cerr << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000153}
154
155void Preprocessor::DumpLocation(SourceLocation Loc) const {
156 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000157 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
158 << SourceMgr.getLineNumber(LogLoc) << ':'
159 << SourceMgr.getLineNumber(LogLoc);
Chris Lattner615315f2007-12-09 20:31:55 +0000160
161 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
162 if (PhysLoc != LogLoc) {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000163 llvm::cerr << " <PhysLoc=";
Chris Lattner615315f2007-12-09 20:31:55 +0000164 DumpLocation(PhysLoc);
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000165 llvm::cerr << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000166 }
Chris Lattnerd01e2912006-06-18 16:22:51 +0000167}
168
169void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000170 llvm::cerr << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000171 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
172 DumpToken(MI.getReplacementToken(i));
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000173 llvm::cerr << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000174 }
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000175 llvm::cerr << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000176}
177
Chris Lattner22eb9722006-06-18 05:43:12 +0000178void Preprocessor::PrintStats() {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000179 llvm::cerr << "\n*** Preprocessor Stats:\n";
180 llvm::cerr << NumDirectives << " directives found:\n";
181 llvm::cerr << " " << NumDefined << " #define.\n";
182 llvm::cerr << " " << NumUndefined << " #undef.\n";
183 llvm::cerr << " #include/#include_next/#import:\n";
184 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
185 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
186 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
187 llvm::cerr << " " << NumElse << " #else/#elif.\n";
188 llvm::cerr << " " << NumEndif << " #endif.\n";
189 llvm::cerr << " " << NumPragma << " #pragma.\n";
190 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000191
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000192 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
193 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
194 << NumFastMacroExpanded << " on the fast path.\n";
195 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
196 << " token paste (##) operations performed, "
197 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000198}
199
200//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000201// Token Spelling
202//===----------------------------------------------------------------------===//
203
204
205/// getSpelling() - Return the 'spelling' of this token. The spelling of a
206/// token are the characters used to represent the token in the source file
207/// after trigraph expansion and escaped-newline folding. In particular, this
208/// wants to get the true, uncanonicalized, spelling of things like digraphs
209/// UCNs, etc.
Chris Lattner146762e2007-07-20 16:59:19 +0000210std::string Preprocessor::getSpelling(const Token &Tok) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000211 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
212
213 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000214 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000215 if (!Tok.needsCleaning())
216 return std::string(TokStart, TokStart+Tok.getLength());
217
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218 std::string Result;
219 Result.reserve(Tok.getLength());
220
Chris Lattneref9eae12006-07-04 22:33:12 +0000221 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000222 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
223 Ptr != End; ) {
224 unsigned CharSize;
225 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
226 Ptr += CharSize;
227 }
228 assert(Result.size() != unsigned(Tok.getLength()) &&
229 "NeedsCleaning flag set on something that didn't need cleaning!");
230 return Result;
231}
232
233/// getSpelling - This method is used to get the spelling of a token into a
234/// preallocated buffer, instead of as an std::string. The caller is required
235/// to allocate enough space for the token, which is guaranteed to be at least
236/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000237///
238/// Note that this method may do two possible things: it may either fill in
239/// the buffer specified with characters, or it may *change the input pointer*
240/// to point to a constant buffer with the data already in it (avoiding a
241/// copy). The caller is not allowed to modify the returned buffer pointer
242/// if an internal buffer is returned.
Chris Lattner146762e2007-07-20 16:59:19 +0000243unsigned Preprocessor::getSpelling(const Token &Tok,
Chris Lattneref9eae12006-07-04 22:33:12 +0000244 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000245 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
246
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000247 // If this token is an identifier, just return the string from the identifier
248 // table, which is very quick.
249 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
250 Buffer = II->getName();
Chris Lattner32e6d642007-07-22 22:50:09 +0000251
252 // Return the length of the token. If the token needed cleaning, don't
253 // include the size of the newlines or trigraphs in it.
254 if (!Tok.needsCleaning())
255 return Tok.getLength();
256 else
257 return strlen(Buffer);
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000258 }
259
260 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000261 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000262
263 // If this token contains nothing interesting, return it directly.
264 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000265 Buffer = TokStart;
266 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000267 }
268 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000269 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000270 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
271 Ptr != End; ) {
272 unsigned CharSize;
273 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
274 Ptr += CharSize;
275 }
276 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
277 "NeedsCleaning flag set on something that didn't need cleaning!");
278
279 return OutBuf-Buffer;
280}
281
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000282
283/// CreateString - Plop the specified string into a scratch buffer and return a
284/// location for it. If specified, the source location provides a source
285/// location for the token.
286SourceLocation Preprocessor::
287CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
288 if (SLoc.isValid())
289 return ScratchBuf->getToken(Buf, Len, SLoc);
290 return ScratchBuf->getToken(Buf, Len);
291}
292
293
Chris Lattner8a7003c2007-07-16 06:48:38 +0000294/// AdvanceToTokenCharacter - Given a location that specifies the start of a
295/// token, return a new location that specifies a character within the token.
296SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
297 unsigned CharNo) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000298 // If they request the first char of the token, we're trivially done. If this
299 // is a macro expansion, it doesn't make sense to point to a character within
300 // the instantiation point (the name). We could point to the source
301 // character, but without also pointing to instantiation info, this is
302 // confusing.
303 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000304
305 // Figure out how many physical characters away the specified logical
306 // character is. This needs to take into consideration newlines and
307 // trigraphs.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000308 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
309 unsigned PhysOffset = 0;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000310
311 // The usual case is that tokens don't contain anything interesting. Skip
312 // over the uninteresting characters. If a token only consists of simple
313 // chars, this method is extremely fast.
314 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000315 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000316
317 // If we have a character that may be a trigraph or escaped newline, create a
318 // lexer to parse it correctly.
Chris Lattner8a7003c2007-07-16 06:48:38 +0000319 if (CharNo != 0) {
320 // Create a lexer starting at this token position.
Chris Lattner77e9de52007-07-20 16:52:03 +0000321 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattner146762e2007-07-20 16:59:19 +0000322 Token Tok;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000323 // Skip over characters the remaining characters.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000324 const char *TokStartPtr = TokPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000325 for (; CharNo; --CharNo)
326 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000327
328 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000329 }
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000330
331 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner8a7003c2007-07-16 06:48:38 +0000332}
333
334
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000335//===----------------------------------------------------------------------===//
336// Preprocessor Initialization Methods
337//===----------------------------------------------------------------------===//
338
339// Append a #define line to Buf for Macro. Macro should be of the form XXX,
340// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
341// "#define XXX Y z W". To get a #define with no value, use "XXX=".
342static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
343 const char *Command = "#define ") {
344 Buf.insert(Buf.end(), Command, Command+strlen(Command));
345 if (const char *Equal = strchr(Macro, '=')) {
346 // Turn the = into ' '.
347 Buf.insert(Buf.end(), Macro, Equal);
348 Buf.push_back(' ');
349 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
350 } else {
351 // Push "macroname 1".
352 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
353 Buf.push_back(' ');
354 Buf.push_back('1');
355 }
356 Buf.push_back('\n');
357}
358
359
360static void InitializePredefinedMacros(Preprocessor &PP,
361 std::vector<char> &Buf) {
362 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
363 // and __DATE__ etc.
364#if 0
365 /* __STDC__ has the value 1 under normal circumstances.
366 However, if (a) we are in a system header, (b) the option
367 stdc_0_in_system_headers is true (set by target config), and
368 (c) we are not in strictly conforming mode, then it has the
369 value 0. (b) and (c) are already checked in cpp_init_builtins. */
370 //case BT_STDC:
371 if (cpp_in_system_header (pfile))
372 number = 0;
373 else
374 number = 1;
375 break;
376#endif
377 // These should all be defined in the preprocessor according to the
378 // current language configuration.
379 DefineBuiltinMacro(Buf, "__STDC__=1");
380 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
381 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
382 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
383 else if (0) // STDC94 ?
384 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
385
386 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
387 if (PP.getLangOptions().ObjC1)
388 DefineBuiltinMacro(Buf, "__OBJC__=1");
389 if (PP.getLangOptions().ObjC2)
390 DefineBuiltinMacro(Buf, "__OBJC2__=1");
Steve Naroff6d40db02007-10-31 18:42:27 +0000391
Chris Lattnered2a9eb2007-10-10 17:48:53 +0000392 // Add __builtin_va_list typedef.
393 {
394 const char *VAList = PP.getTargetInfo().getVAListDeclaration();
395 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
396 Buf.push_back('\n');
397 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000398
399 // Get the target #defines.
400 PP.getTargetInfo().getTargetDefines(Buf);
401
402 // Compiler set macros.
403 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
Steve Naroff68754c52007-11-10 18:06:36 +0000404 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1050");
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000405 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
406 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
407 DefineBuiltinMacro(Buf, "__GNUC__=4");
408 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
409 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
410 "build 5250)\"");
411
412 // Build configuration options.
413 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
414 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
415 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
416 DefineBuiltinMacro(Buf, "__PIC__=1");
417
418
419 if (PP.getLangOptions().CPlusPlus) {
420 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
421 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
422 DefineBuiltinMacro(Buf, "__GNUG__=4");
423 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
424 DefineBuiltinMacro(Buf, "__cplusplus=1");
425 DefineBuiltinMacro(Buf, "__private_extern__=extern");
426 }
Steve Naroffb2c80c72008-02-07 03:50:06 +0000427 if (PP.getLangOptions().Microsoft) {
428 DefineBuiltinMacro(Buf, "__stdcall=");
429 DefineBuiltinMacro(Buf, "__cdecl=");
430 DefineBuiltinMacro(Buf, "_cdecl=");
431 DefineBuiltinMacro(Buf, "__ptr64=");
Steve Naroff4e79d342008-02-07 23:24:32 +0000432 DefineBuiltinMacro(Buf, "__w64=");
Steve Naroffb2c80c72008-02-07 03:50:06 +0000433 DefineBuiltinMacro(Buf, "__forceinline=");
Steve Naroff6936a082008-02-07 15:26:07 +0000434 DefineBuiltinMacro(Buf, "__int8=char");
435 DefineBuiltinMacro(Buf, "__int16=short");
436 DefineBuiltinMacro(Buf, "__int32=int");
Chris Lattner00c5b282008-02-10 21:12:45 +0000437 DefineBuiltinMacro(Buf, "__int64=long long");
Steve Naroff5915777f2008-02-11 22:29:58 +0000438 DefineBuiltinMacro(Buf, "__declspec(X)=");
Steve Naroffb2c80c72008-02-07 03:50:06 +0000439 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000440 // FIXME: Should emit a #line directive here.
441}
442
443
444/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000445/// which implicitly adds the builtin defines etc.
Ted Kremenek230bd912007-12-19 22:51:13 +0000446void Preprocessor::EnterMainSourceFile() {
447
448 unsigned MainFileID = SourceMgr.getMainFileID();
449
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000450 // Enter the main file source buffer.
451 EnterSourceFile(MainFileID, 0);
452
Chris Lattner609d4132007-11-15 19:07:47 +0000453 // Tell the header info that the main file was entered. If the file is later
454 // #imported, it won't be re-entered.
455 if (const FileEntry *FE =
456 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
457 HeaderInfo.IncrementIncludeCount(FE);
458
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000459 std::vector<char> PrologFile;
460 PrologFile.reserve(4080);
461
462 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
463 InitializePredefinedMacros(*this, PrologFile);
464
465 // Add on the predefines from the driver.
466 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
467
468 // Memory buffer must end with a null byte!
469 PrologFile.push_back(0);
470
471 // Now that we have emitted the predefined macros, #includes, etc into
472 // PrologFile, preprocess it to populate the initial preprocessor state.
473 llvm::MemoryBuffer *SB =
474 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
475 "<predefines>");
476 assert(SB && "Cannot fail to create predefined source buffer");
477 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
478 assert(FileID && "Could not create FileID for predefines?");
479
480 // Start parsing the predefines.
481 EnterSourceFile(FileID, 0);
482}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000483
Chris Lattnerd01e2912006-06-18 16:22:51 +0000484//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000485// Source File Location Methods.
486//===----------------------------------------------------------------------===//
487
Chris Lattner22eb9722006-06-18 05:43:12 +0000488/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
489/// return null on failure. isAngled indicates whether the file reference is
490/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000491const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
492 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000493 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000494 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000495 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000496 // If the header lookup mechanism may be relative to the current file, pass in
497 // info about where the current file is.
498 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000499 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000500 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
501 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000502 }
503
Chris Lattner63dd32b2006-10-20 04:42:40 +0000504 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000505 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000506 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000507 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
508 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000509 if (FE) return FE;
510
511 // Otherwise, see if this is a subframework header. If so, this is relative
512 // to one of the headers on the #include stack. Walk the list of the current
513 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000514 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner12261882008-02-01 05:34:02 +0000515 if ((CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc())))
516 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
517 CurFileEnt)))
518 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000519 }
520
521 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
522 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000523 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner12261882008-02-01 05:34:02 +0000524 if ((CurFileEnt =
525 SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc())))
526 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
527 FilenameEnd, CurFileEnt)))
528 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000529 }
530 }
531
532 // Otherwise, we really couldn't find the file.
533 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000534}
535
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000536/// isInPrimaryFile - Return true if we're in the top-level file, not in a
537/// #include.
538bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000539 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000540 return IncludeMacroStack.empty();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000541
Chris Lattner13044d92006-07-03 05:16:44 +0000542 // If there are any stacked lexers, we're in a #include.
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000543 assert(IncludeMacroStack[0].TheLexer &&
544 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
545 "Top level include stack isn't our primary lexer?");
546 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000547 if (IncludeMacroStack[i].TheLexer &&
548 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000549 return false;
550 return true;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000551}
552
553/// getCurrentLexer - Return the current file lexer being lexed from. Note
554/// that this ignores any potentially active macro expansions and _Pragma
555/// expansions going on at the time.
556Lexer *Preprocessor::getCurrentFileLexer() const {
557 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
558
559 // Look for a stacked lexer.
560 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000561 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000562 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
563 return L;
564 }
565 return 0;
566}
567
568
Chris Lattner22eb9722006-06-18 05:43:12 +0000569/// EnterSourceFile - Add a source file to the top of the include stack and
570/// start lexing tokens from it instead of the current buffer. Return true
571/// on failure.
572void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000573 const DirectoryLookup *CurDir) {
Chris Lattner69772b02006-07-02 20:34:39 +0000574 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000575 ++NumEnteredSourceFiles;
576
Chris Lattner69772b02006-07-02 20:34:39 +0000577 if (MaxIncludeStackDepth < IncludeMacroStack.size())
578 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000579
Chris Lattner77e9de52007-07-20 16:52:03 +0000580 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Chris Lattner69772b02006-07-02 20:34:39 +0000581 EnterSourceFileWithLexer(TheLexer, CurDir);
582}
Chris Lattner22eb9722006-06-18 05:43:12 +0000583
Chris Lattner69772b02006-07-02 20:34:39 +0000584/// EnterSourceFile - Add a source file to the top of the include stack and
585/// start lexing tokens from it instead of the current buffer.
586void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
587 const DirectoryLookup *CurDir) {
588
589 // Add the current lexer to the include stack.
590 if (CurLexer || CurMacroExpander)
591 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
592 CurMacroExpander));
593
594 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000595 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000596 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000597
598 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000599 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000600 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
601
602 // Get the file entry for the current file.
603 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000604 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000605 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000606
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000607 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000608 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000609 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000610}
611
Chris Lattner69772b02006-07-02 20:34:39 +0000612
613
Chris Lattner22eb9722006-06-18 05:43:12 +0000614/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000615/// tokens from it instead of the current buffer.
Chris Lattner146762e2007-07-20 16:59:19 +0000616void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000617 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
618 CurMacroExpander));
619 CurLexer = 0;
620 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000621
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000622 if (NumCachedMacroExpanders == 0) {
623 CurMacroExpander = new MacroExpander(Tok, Args, *this);
624 } else {
625 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
626 CurMacroExpander->Init(Tok, Args);
627 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000628}
629
Chris Lattner7667d0d2006-07-16 18:16:58 +0000630/// EnterTokenStream - Add a "macro" context to the top of the include stack,
631/// which will cause the lexer to start returning the specified tokens. Note
632/// that these tokens will be re-macro-expanded when/if expansion is enabled.
633/// This method assumes that the specified stream of tokens has a permanent
634/// owner somewhere, so they do not need to be copied.
Chris Lattner146762e2007-07-20 16:59:19 +0000635void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000636 // Save our current state.
637 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
638 CurMacroExpander));
639 CurLexer = 0;
640 CurDirLookup = 0;
641
642 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000643 if (NumCachedMacroExpanders == 0) {
644 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
645 } else {
646 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
647 CurMacroExpander->Init(Toks, NumToks);
648 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000649}
650
651/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
652/// lexer stack. This should only be used in situations where the current
653/// state of the top-of-stack lexer is known.
654void Preprocessor::RemoveTopOfLexerStack() {
655 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000656
657 if (CurMacroExpander) {
658 // Delete or cache the now-dead macro expander.
659 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
660 delete CurMacroExpander;
661 else
662 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
663 } else {
664 delete CurLexer;
665 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000666 CurLexer = IncludeMacroStack.back().TheLexer;
667 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
668 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
669 IncludeMacroStack.pop_back();
670}
671
Chris Lattner22eb9722006-06-18 05:43:12 +0000672//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000673// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000674//===----------------------------------------------------------------------===//
675
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000676/// setMacroInfo - Specify a macro for this identifier.
677///
678void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
679 if (MI == 0) {
680 if (II->hasMacroDefinition()) {
681 Macros.erase(II);
682 II->setHasMacroDefinition(false);
683 }
684 } else {
685 Macros[II] = MI;
686 II->setHasMacroDefinition(true);
687 }
688}
689
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000690/// RegisterBuiltinMacro - Register the specified identifier in the identifier
691/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000692IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000693 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000694 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000695
696 // Mark it as being a macro that is builtin.
697 MacroInfo *MI = new MacroInfo(SourceLocation());
698 MI->setIsBuiltinMacro();
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000699 setMacroInfo(Id, MI);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000700 return Id;
701}
702
703
Chris Lattner677757a2006-06-28 05:26:32 +0000704/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
705/// identifier table.
706void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000707 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000708 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000709 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
710 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000711 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000712
713 // GCC Extensions.
714 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
715 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000716 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000717}
718
Chris Lattnerc2395832006-07-09 00:57:04 +0000719/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
720/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000721static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000722 const IdentifierInfo *MacroIdent,
723 Preprocessor &PP) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000724 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
725
726 // If the token isn't an identifier, it's always literally expanded.
727 if (II == 0) return true;
728
729 // If the identifier is a macro, and if that macro is enabled, it may be
730 // expanded so it's not a trivial expansion.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000731 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000732 // Fast expanding "#define X X" is ok, because X would be disabled.
733 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000734 return false;
735
736 // If this is an object-like macro invocation, it is safe to trivially expand
737 // it.
738 if (MI->isObjectLike()) return true;
739
740 // If this is a function-like macro invocation, it's safe to trivially expand
741 // as long as the identifier is not a macro argument.
742 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
743 I != E; ++I)
744 if (*I == II)
745 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000746
Chris Lattnerc2395832006-07-09 00:57:04 +0000747 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000748}
749
Chris Lattnerc2395832006-07-09 00:57:04 +0000750
Chris Lattnerafe603f2006-07-11 04:02:46 +0000751/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
752/// lexed is a '('. If so, consume the token and return true, if not, this
753/// method should have no observable side-effect on the lexed tokens.
754bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000755 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000756 unsigned Val;
757 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000758 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000759 else
760 Val = CurMacroExpander->isNextTokenLParen();
761
762 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000763 // We have run off the end. If it's a source file we don't
764 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
765 // macro stack.
766 if (CurLexer)
767 return false;
768 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000769 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
770 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000771 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000772 else
773 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000774
775 if (Val != 2)
776 break;
777
778 // Ran off the end of a source file?
779 if (Entry.TheLexer)
780 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000781 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000782 }
783
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000784 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
785 // have found something that isn't a '(' or we found the end of the
786 // translation unit. In either case, return false.
787 if (Val != 1)
788 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000789
Chris Lattner146762e2007-07-20 16:59:19 +0000790 Token Tok;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000791 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000792 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000793 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000794}
Chris Lattner677757a2006-06-28 05:26:32 +0000795
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000796/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
797/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner146762e2007-07-20 16:59:19 +0000798bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000799 MacroInfo *MI) {
Chris Lattnera30be592008-01-07 19:50:27 +0000800 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
801 // then the macro could expand to different things in other contexts, we need
802 // to disable the optimization in this case.
803 if (CurLexer) CurLexer->MIOpt.ExpandedMacro();
Chris Lattner78186052006-07-09 00:45:31 +0000804
805 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
806 if (MI->isBuiltinMacro()) {
807 ExpandBuiltinMacro(Identifier);
808 return false;
809 }
810
Chris Lattner81278c62006-10-14 19:03:49 +0000811 // If this is the first use of a target-specific macro, warn about it.
812 if (MI->isTargetSpecific()) {
813 MI->setIsTargetSpecific(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +0000814 getTargetInfo().DiagnoseNonPortability(getFullLoc(Identifier.getLocation()),
Chris Lattner81278c62006-10-14 19:03:49 +0000815 diag::port_target_macro_use);
816 }
817
Chris Lattneree8760b2006-07-15 07:42:55 +0000818 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000819 /// for each macro argument, the list of tokens that were provided to the
820 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000821 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000822
823 // If this is a function-like macro, read the arguments.
824 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000825 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000826 // name isn't a '(', this macro should not be expanded. Otherwise, consume
827 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000828 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000829 return true;
830
Chris Lattner78186052006-07-09 00:45:31 +0000831 // Remember that we are now parsing the arguments to a macro invocation.
832 // Preprocessor directives used inside macro arguments are not portable, and
833 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000834 InMacroArgs = true;
835 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000836
837 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000838 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000839
840 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000841 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000842
843 ++NumFnMacroExpanded;
844 } else {
845 ++NumMacroExpanded;
846 }
Chris Lattner13044d92006-07-03 05:16:44 +0000847
848 // Notice that this macro has been used.
849 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000850
851 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000852
853 // If this macro expands to no tokens, don't bother to push it onto the
854 // expansion stack, only to take it right back off.
855 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000856 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000857 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000858
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000859 // Ignore this macro use, just return the next token in the current
860 // buffer.
861 bool HadLeadingSpace = Identifier.hasLeadingSpace();
862 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
863
864 Lex(Identifier);
865
866 // If the identifier isn't on some OTHER line, inherit the leading
867 // whitespace/first-on-a-line property of this token. This handles
868 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
869 // empty.
870 if (!Identifier.isAtStartOfLine()) {
Chris Lattner146762e2007-07-20 16:59:19 +0000871 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
872 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000873 }
874 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000875 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000876
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000877 } else if (MI->getNumTokens() == 1 &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000878 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
879 *this)){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000880 // Otherwise, if this macro expands into a single trivially-expanded
881 // token: expand it now. This handles common cases like
882 // "#define VAL 42".
883
884 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
885 // identifier to the expanded token.
886 bool isAtStartOfLine = Identifier.isAtStartOfLine();
887 bool hasLeadingSpace = Identifier.hasLeadingSpace();
888
889 // Remember where the token is instantiated.
890 SourceLocation InstantiateLoc = Identifier.getLocation();
891
892 // Replace the result token.
893 Identifier = MI->getReplacementToken(0);
894
895 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner146762e2007-07-20 16:59:19 +0000896 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
897 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000898
899 // Update the tokens location to include both its logical and physical
900 // locations.
901 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000902 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000903 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000904
Chris Lattner6e4bf522006-07-27 06:59:25 +0000905 // If this is #define X X, we must mark the result as unexpandible.
906 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000907 if (getMacroInfo(NewII) == MI)
Chris Lattner146762e2007-07-20 16:59:19 +0000908 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000909
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000910 // Since this is not an identifier token, it can't be macro expanded, so
911 // we're done.
912 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000913 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000914 }
915
Chris Lattner78186052006-07-09 00:45:31 +0000916 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000917 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000918
919 // Now that the macro is at the top of the include stack, ask the
920 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000921 Lex(Identifier);
922 return false;
923}
924
Chris Lattneree8760b2006-07-15 07:42:55 +0000925/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000926/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000927/// invocation. This returns null on error.
Chris Lattner146762e2007-07-20 16:59:19 +0000928MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattneree8760b2006-07-15 07:42:55 +0000929 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000930 // The number of fixed arguments to parse.
931 unsigned NumFixedArgsLeft = MI->getNumArgs();
932 bool isVariadic = MI->isVariadic();
933
Chris Lattner78186052006-07-09 00:45:31 +0000934 // Outer loop, while there are more arguments, keep reading them.
Chris Lattner146762e2007-07-20 16:59:19 +0000935 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000936 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000937 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000938
939 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000940 // argument is separated by an EOF token. Use a SmallVector so we can avoid
941 // heap allocations in the common case.
Chris Lattner146762e2007-07-20 16:59:19 +0000942 llvm::SmallVector<Token, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000943
944 unsigned NumActuals = 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000945 while (Tok.is(tok::comma)) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000946 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
947 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000948 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000949
Chris Lattner78186052006-07-09 00:45:31 +0000950 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000951 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
952 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000953 LexUnexpandedToken(Tok);
954
Chris Lattner97ff7762008-01-22 19:34:51 +0000955 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
Chris Lattner78186052006-07-09 00:45:31 +0000956 Diag(MacroName, diag::err_unterm_macro_invoc);
Chris Lattner97ff7762008-01-22 19:34:51 +0000957 // Do not lose the EOF/EOM. Return it to the client.
Chris Lattner78186052006-07-09 00:45:31 +0000958 MacroName = Tok;
959 return 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000960 } else if (Tok.is(tok::r_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000961 // If we found the ) token, the macro arg list is done.
962 if (NumParens-- == 0)
963 break;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000964 } else if (Tok.is(tok::l_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000965 ++NumParens;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000966 } else if (Tok.is(tok::comma) && NumParens == 0) {
Chris Lattner78186052006-07-09 00:45:31 +0000967 // Comma ends this argument if there are more fixed arguments expected.
968 if (NumFixedArgsLeft)
969 break;
970
Chris Lattner2ada5d32006-07-15 07:51:24 +0000971 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000972 if (!isVariadic) {
973 // Emit the diagnostic at the macro name in case there is a missing ).
974 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000975 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000976 return 0;
977 }
978 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000979 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000980 // If this is a comment token in the argument list and we're just in
981 // -C mode (not -CC mode), discard the comment.
982 continue;
Chris Lattner9fcdc522007-11-23 06:50:21 +0000983 } else if (Tok.is(tok::identifier)) {
984 // Reading macro arguments can cause macros that we are currently
985 // expanding from to be popped off the expansion stack. Doing so causes
986 // them to be reenabled for expansion. Here we record whether any
987 // identifiers we lex as macro arguments correspond to disabled macros.
988 // If so, we mark the token as noexpand. This is a subtle aspect of
989 // C99 6.10.3.4p2.
990 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
991 if (!MI->isEnabled())
992 Tok.setFlag(Token::DisableExpand);
Chris Lattner78186052006-07-09 00:45:31 +0000993 }
994
995 ArgTokens.push_back(Tok);
996 }
997
Chris Lattnera12dd152006-07-11 04:09:02 +0000998 // Empty arguments are standard in C99 and supported as an extension in
999 // other modes.
1000 if (ArgTokens.empty() && !Features.C99)
1001 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +00001002
Chris Lattner36b6e812006-07-21 06:38:30 +00001003 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001004 Token EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +00001005 EOFTok.startToken();
1006 EOFTok.setKind(tok::eof);
1007 EOFTok.setLocation(Tok.getLocation());
1008 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +00001009 ArgTokens.push_back(EOFTok);
1010 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +00001011 --NumFixedArgsLeft;
1012 };
1013
1014 // Okay, we either found the r_paren. Check to see if we parsed too few
1015 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +00001016 unsigned MinArgsExpected = MI->getNumArgs();
1017
Chris Lattner775d8322006-07-29 04:39:41 +00001018 // See MacroArgs instance var for description of this.
1019 bool isVarargsElided = false;
1020
Chris Lattner2ada5d32006-07-15 07:51:24 +00001021 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +00001022 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +00001023 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +00001024 // Varargs where the named vararg parameter is missing: ok as extension.
1025 // #define A(x, ...)
1026 // A("blah")
1027 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +00001028
1029 // Remember this occurred if this is a C99 macro invocation with at least
1030 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +00001031 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +00001032 } else if (MI->getNumArgs() == 1) {
1033 // #define A(x)
1034 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +00001035 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +00001036
1037 // Empty arguments are standard in C99 and supported as an extension in
1038 // other modes.
1039 if (ArgTokens.empty() && !Features.C99)
1040 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +00001041 } else {
1042 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +00001043 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +00001044 return 0;
1045 }
Chris Lattnere7a51302006-07-29 01:25:12 +00001046
1047 // Add a marker EOF token to the end of the token list for this argument.
1048 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +00001049 Tok.startToken();
1050 Tok.setKind(tok::eof);
1051 Tok.setLocation(EndLoc);
1052 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +00001053 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +00001054 }
1055
Chris Lattner775d8322006-07-29 04:39:41 +00001056 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +00001057}
1058
Chris Lattnerc673f902006-06-30 06:10:41 +00001059/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1060/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1061/// the identifier tokens inserted.
1062static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001063 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001064 time_t TT = time(0);
1065 struct tm *TM = localtime(&TT);
1066
1067 static const char * const Months[] = {
1068 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1069 };
1070
1071 char TmpBuffer[100];
1072 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1073 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001074 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001075
1076 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001077 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001078}
1079
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001080/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1081/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +00001082void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001083 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001084 IdentifierInfo *II = Tok.getIdentifierInfo();
1085 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +00001086
1087 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1088 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001089 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +00001090 return Handle_Pragma(Tok);
1091
Chris Lattner78186052006-07-09 00:45:31 +00001092 ++NumBuiltinMacroExpanded;
1093
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001094 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +00001095
1096 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +00001097 Tok.setIdentifierInfo(0);
Chris Lattner146762e2007-07-20 16:59:19 +00001098 Tok.clearFlag(Token::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +00001099
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001100 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001101 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001102 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001103 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001104 Tok.setKind(tok::numeric_constant);
1105 Tok.setLength(Length);
1106 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001107 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001108 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001109 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001110 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001111 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1112 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001113 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001114 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001115 }
1116 }
1117
Chris Lattner0766e592006-07-03 01:07:01 +00001118 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001119 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +00001120 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +00001121 Tok.setKind(tok::string_literal);
1122 Tok.setLength(FN.size());
1123 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001124 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001125 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001126 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001127 Tok.setKind(tok::string_literal);
1128 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1129 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001130 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001131 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001132 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001133 Tok.setKind(tok::string_literal);
1134 Tok.setLength(strlen("\"hh:mm:ss\""));
1135 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001136 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001137 Diag(Tok, diag::ext_pp_include_level);
1138
1139 // Compute the include depth of this token.
1140 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001141 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1142 for (; Loc.isValid(); ++Depth)
1143 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001144
1145 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1146 sprintf(TmpBuffer, "%u", Depth);
1147 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001148 Tok.setKind(tok::numeric_constant);
1149 Tok.setLength(Length);
1150 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001151 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +00001152 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1153 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1154 Diag(Tok, diag::ext_pp_timestamp);
1155
1156 // Get the file that we are lexing out of. If we're currently lexing from
1157 // a macro, dig into the include stack.
1158 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +00001159 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +00001160
1161 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001162 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +00001163
1164 // If this file is older than the file it depends on, emit a diagnostic.
1165 const char *Result;
1166 if (CurFile) {
1167 time_t TT = CurFile->getModificationTime();
1168 struct tm *TM = localtime(&TT);
1169 Result = asctime(TM);
1170 } else {
1171 Result = "??? ??? ?? ??:??:?? ????\n";
1172 }
1173 TmpBuffer[0] = '"';
1174 strcpy(TmpBuffer+1, Result);
1175 unsigned Len = strlen(TmpBuffer);
1176 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +00001177 Tok.setKind(tok::string_literal);
1178 Tok.setLength(Len);
1179 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001180 } else {
1181 assert(0 && "Unknown identifier!");
Chris Lattner615315f2007-12-09 20:31:55 +00001182 }
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001183}
Chris Lattner677757a2006-06-28 05:26:32 +00001184
1185//===----------------------------------------------------------------------===//
1186// Lexer Event Handling.
1187//===----------------------------------------------------------------------===//
1188
Chris Lattnercefc7682006-07-08 08:28:12 +00001189/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1190/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +00001191IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +00001192 const char *BufPtr) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001193 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattnercefc7682006-07-08 08:28:12 +00001194 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1195
1196 // Look up this token, see if it is a macro, or if it is a language keyword.
1197 IdentifierInfo *II;
1198 if (BufPtr && !Identifier.needsCleaning()) {
1199 // No cleaning needed, just use the characters from the lexed buffer.
1200 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1201 } else {
1202 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +00001203 llvm::SmallVector<char, 64> IdentifierBuffer;
1204 IdentifierBuffer.resize(Identifier.getLength());
1205 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +00001206 unsigned Size = getSpelling(Identifier, TmpBuf);
1207 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1208 }
Chris Lattner8c204872006-10-14 05:19:21 +00001209 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001210 return II;
1211}
1212
1213
Chris Lattner677757a2006-06-28 05:26:32 +00001214/// HandleIdentifier - This callback is invoked when the lexer reads an
1215/// identifier. This callback looks up the identifier in the map and/or
1216/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +00001217void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001218 assert(Identifier.getIdentifierInfo() &&
1219 "Can't handle identifiers without identifier info!");
1220
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001221 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001222
1223 // If this identifier was poisoned, and if it was not produced from a macro
1224 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001225 if (II.isPoisoned() && CurLexer) {
1226 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1227 Diag(Identifier, diag::err_pp_used_poisoned_id);
1228 else
1229 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1230 }
Chris Lattner677757a2006-06-28 05:26:32 +00001231
Chris Lattner78186052006-07-09 00:45:31 +00001232 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001233 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001234 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1235 if (MI->isEnabled()) {
1236 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1237 return;
1238 } else {
1239 // C99 6.10.3.4p2 says that a disabled macro may never again be
1240 // expanded, even if it's in a context where it could be expanded in the
1241 // future.
Chris Lattner146762e2007-07-20 16:59:19 +00001242 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001243 }
1244 }
Chris Lattner063400e2006-10-14 19:54:15 +00001245 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1246 // If this identifier is a macro on some other target, emit a diagnostic.
1247 // This diagnosic is only emitted when macro expansion is enabled, because
1248 // the macro would not have been expanded for the other target either.
1249 II.setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001250 getTargetInfo().DiagnoseNonPortability(getFullLoc(Identifier.getLocation()),
Chris Lattner063400e2006-10-14 19:54:15 +00001251 diag::port_target_macro_use);
1252
1253 }
Chris Lattner677757a2006-06-28 05:26:32 +00001254
Chris Lattner5b9f4892006-11-21 17:23:33 +00001255 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1256 // then we act as if it is the actual operator and not the textual
1257 // representation of it.
1258 if (II.isCPlusPlusOperatorKeyword())
1259 Identifier.setIdentifierInfo(0);
1260
Chris Lattner677757a2006-06-28 05:26:32 +00001261 // Change the kind of this identifier to the appropriate token kind, e.g.
1262 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001263 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001264
1265 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001266 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1267 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001268 if (II.isExtensionToken() && Features.C99)
1269 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001270}
1271
Chris Lattner22eb9722006-06-18 05:43:12 +00001272/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1273/// the current file. This either returns the EOF token or pops a level off
1274/// the include stack and keeps going.
Chris Lattner146762e2007-07-20 16:59:19 +00001275bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001276 assert(!CurMacroExpander &&
1277 "Ending a file when currently in a macro!");
1278
Chris Lattner371ac8a2006-07-04 07:11:10 +00001279 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001280 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001281 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001282 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001283 // Okay, this has a controlling macro, remember in PerFileInfo.
1284 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001285 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001286 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001287 }
1288 }
1289
Chris Lattner22eb9722006-06-18 05:43:12 +00001290 // If this is a #include'd file, pop it off the include stack and continue
1291 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001292 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001293 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001294 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001295
1296 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001297 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001298 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1299
1300 // Get the file entry for the current file.
1301 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001302 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001303 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001304
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001305 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1306 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001307 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001308
1309 // Client should lex another token.
1310 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001311 }
Chris Lattner9046dc12008-01-25 00:00:30 +00001312
1313 // If the file ends with a newline, form the EOF token on the newline itself,
1314 // rather than "on the line following it", which doesn't exist. This makes
1315 // diagnostics relating to the end of file include the last file that the user
1316 // actually typed, which is goodness.
1317 const char *EndPos = CurLexer->BufferEnd;
1318 if (EndPos != CurLexer->BufferStart &&
1319 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
1320 --EndPos;
1321
1322 // Handle \n\r and \r\n:
1323 if (EndPos != CurLexer->BufferStart &&
1324 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
1325 EndPos[-1] != EndPos[0])
1326 --EndPos;
1327 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001328
Chris Lattner8c204872006-10-14 05:19:21 +00001329 Result.startToken();
Chris Lattner9046dc12008-01-25 00:00:30 +00001330 CurLexer->BufferPtr = EndPos;
1331 CurLexer->FormTokenWithChars(Result, EndPos);
Chris Lattner8c204872006-10-14 05:19:21 +00001332 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001333
1334 // We're done with the #included file.
1335 delete CurLexer;
1336 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001337
Chris Lattner03f83482006-07-10 06:16:26 +00001338 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001339 // diagnostic is enabled, look for macros that have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001340 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001341 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1342 Macros.begin(), E = Macros.end(); I != E; ++I) {
1343 if (!I->second->isUsed())
1344 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001345 }
1346 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001347 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001348}
1349
1350/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001351/// the current macro expansion or token stream expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001352bool Preprocessor::HandleEndOfMacro(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001353 assert(CurMacroExpander && !CurLexer &&
1354 "Ending a macro when currently in a #include file!");
1355
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001356 // Delete or cache the now-dead macro expander.
1357 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1358 delete CurMacroExpander;
1359 else
1360 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001361
Chris Lattner69772b02006-07-02 20:34:39 +00001362 // Handle this like a #include file being popped off the stack.
1363 CurMacroExpander = 0;
1364 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001365}
1366
Chris Lattner3b5054d2008-02-07 06:03:59 +00001367/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
1368/// comment (/##/) in microsoft mode, this method handles updating the current
1369/// state, returning the token on the next source line.
1370void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
1371 assert(CurMacroExpander && !CurLexer &&
1372 "Pasted comment can only be formed from macro");
1373
1374 // We handle this by scanning for the closest real lexer, switching it to
1375 // raw mode and preprocessor mode. This will cause it to return \n as an
1376 // explicit EOM token.
1377 Lexer *FoundLexer = 0;
1378 bool LexerWasInPPMode = false;
1379 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
1380 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
1381 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
1382
1383 // Once we find a real lexer, mark it as raw mode (disabling macro
1384 // expansions) and preprocessor mode (return EOM). We know that the lexer
1385 // was *not* in raw mode before, because the macro that the comment came
1386 // from was expanded. However, it could have already been in preprocessor
1387 // mode (#if COMMENT) in which case we have to return it to that mode and
1388 // return EOM.
1389 FoundLexer = ISI.TheLexer;
1390 FoundLexer->LexingRawMode = true;
1391 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
1392 FoundLexer->ParsingPreprocessorDirective = true;
1393 break;
1394 }
1395
1396 // Okay, we either found and switched over the lexer, or we didn't find a
1397 // lexer. In either case, finish off the macro the comment came from, getting
1398 // the next token.
1399 if (!HandleEndOfMacro(Tok)) Lex(Tok);
1400
1401 // Discarding comments as long as we don't have EOF or EOM. This 'comments
1402 // out' the rest of the line, including any tokens that came from other macros
1403 // that were active, as in:
1404 // #define submacro a COMMENT b
1405 // submacro c
1406 // which should lex to 'a' only: 'b' and 'c' should be removed.
1407 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
1408 Lex(Tok);
1409
1410 // If we got an eom token, then we successfully found the end of the line.
1411 if (Tok.is(tok::eom)) {
1412 assert(FoundLexer && "Can't get end of line without an active lexer");
1413 // Restore the lexer back to normal mode instead of raw mode.
1414 FoundLexer->LexingRawMode = false;
1415
1416 // If the lexer was already in preprocessor mode, just return the EOM token
1417 // to finish the preprocessor line.
1418 if (LexerWasInPPMode) return;
1419
1420 // Otherwise, switch out of PP mode and return the next lexed token.
1421 FoundLexer->ParsingPreprocessorDirective = false;
1422 return Lex(Tok);
1423 }
1424
1425 // If we got an EOF token, then we reached the end of the token stream but
1426 // didn't find an explicit \n. This can only happen if there was no lexer
1427 // active (an active lexer would return EOM at EOF if there was no \n in
1428 // preprocessor directive mode), so just return EOF as our token.
1429 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
1430 return;
1431}
Chris Lattner22eb9722006-06-18 05:43:12 +00001432
1433//===----------------------------------------------------------------------===//
1434// Utility Methods for Preprocessor Directive Handling.
1435//===----------------------------------------------------------------------===//
1436
1437/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1438/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001439void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner146762e2007-07-20 16:59:19 +00001440 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001441 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001442 LexUnexpandedToken(Tmp);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001443 } while (Tmp.isNot(tok::eom));
Chris Lattner22eb9722006-06-18 05:43:12 +00001444}
1445
Chris Lattner652c1692006-11-21 23:47:30 +00001446/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1447static bool isCXXNamedOperator(const std::string &Spelling) {
1448 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1449 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1450 Spelling == "or" || Spelling == "xor";
1451}
1452
Chris Lattner22eb9722006-06-18 05:43:12 +00001453/// ReadMacroName - Lex and validate a macro name, which occurs after a
1454/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001455/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1456/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001457/// else (e.g. #ifdef).
Chris Lattner146762e2007-07-20 16:59:19 +00001458void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001459 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001460 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001461
1462 // Missing macro name?
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001463 if (MacroNameTok.is(tok::eom))
Chris Lattner22eb9722006-06-18 05:43:12 +00001464 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1465
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001466 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1467 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001468 std::string Spelling = getSpelling(MacroNameTok);
1469 if (isCXXNamedOperator(Spelling))
1470 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1471 // except for their spellings.
1472 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1473 else
1474 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001475 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001476 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001477 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001478 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner259716a2007-10-07 08:04:56 +00001479 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001480 getMacroInfo(II)->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001481 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001482 if (isDefineUndef == 1)
1483 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1484 else
1485 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001486 } else {
1487 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001488 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001489 }
1490
Chris Lattner22eb9722006-06-18 05:43:12 +00001491 // Invalid macro name, read and discard the rest of the line. Then set the
1492 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001493 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001494 return DiscardUntilEndOfDirective();
1495}
1496
1497/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1498/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001499void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner146762e2007-07-20 16:59:19 +00001500 Token Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001501 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001502 // There should be no tokens after the directive, but we allow them as an
1503 // extension.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001504 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001505 Lex(Tmp);
1506
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001507 if (Tmp.isNot(tok::eom)) {
Chris Lattnercb283342006-06-18 06:48:37 +00001508 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1509 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001510 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001511}
1512
1513
1514
1515/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1516/// decided that the subsequent tokens are in the #if'd out portion of the
1517/// file. Lex the rest of the file, until we see an #endif. If
1518/// FoundNonSkipPortion is true, then we have already emitted code for part of
1519/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1520/// is true, then #else directives are ok, if not, then we have already seen one
1521/// so a #else directive is a duplicate. When this returns, the caller can lex
1522/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001523void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001524 bool FoundNonSkipPortion,
1525 bool FoundElse) {
1526 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001527 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001528 "Lexing a macro, not a file?");
1529
1530 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1531 FoundNonSkipPortion, FoundElse);
1532
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001533 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1534 // disabling warnings, etc.
1535 CurLexer->LexingRawMode = true;
Chris Lattner146762e2007-07-20 16:59:19 +00001536 Token Tok;
Chris Lattner22eb9722006-06-18 05:43:12 +00001537 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001538 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001539
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001540 // If this is the end of the buffer, we have an error.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001541 if (Tok.is(tok::eof)) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001542 // Emit errors for each unterminated conditional on the stack, including
1543 // the current one.
1544 while (!CurLexer->ConditionalStack.empty()) {
1545 Diag(CurLexer->ConditionalStack.back().IfLoc,
1546 diag::err_pp_unterminated_conditional);
1547 CurLexer->ConditionalStack.pop_back();
1548 }
1549
1550 // Just return and let the caller lex after this #include.
1551 break;
1552 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001553
1554 // If this token is not a preprocessor directive, just skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001555 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Chris Lattner22eb9722006-06-18 05:43:12 +00001556 continue;
1557
1558 // We just parsed a # character at the start of a line, so we're in
1559 // directive mode. Tell the lexer this so any newlines we see will be
1560 // converted into an EOM token (this terminates the macro).
1561 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001562 CurLexer->KeepCommentMode = false;
1563
Chris Lattner22eb9722006-06-18 05:43:12 +00001564
1565 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001566 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001567
1568 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1569 // something bogus), skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001570 if (Tok.isNot(tok::identifier)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001571 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001572 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001573 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001574 continue;
1575 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001576
Chris Lattner22eb9722006-06-18 05:43:12 +00001577 // If the first letter isn't i or e, it isn't intesting to us. We know that
1578 // this is safe in the face of spelling differences, because there is no way
1579 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001580 // allows us to avoid looking up the identifier info for #define/#undef and
1581 // other common directives.
1582 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1583 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001584 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1585 FirstChar != 'i' && FirstChar != 'e') {
1586 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001587 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001588 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001589 continue;
1590 }
1591
Chris Lattnere60165f2006-06-22 06:36:29 +00001592 // Get the identifier name without trigraphs or embedded newlines. Note
1593 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1594 // when skipping.
1595 // TODO: could do this with zero copies in the no-clean case by using
1596 // strncmp below.
1597 char Directive[20];
1598 unsigned IdLen;
1599 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1600 IdLen = Tok.getLength();
1601 memcpy(Directive, RawCharData, IdLen);
1602 Directive[IdLen] = 0;
1603 } else {
1604 std::string DirectiveStr = getSpelling(Tok);
1605 IdLen = DirectiveStr.size();
1606 if (IdLen >= 20) {
1607 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001608 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001609 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001610 continue;
1611 }
1612 memcpy(Directive, &DirectiveStr[0], IdLen);
1613 Directive[IdLen] = 0;
1614 }
1615
Chris Lattner22eb9722006-06-18 05:43:12 +00001616 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001617 if ((IdLen == 2) || // "if"
1618 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1619 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001620 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1621 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001622 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001623 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001624 /*foundnonskip*/false,
1625 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001626 }
1627 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001628 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001629 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001630 PPConditionalInfo CondInfo;
1631 CondInfo.WasSkipping = true; // Silence bogus warning.
1632 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001633 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001634 assert(!InCond && "Can't be skipping if not in a conditional!");
1635
1636 // If we popped the outermost skipping block, we're done skipping!
1637 if (!CondInfo.WasSkipping)
1638 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001639 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001640 // #else directive in a skipping conditional. If not in some other
1641 // skipping conditional, and if #else hasn't already been seen, enter it
1642 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001643 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001644 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1645
1646 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001647 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001648
1649 // Note that we've seen a #else in this conditional.
1650 CondInfo.FoundElse = true;
1651
1652 // If the conditional is at the top level, and the #if block wasn't
1653 // entered, enter the #else block now.
1654 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1655 CondInfo.FoundNonSkip = true;
1656 break;
1657 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001658 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001659 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1660
1661 bool ShouldEnter;
1662 // If this is in a skipping block or if we're already handled this #if
1663 // block, don't bother parsing the condition.
1664 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001665 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001666 ShouldEnter = false;
1667 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001668 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001669 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001670 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1671 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001672 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001673 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001674 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001675 }
1676
1677 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001678 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001679
1680 // If this condition is true, enter it!
1681 if (ShouldEnter) {
1682 CondInfo.FoundNonSkip = true;
1683 break;
1684 }
1685 }
1686 }
1687
1688 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001689 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001690 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001691 }
1692
1693 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1694 // of the file, just stop skipping and return to lexing whatever came after
1695 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001696 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001697}
1698
1699//===----------------------------------------------------------------------===//
1700// Preprocessor Directive Handling.
1701//===----------------------------------------------------------------------===//
1702
1703/// HandleDirective - This callback is invoked when the lexer sees a # token
1704/// at the start of a line. This consumes the directive, modifies the
1705/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1706/// read is the correct one.
Chris Lattner146762e2007-07-20 16:59:19 +00001707void Preprocessor::HandleDirective(Token &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001708 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001709
1710 // We just parsed a # character at the start of a line, so we're in directive
1711 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001712 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001713 CurLexer->ParsingPreprocessorDirective = true;
1714
1715 ++NumDirectives;
1716
Chris Lattner371ac8a2006-07-04 07:11:10 +00001717 // We are about to read a token. For the multiple-include optimization FA to
1718 // work, we have to remember if we had read any tokens *before* this
1719 // pp-directive.
1720 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1721
Chris Lattner78186052006-07-09 00:45:31 +00001722 // Read the next token, the directive flavor. This isn't expanded due to
1723 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001724 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001725
Chris Lattner78186052006-07-09 00:45:31 +00001726 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1727 // #define A(x) #x
1728 // A(abc
1729 // #warning blah
1730 // def)
1731 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001732 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001733 Diag(Result, diag::ext_embedded_directive);
1734
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001735TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001736 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001737 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001738 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001739 case tok::comment:
1740 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1741 LexUnexpandedToken(Result);
1742 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001743
Chris Lattner22eb9722006-06-18 05:43:12 +00001744 case tok::numeric_constant:
1745 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001746 DiscardUntilEndOfDirective();
1747 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001748 default:
1749 IdentifierInfo *II = Result.getIdentifierInfo();
1750 if (II == 0) break; // Not an identifier.
1751
1752 // Ask what the preprocessor keyword ID is.
1753 switch (II->getPPKeywordID()) {
1754 default: break;
1755 // C99 6.10.1 - Conditional Inclusion.
1756 case tok::pp_if:
1757 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1758 case tok::pp_ifdef:
1759 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1760 case tok::pp_ifndef:
1761 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1762 case tok::pp_elif:
1763 return HandleElifDirective(Result);
1764 case tok::pp_else:
1765 return HandleElseDirective(Result);
1766 case tok::pp_endif:
1767 return HandleEndifDirective(Result);
1768
1769 // C99 6.10.2 - Source File Inclusion.
1770 case tok::pp_include:
1771 return HandleIncludeDirective(Result); // Handle #include.
1772
1773 // C99 6.10.3 - Macro Replacement.
1774 case tok::pp_define:
1775 return HandleDefineDirective(Result, false);
1776 case tok::pp_undef:
1777 return HandleUndefDirective(Result);
1778
1779 // C99 6.10.4 - Line Control.
1780 case tok::pp_line:
1781 // FIXME: implement #line
1782 DiscardUntilEndOfDirective();
1783 return;
1784
1785 // C99 6.10.5 - Error Directive.
1786 case tok::pp_error:
1787 return HandleUserDiagnosticDirective(Result, false);
1788
1789 // C99 6.10.6 - Pragma Directive.
1790 case tok::pp_pragma:
1791 return HandlePragmaDirective();
1792
1793 // GNU Extensions.
1794 case tok::pp_import:
1795 return HandleImportDirective(Result);
1796 case tok::pp_include_next:
1797 return HandleIncludeNextDirective(Result);
1798
1799 case tok::pp_warning:
1800 Diag(Result, diag::ext_pp_warning_directive);
1801 return HandleUserDiagnosticDirective(Result, true);
1802 case tok::pp_ident:
1803 return HandleIdentSCCSDirective(Result);
1804 case tok::pp_sccs:
1805 return HandleIdentSCCSDirective(Result);
1806 case tok::pp_assert:
1807 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001808 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001809 case tok::pp_unassert:
1810 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001811 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001812
1813 // clang extensions.
1814 case tok::pp_define_target:
1815 return HandleDefineDirective(Result, true);
1816 case tok::pp_define_other_target:
1817 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001818 }
1819 break;
1820 }
1821
1822 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001823 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001824
1825 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001826 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001827
1828 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001829}
1830
Chris Lattner146762e2007-07-20 16:59:19 +00001831void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001832 bool isWarning) {
1833 // Read the rest of the line raw. We do this because we don't want macros
1834 // to be expanded and we don't require that the tokens be valid preprocessing
1835 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1836 // collapse multiple consequtive white space between tokens, but this isn't
1837 // specified by the standard.
1838 std::string Message = CurLexer->ReadToEndOfLine();
1839
1840 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001841 return Diag(Tok, DiagID, Message);
1842}
1843
1844/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1845///
Chris Lattner146762e2007-07-20 16:59:19 +00001846void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001847 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001848 Diag(Tok, diag::ext_pp_ident_directive);
1849
Chris Lattner371ac8a2006-07-04 07:11:10 +00001850 // Read the string argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001851 Token StrTok;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001852 Lex(StrTok);
1853
1854 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001855 if (StrTok.isNot(tok::string_literal) &&
1856 StrTok.isNot(tok::wide_string_literal))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001857 return Diag(StrTok, diag::err_pp_malformed_ident);
1858
1859 // Verify that there is nothing after the string, other than EOM.
1860 CheckEndOfDirective("#ident");
1861
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001862 if (Callbacks)
1863 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001864}
1865
Chris Lattnerb8761832006-06-24 21:31:03 +00001866//===----------------------------------------------------------------------===//
1867// Preprocessor Include Directive Handling.
1868//===----------------------------------------------------------------------===//
1869
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001870/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1871/// checked and spelled filename, e.g. as an operand of #include. This returns
1872/// true if the input filename was in <>'s or false if it were in ""'s. The
1873/// caller is expected to provide a buffer that is large enough to hold the
1874/// spelling of the filename, but is also expected to handle the case when
1875/// this method decides to use a different buffer.
Chris Lattner93ab9f12007-07-23 04:15:27 +00001876bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001877 const char *&BufStart,
1878 const char *&BufEnd) {
1879 // Get the text form of the filename.
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001880 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1881
1882 // Make sure the filename is <x> or "x".
1883 bool isAngled;
1884 if (BufStart[0] == '<') {
1885 if (BufEnd[-1] != '>') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001886 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001887 BufStart = 0;
1888 return true;
1889 }
1890 isAngled = true;
1891 } else if (BufStart[0] == '"') {
1892 if (BufEnd[-1] != '"') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001893 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001894 BufStart = 0;
1895 return true;
1896 }
1897 isAngled = false;
1898 } else {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001899 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001900 BufStart = 0;
1901 return true;
1902 }
1903
1904 // Diagnose #include "" as invalid.
1905 if (BufEnd-BufStart <= 2) {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001906 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001907 BufStart = 0;
1908 return "";
1909 }
1910
1911 // Skip the brackets.
1912 ++BufStart;
1913 --BufEnd;
1914 return isAngled;
1915}
1916
Chris Lattner43eafb42007-07-23 04:56:47 +00001917/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1918/// from a macro as multiple tokens, which need to be glued together. This
1919/// occurs for code like:
1920/// #define FOO <a/b.h>
1921/// #include FOO
1922/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1923///
1924/// This code concatenates and consumes tokens up to the '>' token. It returns
1925/// false if the > was found, otherwise it returns true if it finds and consumes
1926/// the EOM marker.
1927static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1928 Preprocessor &PP) {
1929 Token CurTok;
1930
1931 PP.Lex(CurTok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001932 while (CurTok.isNot(tok::eom)) {
Chris Lattner43eafb42007-07-23 04:56:47 +00001933 // Append the spelling of this token to the buffer. If there was a space
1934 // before it, add it now.
1935 if (CurTok.hasLeadingSpace())
1936 FilenameBuffer.push_back(' ');
1937
1938 // Get the spelling of the token, directly into FilenameBuffer if possible.
1939 unsigned PreAppendSize = FilenameBuffer.size();
1940 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1941
1942 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1943 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1944
1945 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1946 if (BufPtr != &FilenameBuffer[PreAppendSize])
1947 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1948
1949 // Resize FilenameBuffer to the correct size.
1950 if (CurTok.getLength() != ActualLen)
1951 FilenameBuffer.resize(PreAppendSize+ActualLen);
1952
1953 // If we found the '>' marker, return success.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001954 if (CurTok.is(tok::greater))
Chris Lattner43eafb42007-07-23 04:56:47 +00001955 return false;
1956
1957 PP.Lex(CurTok);
1958 }
1959
1960 // If we hit the eom marker, emit an error and return true so that the caller
1961 // knows the EOM has been read.
1962 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1963 return true;
1964}
1965
Chris Lattner22eb9722006-06-18 05:43:12 +00001966/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1967/// file to be included from the lexer, then include it! This is a common
1968/// routine with functionality shared between #include, #include_next and
1969/// #import.
Chris Lattner146762e2007-07-20 16:59:19 +00001970void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001971 const DirectoryLookup *LookupFrom,
1972 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001973
Chris Lattner146762e2007-07-20 16:59:19 +00001974 Token FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001975 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001976
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001977 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001978 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner43eafb42007-07-23 04:56:47 +00001979 const char *FilenameStart, *FilenameEnd;
1980
1981 switch (FilenameTok.getKind()) {
1982 case tok::eom:
1983 // If the token kind is EOM, the error has already been diagnosed.
1984 return;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001985
Chris Lattner43eafb42007-07-23 04:56:47 +00001986 case tok::angle_string_literal:
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001987 case tok::string_literal: {
Chris Lattner43eafb42007-07-23 04:56:47 +00001988 FilenameBuffer.resize(FilenameTok.getLength());
1989 FilenameStart = &FilenameBuffer[0];
1990 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1991 FilenameEnd = FilenameStart+Len;
1992 break;
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001993 }
Chris Lattner43eafb42007-07-23 04:56:47 +00001994
1995 case tok::less:
1996 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1997 // case, glue the tokens together into FilenameBuffer and interpret those.
1998 FilenameBuffer.push_back('<');
1999 if (ConcatenateIncludeName(FilenameBuffer, *this))
2000 return; // Found <eom> but no ">"? Diagnostic already emitted.
2001 FilenameStart = &FilenameBuffer[0];
2002 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
2003 break;
2004 default:
2005 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
2006 DiscardUntilEndOfDirective();
2007 return;
2008 }
2009
Chris Lattner93ab9f12007-07-23 04:15:27 +00002010 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002011 FilenameStart, FilenameEnd);
2012 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
2013 // error.
Chris Lattner43eafb42007-07-23 04:56:47 +00002014 if (FilenameStart == 0) {
2015 DiscardUntilEndOfDirective();
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002016 return;
Chris Lattner43eafb42007-07-23 04:56:47 +00002017 }
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002018
Chris Lattner269c2322006-06-25 06:23:00 +00002019 // Verify that there is nothing after the filename, other than EOM. Use the
2020 // preprocessor to lex this in case lexing the filename entered a macro.
2021 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00002022
2023 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00002024 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00002025 return Diag(FilenameTok, diag::err_pp_include_too_deep);
2026
Chris Lattner22eb9722006-06-18 05:43:12 +00002027 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00002028 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00002029 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00002030 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00002031 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00002032 return Diag(FilenameTok, diag::err_pp_file_not_found,
2033 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00002034
Chris Lattner59a9ebd2006-10-18 05:34:33 +00002035 // Ask HeaderInfo if we should enter this #include file.
2036 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
2037 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00002038 return;
2039 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002040
2041 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002042 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00002043 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00002044 return Diag(FilenameTok, diag::err_pp_file_not_found,
2045 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00002046
2047 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00002048 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00002049}
2050
2051/// HandleIncludeNextDirective - Implements #include_next.
2052///
Chris Lattner146762e2007-07-20 16:59:19 +00002053void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00002054 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00002055
2056 // #include_next is like #include, except that we start searching after
2057 // the current found directory. If we can't do this, issue a
2058 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00002059 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00002060 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002061 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00002062 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00002063 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00002064 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00002065 } else {
2066 // Start looking up in the next directory.
2067 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00002068 }
2069
2070 return HandleIncludeDirective(IncludeNextTok, Lookup);
2071}
2072
2073/// HandleImportDirective - Implements #import.
2074///
Chris Lattner146762e2007-07-20 16:59:19 +00002075void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00002076 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00002077
2078 return HandleIncludeDirective(ImportTok, 0, true);
2079}
2080
Chris Lattnerb8761832006-06-24 21:31:03 +00002081//===----------------------------------------------------------------------===//
2082// Preprocessor Macro Directive Handling.
2083//===----------------------------------------------------------------------===//
2084
Chris Lattnercefc7682006-07-08 08:28:12 +00002085/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
2086/// definition has just been read. Lex the rest of the arguments and the
2087/// closing ), updating MI with what we learn. Return true if an error occurs
2088/// parsing the arg list.
2089bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00002090 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
2091
Chris Lattner146762e2007-07-20 16:59:19 +00002092 Token Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00002093 while (1) {
2094 LexUnexpandedToken(Tok);
2095 switch (Tok.getKind()) {
2096 case tok::r_paren:
2097 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00002098 if (Arguments.empty()) { // #define FOO()
2099 MI->setArgumentList(Arguments.begin(), Arguments.end());
2100 return false;
2101 }
Chris Lattnercefc7682006-07-08 08:28:12 +00002102 // Otherwise we have #define FOO(A,)
2103 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2104 return true;
2105 case tok::ellipsis: // #define X(... -> C99 varargs
2106 // Warn if use of C99 feature in non-C99 mode.
2107 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
2108
2109 // Lex the token after the identifier.
2110 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002111 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002112 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2113 return true;
2114 }
Chris Lattner95a06b32006-07-30 08:40:43 +00002115 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00002116 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00002117 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00002118 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002119 return false;
2120 case tok::eom: // #define X(
2121 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2122 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00002123 default:
2124 // Handle keywords and identifiers here to accept things like
2125 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002126 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00002127 if (II == 0) {
2128 // #define X(1
2129 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2130 return true;
2131 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002132
2133 // If this is already used as an argument, it is used multiple times (e.g.
2134 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00002135 if (std::find(Arguments.begin(), Arguments.end(), II) !=
2136 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002137 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
2138 return true;
2139 }
2140
2141 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00002142 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00002143
2144 // Lex the token after the identifier.
2145 LexUnexpandedToken(Tok);
2146
2147 switch (Tok.getKind()) {
2148 default: // #define X(A B
2149 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2150 return true;
2151 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00002152 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002153 return false;
2154 case tok::comma: // #define X(A,
2155 break;
2156 case tok::ellipsis: // #define X(A... -> GCC extension
2157 // Diagnose extension.
2158 Diag(Tok, diag::ext_named_variadic_macro);
2159
2160 // Lex the token after the identifier.
2161 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002162 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002163 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2164 return true;
2165 }
2166
2167 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00002168 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002169 return false;
2170 }
2171 }
2172 }
2173}
2174
Chris Lattner22eb9722006-06-18 05:43:12 +00002175/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00002176/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2177/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00002178///
Chris Lattner146762e2007-07-20 16:59:19 +00002179void Preprocessor::HandleDefineDirective(Token &DefineTok,
Chris Lattner81278c62006-10-14 19:03:49 +00002180 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002181 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002182
Chris Lattner146762e2007-07-20 16:59:19 +00002183 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002184 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00002185
2186 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002187 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002188 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00002189
Chris Lattner457fc152006-07-29 06:30:25 +00002190 // If we are supposed to keep comments in #defines, reenable comment saving
2191 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00002192 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00002193
Chris Lattner063400e2006-10-14 19:54:15 +00002194 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00002195 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00002196 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00002197
Chris Lattner063400e2006-10-14 19:54:15 +00002198 // If the identifier is an 'other target' macro, clear this bit.
2199 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2200
2201
Chris Lattner146762e2007-07-20 16:59:19 +00002202 Token Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00002203 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002204
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002205 // If this is a function-like macro definition, parse the argument list,
2206 // marking each of the identifiers as being used as macro arguments. Also,
2207 // check other constraints on the first token of the macro body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002208 if (Tok.is(tok::eom)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002209 // If there is no body to this macro, we have no special handling here.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002210 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002211 // This is a function-like macro definition. Read the argument list.
2212 MI->setIsFunctionLike();
2213 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002214 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00002215 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002216 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00002217 if (CurLexer->ParsingPreprocessorDirective)
2218 DiscardUntilEndOfDirective();
2219 return;
2220 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002221
Chris Lattner815a1f92006-07-08 20:48:04 +00002222 // Read the first token after the arg list for down below.
2223 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002224 } else if (!Tok.hasLeadingSpace()) {
2225 // C99 requires whitespace between the macro definition and the body. Emit
2226 // a diagnostic for something like "#define X+".
2227 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00002228 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00002229 } else {
2230 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2231 // one in some cases!
2232 }
2233 } else {
2234 // This is a normal token with leading space. Clear the leading space
2235 // marker on the first token to get proper expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00002236 Tok.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002237 }
2238
Chris Lattner7e374832006-07-29 03:46:57 +00002239 // If this is a definition of a variadic C99 function-like macro, not using
2240 // the GNU named varargs extension, enabled __VA_ARGS__.
2241
2242 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2243 // This gets unpoisoned where it is allowed.
2244 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2245 if (MI->isC99Varargs())
2246 Ident__VA_ARGS__->setIsPoisoned(false);
2247
Chris Lattner22eb9722006-06-18 05:43:12 +00002248 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00002249 if (MI->isObjectLike()) {
2250 // Object-like macros are very simple, just read their body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002251 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002252 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002253 // Get the next token of the macro.
2254 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002255 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002256
Chris Lattnera3834342007-07-14 21:54:03 +00002257 } else {
2258 // Otherwise, read the body of a function-like macro. This has to validate
2259 // the # (stringize) operator.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002260 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002261 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002262
Chris Lattnera3834342007-07-14 21:54:03 +00002263 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2264 // parameters in function-like macro expansions.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002265 if (Tok.isNot(tok::hash)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002266 // Get the next token of the macro.
2267 LexUnexpandedToken(Tok);
2268 continue;
2269 }
2270
2271 // Get the next token of the macro.
2272 LexUnexpandedToken(Tok);
2273
2274 // Not a macro arg identifier?
2275 if (!Tok.getIdentifierInfo() ||
2276 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2277 Diag(Tok, diag::err_pp_stringize_not_parameter);
2278 delete MI;
2279
2280 // Disable __VA_ARGS__ again.
2281 Ident__VA_ARGS__->setIsPoisoned(true);
2282 return;
2283 }
2284
2285 // Things look ok, add the param name token to the macro.
2286 MI->AddTokenToBody(Tok);
2287
2288 // Get the next token of the macro.
2289 LexUnexpandedToken(Tok);
2290 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002291 }
Chris Lattner7e374832006-07-29 03:46:57 +00002292
Chris Lattnerf40fe992007-07-14 22:11:41 +00002293
Chris Lattner7e374832006-07-29 03:46:57 +00002294 // Disable __VA_ARGS__ again.
2295 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002296
Chris Lattnerbff18d52006-07-06 04:49:18 +00002297 // Check that there is no paste (##) operator at the begining or end of the
2298 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00002299 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00002300 if (NumTokens != 0) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002301 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002302 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002303 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002304 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002305 }
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002306 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002307 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002308 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002309 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002310 }
2311 }
2312
Chris Lattner13044d92006-07-03 05:16:44 +00002313 // If this is the primary source file, remember that this macro hasn't been
2314 // used yet.
2315 if (isInPrimaryFile())
2316 MI->setIsUsed(false);
2317
Chris Lattner22eb9722006-06-18 05:43:12 +00002318 // Finally, if this identifier already had a macro defined for it, verify that
2319 // the macro bodies are identical and free the old definition.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002320 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner13044d92006-07-03 05:16:44 +00002321 if (!OtherMI->isUsed())
2322 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2323
Chris Lattner22eb9722006-06-18 05:43:12 +00002324 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00002325 // must be the same. C99 6.10.3.2.
2326 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00002327 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2328 MacroNameTok.getIdentifierInfo()->getName());
2329 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2330 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002331 delete OtherMI;
2332 }
2333
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002334 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00002335}
2336
Chris Lattner063400e2006-10-14 19:54:15 +00002337/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattner146762e2007-07-20 16:59:19 +00002338void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2339 Token MacroNameTok;
Chris Lattner063400e2006-10-14 19:54:15 +00002340 ReadMacroName(MacroNameTok, 1);
2341
2342 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002343 if (MacroNameTok.is(tok::eom))
Chris Lattner063400e2006-10-14 19:54:15 +00002344 return;
2345
2346 // Check to see if this is the last token on the #undef line.
2347 CheckEndOfDirective("#define_other_target");
2348
2349 // If there is already a macro defined by this name, turn it into a
2350 // target-specific define.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002351 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner063400e2006-10-14 19:54:15 +00002352 MI->setIsTargetSpecific(true);
2353 return;
2354 }
2355
2356 // Mark the identifier as being a macro on some other target.
2357 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2358}
2359
Chris Lattner22eb9722006-06-18 05:43:12 +00002360
2361/// HandleUndefDirective - Implements #undef.
2362///
Chris Lattner146762e2007-07-20 16:59:19 +00002363void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002364 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002365
Chris Lattner146762e2007-07-20 16:59:19 +00002366 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002367 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002368
2369 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002370 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002371 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002372
2373 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002374 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002375
2376 // Okay, we finally have a valid identifier to undef.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002377 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Chris Lattner22eb9722006-06-18 05:43:12 +00002378
Chris Lattner063400e2006-10-14 19:54:15 +00002379 // #undef untaints an identifier if it were marked by define_other_target.
2380 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2381
Chris Lattner22eb9722006-06-18 05:43:12 +00002382 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002383 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002384
Chris Lattner13044d92006-07-03 05:16:44 +00002385 if (!MI->isUsed())
2386 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002387
2388 // Free macro definition.
2389 delete MI;
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002390 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002391}
2392
2393
Chris Lattnerb8761832006-06-24 21:31:03 +00002394//===----------------------------------------------------------------------===//
2395// Preprocessor Conditional Directive Handling.
2396//===----------------------------------------------------------------------===//
2397
Chris Lattner22eb9722006-06-18 05:43:12 +00002398/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002399/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2400/// if any tokens have been returned or pp-directives activated before this
2401/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002402///
Chris Lattner146762e2007-07-20 16:59:19 +00002403void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Chris Lattner371ac8a2006-07-04 07:11:10 +00002404 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002405 ++NumIf;
Chris Lattner146762e2007-07-20 16:59:19 +00002406 Token DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002407
Chris Lattner146762e2007-07-20 16:59:19 +00002408 Token MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002409 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002410
2411 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002412 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002413 // Skip code until we get to #endif. This helps with recovery by not
2414 // emitting an error when the #endif is reached.
2415 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2416 /*Foundnonskip*/false, /*FoundElse*/false);
Chris Lattnercb283342006-06-18 06:48:37 +00002417 return;
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002418 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002419
2420 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002421 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2422
2423 // If the start of a top-level #ifdef, inform MIOpt.
2424 if (!ReadAnyTokensBeforeDirective &&
2425 CurLexer->getConditionalStackDepth() == 0) {
2426 assert(isIfndef && "#ifdef shouldn't reach here");
2427 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2428 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002429
Chris Lattner063400e2006-10-14 19:54:15 +00002430 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002431 MacroInfo *MI = getMacroInfo(MII);
Chris Lattnera78a97e2006-07-03 05:42:18 +00002432
Chris Lattner81278c62006-10-14 19:03:49 +00002433 // If there is a macro, process it.
2434 if (MI) {
2435 // Mark it used.
2436 MI->setIsUsed(true);
2437
2438 // If this is the first use of a target-specific macro, warn about it.
2439 if (MI->isTargetSpecific()) {
2440 MI->setIsTargetSpecific(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00002441 getTargetInfo().DiagnoseNonPortability(
2442 getFullLoc(MacroNameTok.getLocation()),
2443 diag::port_target_macro_use);
Chris Lattner81278c62006-10-14 19:03:49 +00002444 }
Chris Lattner063400e2006-10-14 19:54:15 +00002445 } else {
2446 // Use of a target-specific macro for some other target? If so, warn.
2447 if (MII->isOtherTargetMacro()) {
2448 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00002449 getTargetInfo().DiagnoseNonPortability(
2450 getFullLoc(MacroNameTok.getLocation()),
2451 diag::port_target_macro_use);
Chris Lattner063400e2006-10-14 19:54:15 +00002452 }
Chris Lattner81278c62006-10-14 19:03:49 +00002453 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002454
Chris Lattner22eb9722006-06-18 05:43:12 +00002455 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002456 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002457 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002458 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002459 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002460 } else {
2461 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002462 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002463 /*Foundnonskip*/false,
2464 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002465 }
2466}
2467
2468/// HandleIfDirective - Implements the #if directive.
2469///
Chris Lattner146762e2007-07-20 16:59:19 +00002470void Preprocessor::HandleIfDirective(Token &IfToken,
Chris Lattnera8654ca2006-07-04 17:42:08 +00002471 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002472 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002473
Chris Lattner371ac8a2006-07-04 07:11:10 +00002474 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002475 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002476 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002477
2478 // Should we include the stuff contained by this directive?
2479 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002480 // If this condition is equivalent to #ifndef X, and if this is the first
2481 // directive seen, handle it for the multiple-include optimization.
2482 if (!ReadAnyTokensBeforeDirective &&
2483 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2484 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2485
Chris Lattner22eb9722006-06-18 05:43:12 +00002486 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002487 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002488 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002489 } else {
2490 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002491 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002492 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002493 }
2494}
2495
2496/// HandleEndifDirective - Implements the #endif directive.
2497///
Chris Lattner146762e2007-07-20 16:59:19 +00002498void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002499 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002500
Chris Lattner22eb9722006-06-18 05:43:12 +00002501 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002502 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002503
2504 PPConditionalInfo CondInfo;
2505 if (CurLexer->popConditionalLevel(CondInfo)) {
2506 // No conditionals on the stack: this is an #endif without an #if.
2507 return Diag(EndifToken, diag::err_pp_endif_without_if);
2508 }
2509
Chris Lattner371ac8a2006-07-04 07:11:10 +00002510 // If this the end of a top-level #endif, inform MIOpt.
2511 if (CurLexer->getConditionalStackDepth() == 0)
2512 CurLexer->MIOpt.ExitTopLevelConditional();
2513
Chris Lattner538d7f32006-07-20 04:31:52 +00002514 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002515 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002516}
2517
2518
Chris Lattner146762e2007-07-20 16:59:19 +00002519void Preprocessor::HandleElseDirective(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002520 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002521
Chris Lattner22eb9722006-06-18 05:43:12 +00002522 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002523 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002524
2525 PPConditionalInfo CI;
2526 if (CurLexer->popConditionalLevel(CI))
2527 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002528
2529 // If this is a top-level #else, inform the MIOpt.
2530 if (CurLexer->getConditionalStackDepth() == 0)
2531 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002532
2533 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002534 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002535
2536 // Finally, skip the rest of the contents of this block and return the first
2537 // token after it.
2538 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2539 /*FoundElse*/true);
2540}
2541
Chris Lattner146762e2007-07-20 16:59:19 +00002542void Preprocessor::HandleElifDirective(Token &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002543 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002544
Chris Lattner22eb9722006-06-18 05:43:12 +00002545 // #elif directive in a non-skipping conditional... start skipping.
2546 // We don't care what the condition is, because we will always skip it (since
2547 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002548 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002549
2550 PPConditionalInfo CI;
2551 if (CurLexer->popConditionalLevel(CI))
2552 return Diag(ElifToken, diag::pp_err_elif_without_if);
2553
Chris Lattner371ac8a2006-07-04 07:11:10 +00002554 // If this is a top-level #elif, inform the MIOpt.
2555 if (CurLexer->getConditionalStackDepth() == 0)
2556 CurLexer->MIOpt.FoundTopLevelElse();
2557
Chris Lattner22eb9722006-06-18 05:43:12 +00002558 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002559 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002560
2561 // Finally, skip the rest of the contents of this block and return the first
2562 // token after it.
2563 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2564 /*FoundElse*/CI.FoundElse);
2565}
Chris Lattnerb8761832006-06-24 21:31:03 +00002566