blob: 25ddb03d48a782202ef88671533ea23521db99e5 [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//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
Chris Lattner22eb9722006-06-18 05:43:12 +000040#include <iostream>
Chris Lattner22eb9722006-06-18 05:43:12 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
44
Chris Lattner02dffbd2006-10-14 07:50:21 +000045Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000046 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000047 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000048 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
49 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000050 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000051 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000052
Chris Lattner22eb9722006-06-18 05:43:12 +000053 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000054 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000055 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000056 NumEnteredSourceFiles = 0;
57 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000058 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000059 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000061
62 // Default to discarding comments.
63 KeepComments = false;
64 KeepMacroComments = false;
65
Chris Lattner22eb9722006-06-18 05:43:12 +000066 // Macro expansion is enabled.
67 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000068 InMacroArgs = false;
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000069 NumCachedMacroExpanders = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000070
Chris Lattner8ff71992006-07-06 05:17:39 +000071 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
72 // This gets unpoisoned where it is allowed.
73 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
74
Chris Lattnerb8761832006-06-24 21:31:03 +000075 // Initialize the pragma handlers.
76 PragmaHandlers = new PragmaNamespace(0);
77 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000078
79 // Initialize builtin macros like __LINE__ and friends.
80 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000081}
82
83Preprocessor::~Preprocessor() {
84 // Free any active lexers.
85 delete CurLexer;
86
Chris Lattner69772b02006-07-02 20:34:39 +000087 while (!IncludeMacroStack.empty()) {
88 delete IncludeMacroStack.back().TheLexer;
89 delete IncludeMacroStack.back().TheMacroExpander;
90 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000091 }
Chris Lattnerb8761832006-06-24 21:31:03 +000092
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000093 // Free any cached macro expanders.
94 for (unsigned i = 0, e = NumCachedMacroExpanders; i != e; ++i)
95 delete MacroExpanderCache[i];
96
Chris Lattnerb8761832006-06-24 21:31:03 +000097 // Release pragma information.
98 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000099
100 // Delete the scratch buffer info.
101 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +0000102}
103
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000104PPCallbacks::~PPCallbacks() {
105}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000106
Chris Lattner22eb9722006-06-18 05:43:12 +0000107/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
Chris Lattner146762e2007-07-20 16:59:19 +0000108/// the specified Token's location, translating the token's start
Chris Lattner22eb9722006-06-18 05:43:12 +0000109/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattner36982e42007-05-16 17:49:37 +0000110void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
111 Diags.Report(Loc, DiagID);
112}
113
Chris Lattnercb283342006-06-18 06:48:37 +0000114void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000115 const std::string &Msg) {
Chris Lattner36982e42007-05-16 17:49:37 +0000116 Diags.Report(Loc, DiagID, &Msg, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000117}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000118
Chris Lattner146762e2007-07-20 16:59:19 +0000119void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000120 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
121 << getSpelling(Tok) << "'";
122
123 if (!DumpFlags) return;
124 std::cerr << "\t";
125 if (Tok.isAtStartOfLine())
126 std::cerr << " [StartOfLine]";
127 if (Tok.hasLeadingSpace())
128 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000129 if (Tok.isExpandDisabled())
130 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000131 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000132 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000133 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
134 << "']";
135 }
136}
137
138void Preprocessor::DumpMacro(const MacroInfo &MI) const {
139 std::cerr << "MACRO: ";
140 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
141 DumpToken(MI.getReplacementToken(i));
142 std::cerr << " ";
143 }
144 std::cerr << "\n";
145}
146
Chris Lattner22eb9722006-06-18 05:43:12 +0000147void Preprocessor::PrintStats() {
148 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000149 std::cerr << NumDirectives << " directives found:\n";
150 std::cerr << " " << NumDefined << " #define.\n";
151 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000152 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000153 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
154 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
155 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
156 std::cerr << " " << NumElse << " #else/#elif.\n";
157 std::cerr << " " << NumEndif << " #endif.\n";
158 std::cerr << " " << NumPragma << " #pragma.\n";
159 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
160
Chris Lattner78186052006-07-09 00:45:31 +0000161 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
162 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000163 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000164 std::cerr << (NumFastTokenPaste+NumTokenPaste)
165 << " token paste (##) operations performed, "
166 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000167}
168
169//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000170// Token Spelling
171//===----------------------------------------------------------------------===//
172
173
174/// getSpelling() - Return the 'spelling' of this token. The spelling of a
175/// token are the characters used to represent the token in the source file
176/// after trigraph expansion and escaped-newline folding. In particular, this
177/// wants to get the true, uncanonicalized, spelling of things like digraphs
178/// UCNs, etc.
Chris Lattner146762e2007-07-20 16:59:19 +0000179std::string Preprocessor::getSpelling(const Token &Tok) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000180 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
181
182 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000183 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000184 if (!Tok.needsCleaning())
185 return std::string(TokStart, TokStart+Tok.getLength());
186
Chris Lattnerd01e2912006-06-18 16:22:51 +0000187 std::string Result;
188 Result.reserve(Tok.getLength());
189
Chris Lattneref9eae12006-07-04 22:33:12 +0000190 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000191 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
192 Ptr != End; ) {
193 unsigned CharSize;
194 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
195 Ptr += CharSize;
196 }
197 assert(Result.size() != unsigned(Tok.getLength()) &&
198 "NeedsCleaning flag set on something that didn't need cleaning!");
199 return Result;
200}
201
202/// getSpelling - This method is used to get the spelling of a token into a
203/// preallocated buffer, instead of as an std::string. The caller is required
204/// to allocate enough space for the token, which is guaranteed to be at least
205/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000206///
207/// Note that this method may do two possible things: it may either fill in
208/// the buffer specified with characters, or it may *change the input pointer*
209/// to point to a constant buffer with the data already in it (avoiding a
210/// copy). The caller is not allowed to modify the returned buffer pointer
211/// if an internal buffer is returned.
Chris Lattner146762e2007-07-20 16:59:19 +0000212unsigned Preprocessor::getSpelling(const Token &Tok,
Chris Lattneref9eae12006-07-04 22:33:12 +0000213 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000214 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
215
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000216 // If this token is an identifier, just return the string from the identifier
217 // table, which is very quick.
218 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
219 Buffer = II->getName();
Chris Lattner32e6d642007-07-22 22:50:09 +0000220
221 // Return the length of the token. If the token needed cleaning, don't
222 // include the size of the newlines or trigraphs in it.
223 if (!Tok.needsCleaning())
224 return Tok.getLength();
225 else
226 return strlen(Buffer);
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000227 }
228
229 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000230 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000231
232 // If this token contains nothing interesting, return it directly.
233 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000234 Buffer = TokStart;
235 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000236 }
237 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000238 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000239 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
240 Ptr != End; ) {
241 unsigned CharSize;
242 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
243 Ptr += CharSize;
244 }
245 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
246 "NeedsCleaning flag set on something that didn't need cleaning!");
247
248 return OutBuf-Buffer;
249}
250
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000251
252/// CreateString - Plop the specified string into a scratch buffer and return a
253/// location for it. If specified, the source location provides a source
254/// location for the token.
255SourceLocation Preprocessor::
256CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
257 if (SLoc.isValid())
258 return ScratchBuf->getToken(Buf, Len, SLoc);
259 return ScratchBuf->getToken(Buf, Len);
260}
261
262
Chris Lattner8a7003c2007-07-16 06:48:38 +0000263/// AdvanceToTokenCharacter - Given a location that specifies the start of a
264/// token, return a new location that specifies a character within the token.
265SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
266 unsigned CharNo) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000267 // If they request the first char of the token, we're trivially done. If this
268 // is a macro expansion, it doesn't make sense to point to a character within
269 // the instantiation point (the name). We could point to the source
270 // character, but without also pointing to instantiation info, this is
271 // confusing.
272 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000273
274 // Figure out how many physical characters away the specified logical
275 // character is. This needs to take into consideration newlines and
276 // trigraphs.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000277 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
278 unsigned PhysOffset = 0;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000279
280 // The usual case is that tokens don't contain anything interesting. Skip
281 // over the uninteresting characters. If a token only consists of simple
282 // chars, this method is extremely fast.
283 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000284 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000285
286 // If we have a character that may be a trigraph or escaped newline, create a
287 // lexer to parse it correctly.
Chris Lattner8a7003c2007-07-16 06:48:38 +0000288 if (CharNo != 0) {
289 // Create a lexer starting at this token position.
Chris Lattner77e9de52007-07-20 16:52:03 +0000290 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattner146762e2007-07-20 16:59:19 +0000291 Token Tok;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000292 // Skip over characters the remaining characters.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000293 const char *TokStartPtr = TokPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000294 for (; CharNo; --CharNo)
295 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000296
297 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000298 }
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000299
300 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner8a7003c2007-07-16 06:48:38 +0000301}
302
303
304
Chris Lattnerd01e2912006-06-18 16:22:51 +0000305//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000306// Source File Location Methods.
307//===----------------------------------------------------------------------===//
308
Chris Lattner22eb9722006-06-18 05:43:12 +0000309/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
310/// return null on failure. isAngled indicates whether the file reference is
311/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000312const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
313 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000314 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000315 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000316 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000317 // If the header lookup mechanism may be relative to the current file, pass in
318 // info about where the current file is.
319 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000320 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000321 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
322 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000323 }
324
Chris Lattner63dd32b2006-10-20 04:42:40 +0000325 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000326 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000327 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000328 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
329 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000330 if (FE) return FE;
331
332 // Otherwise, see if this is a subframework header. If so, this is relative
333 // to one of the headers on the #include stack. Walk the list of the current
334 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000335 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000336 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000337 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
338 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000339 return FE;
340 }
341
342 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
343 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000344 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000345 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000346 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
347 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000348 return FE;
349 }
350 }
351
352 // Otherwise, we really couldn't find the file.
353 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000354}
355
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000356/// isInPrimaryFile - Return true if we're in the top-level file, not in a
357/// #include.
358bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000359 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000360 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000361
Chris Lattner13044d92006-07-03 05:16:44 +0000362 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000363 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000364 if (IncludeMacroStack[i].TheLexer &&
365 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
366 return IncludeMacroStack[i].TheLexer->isMainFile();
367 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000368}
369
370/// getCurrentLexer - Return the current file lexer being lexed from. Note
371/// that this ignores any potentially active macro expansions and _Pragma
372/// expansions going on at the time.
373Lexer *Preprocessor::getCurrentFileLexer() const {
374 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
375
376 // Look for a stacked lexer.
377 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000378 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000379 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
380 return L;
381 }
382 return 0;
383}
384
385
Chris Lattner22eb9722006-06-18 05:43:12 +0000386/// EnterSourceFile - Add a source file to the top of the include stack and
387/// start lexing tokens from it instead of the current buffer. Return true
388/// on failure.
389void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000390 const DirectoryLookup *CurDir,
391 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000392 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000393 ++NumEnteredSourceFiles;
394
Chris Lattner69772b02006-07-02 20:34:39 +0000395 if (MaxIncludeStackDepth < IncludeMacroStack.size())
396 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000397
Chris Lattner77e9de52007-07-20 16:52:03 +0000398 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000399 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000400 EnterSourceFileWithLexer(TheLexer, CurDir);
401}
Chris Lattner22eb9722006-06-18 05:43:12 +0000402
Chris Lattner69772b02006-07-02 20:34:39 +0000403/// EnterSourceFile - Add a source file to the top of the include stack and
404/// start lexing tokens from it instead of the current buffer.
405void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
406 const DirectoryLookup *CurDir) {
407
408 // Add the current lexer to the include stack.
409 if (CurLexer || CurMacroExpander)
410 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
411 CurMacroExpander));
412
413 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000414 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000415 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000416
417 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000418 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000419 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
420
421 // Get the file entry for the current file.
422 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000423 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000424 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000425
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000426 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000427 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000428 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000429}
430
Chris Lattner69772b02006-07-02 20:34:39 +0000431
432
Chris Lattner22eb9722006-06-18 05:43:12 +0000433/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000434/// tokens from it instead of the current buffer.
Chris Lattner146762e2007-07-20 16:59:19 +0000435void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000436 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
437 CurMacroExpander));
438 CurLexer = 0;
439 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000440
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000441 if (NumCachedMacroExpanders == 0) {
442 CurMacroExpander = new MacroExpander(Tok, Args, *this);
443 } else {
444 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
445 CurMacroExpander->Init(Tok, Args);
446 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000447}
448
Chris Lattner7667d0d2006-07-16 18:16:58 +0000449/// EnterTokenStream - Add a "macro" context to the top of the include stack,
450/// which will cause the lexer to start returning the specified tokens. Note
451/// that these tokens will be re-macro-expanded when/if expansion is enabled.
452/// This method assumes that the specified stream of tokens has a permanent
453/// owner somewhere, so they do not need to be copied.
Chris Lattner146762e2007-07-20 16:59:19 +0000454void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000455 // Save our current state.
456 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
457 CurMacroExpander));
458 CurLexer = 0;
459 CurDirLookup = 0;
460
461 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000462 if (NumCachedMacroExpanders == 0) {
463 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
464 } else {
465 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
466 CurMacroExpander->Init(Toks, NumToks);
467 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000468}
469
470/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
471/// lexer stack. This should only be used in situations where the current
472/// state of the top-of-stack lexer is known.
473void Preprocessor::RemoveTopOfLexerStack() {
474 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000475
476 if (CurMacroExpander) {
477 // Delete or cache the now-dead macro expander.
478 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
479 delete CurMacroExpander;
480 else
481 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
482 } else {
483 delete CurLexer;
484 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000485 CurLexer = IncludeMacroStack.back().TheLexer;
486 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
487 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
488 IncludeMacroStack.pop_back();
489}
490
Chris Lattner22eb9722006-06-18 05:43:12 +0000491//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000492// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000493//===----------------------------------------------------------------------===//
494
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000495/// RegisterBuiltinMacro - Register the specified identifier in the identifier
496/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000497IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000498 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000499 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000500
501 // Mark it as being a macro that is builtin.
502 MacroInfo *MI = new MacroInfo(SourceLocation());
503 MI->setIsBuiltinMacro();
504 Id->setMacroInfo(MI);
505 return Id;
506}
507
508
Chris Lattner677757a2006-06-28 05:26:32 +0000509/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
510/// identifier table.
511void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000512 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000513 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000514 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
515 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000516 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000517
518 // GCC Extensions.
519 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
520 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000521 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000522}
523
Chris Lattnerc2395832006-07-09 00:57:04 +0000524/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
525/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000526static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
527 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000528 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
529
530 // If the token isn't an identifier, it's always literally expanded.
531 if (II == 0) return true;
532
533 // If the identifier is a macro, and if that macro is enabled, it may be
534 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000535 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
536 // Fast expanding "#define X X" is ok, because X would be disabled.
537 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000538 return false;
539
540 // If this is an object-like macro invocation, it is safe to trivially expand
541 // it.
542 if (MI->isObjectLike()) return true;
543
544 // If this is a function-like macro invocation, it's safe to trivially expand
545 // as long as the identifier is not a macro argument.
546 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
547 I != E; ++I)
548 if (*I == II)
549 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000550
Chris Lattnerc2395832006-07-09 00:57:04 +0000551 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000552}
553
Chris Lattnerc2395832006-07-09 00:57:04 +0000554
Chris Lattnerafe603f2006-07-11 04:02:46 +0000555/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
556/// lexed is a '('. If so, consume the token and return true, if not, this
557/// method should have no observable side-effect on the lexed tokens.
558bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000559 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000560 unsigned Val;
561 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000562 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000563 else
564 Val = CurMacroExpander->isNextTokenLParen();
565
566 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000567 // We have run off the end. If it's a source file we don't
568 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
569 // macro stack.
570 if (CurLexer)
571 return false;
572 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000573 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
574 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000575 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000576 else
577 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000578
579 if (Val != 2)
580 break;
581
582 // Ran off the end of a source file?
583 if (Entry.TheLexer)
584 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000585 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000586 }
587
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000588 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
589 // have found something that isn't a '(' or we found the end of the
590 // translation unit. In either case, return false.
591 if (Val != 1)
592 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000593
Chris Lattner146762e2007-07-20 16:59:19 +0000594 Token Tok;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000595 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000596 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
597 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000598}
Chris Lattner677757a2006-06-28 05:26:32 +0000599
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000600/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
601/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner146762e2007-07-20 16:59:19 +0000602bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000603 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000604
605 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
606 if (MI->isBuiltinMacro()) {
607 ExpandBuiltinMacro(Identifier);
608 return false;
609 }
610
Chris Lattner81278c62006-10-14 19:03:49 +0000611 // If this is the first use of a target-specific macro, warn about it.
612 if (MI->isTargetSpecific()) {
613 MI->setIsTargetSpecific(false); // Don't warn on second use.
614 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
615 diag::port_target_macro_use);
616 }
617
Chris Lattneree8760b2006-07-15 07:42:55 +0000618 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000619 /// for each macro argument, the list of tokens that were provided to the
620 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000621 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000622
623 // If this is a function-like macro, read the arguments.
624 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000625 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000626 // name isn't a '(', this macro should not be expanded. Otherwise, consume
627 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000628 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000629 return true;
630
Chris Lattner78186052006-07-09 00:45:31 +0000631 // Remember that we are now parsing the arguments to a macro invocation.
632 // Preprocessor directives used inside macro arguments are not portable, and
633 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000634 InMacroArgs = true;
635 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000636
637 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000638 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000639
640 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000641 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000642
643 ++NumFnMacroExpanded;
644 } else {
645 ++NumMacroExpanded;
646 }
Chris Lattner13044d92006-07-03 05:16:44 +0000647
648 // Notice that this macro has been used.
649 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000650
651 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000652
653 // If this macro expands to no tokens, don't bother to push it onto the
654 // expansion stack, only to take it right back off.
655 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000656 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000657 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000658
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000659 // Ignore this macro use, just return the next token in the current
660 // buffer.
661 bool HadLeadingSpace = Identifier.hasLeadingSpace();
662 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
663
664 Lex(Identifier);
665
666 // If the identifier isn't on some OTHER line, inherit the leading
667 // whitespace/first-on-a-line property of this token. This handles
668 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
669 // empty.
670 if (!Identifier.isAtStartOfLine()) {
Chris Lattner146762e2007-07-20 16:59:19 +0000671 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
672 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000673 }
674 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000675 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000676
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000677 } else if (MI->getNumTokens() == 1 &&
678 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000679 // Otherwise, if this macro expands into a single trivially-expanded
680 // token: expand it now. This handles common cases like
681 // "#define VAL 42".
682
683 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
684 // identifier to the expanded token.
685 bool isAtStartOfLine = Identifier.isAtStartOfLine();
686 bool hasLeadingSpace = Identifier.hasLeadingSpace();
687
688 // Remember where the token is instantiated.
689 SourceLocation InstantiateLoc = Identifier.getLocation();
690
691 // Replace the result token.
692 Identifier = MI->getReplacementToken(0);
693
694 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner146762e2007-07-20 16:59:19 +0000695 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
696 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000697
698 // Update the tokens location to include both its logical and physical
699 // locations.
700 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000701 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000702 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000703
Chris Lattner6e4bf522006-07-27 06:59:25 +0000704 // If this is #define X X, we must mark the result as unexpandible.
705 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
706 if (NewII->getMacroInfo() == MI)
Chris Lattner146762e2007-07-20 16:59:19 +0000707 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000708
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000709 // Since this is not an identifier token, it can't be macro expanded, so
710 // we're done.
711 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000712 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000713 }
714
Chris Lattner78186052006-07-09 00:45:31 +0000715 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000716 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000717
718 // Now that the macro is at the top of the include stack, ask the
719 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000720 Lex(Identifier);
721 return false;
722}
723
Chris Lattneree8760b2006-07-15 07:42:55 +0000724/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000725/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000726/// invocation. This returns null on error.
Chris Lattner146762e2007-07-20 16:59:19 +0000727MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattneree8760b2006-07-15 07:42:55 +0000728 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000729 // The number of fixed arguments to parse.
730 unsigned NumFixedArgsLeft = MI->getNumArgs();
731 bool isVariadic = MI->isVariadic();
732
Chris Lattner78186052006-07-09 00:45:31 +0000733 // Outer loop, while there are more arguments, keep reading them.
Chris Lattner146762e2007-07-20 16:59:19 +0000734 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000735 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000736 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000737
738 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000739 // argument is separated by an EOF token. Use a SmallVector so we can avoid
740 // heap allocations in the common case.
Chris Lattner146762e2007-07-20 16:59:19 +0000741 llvm::SmallVector<Token, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000742
743 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000744 while (Tok.getKind() == tok::comma) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000745 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
746 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000747 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000748
Chris Lattner78186052006-07-09 00:45:31 +0000749 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000750 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
751 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000752 LexUnexpandedToken(Tok);
753
754 if (Tok.getKind() == tok::eof) {
755 Diag(MacroName, diag::err_unterm_macro_invoc);
756 // Do not lose the EOF. Return it to the client.
757 MacroName = Tok;
758 return 0;
759 } else if (Tok.getKind() == tok::r_paren) {
760 // If we found the ) token, the macro arg list is done.
761 if (NumParens-- == 0)
762 break;
763 } else if (Tok.getKind() == tok::l_paren) {
764 ++NumParens;
765 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
766 // Comma ends this argument if there are more fixed arguments expected.
767 if (NumFixedArgsLeft)
768 break;
769
Chris Lattner2ada5d32006-07-15 07:51:24 +0000770 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000771 if (!isVariadic) {
772 // Emit the diagnostic at the macro name in case there is a missing ).
773 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000774 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000775 return 0;
776 }
777 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000778 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000779 // If this is a comment token in the argument list and we're just in
780 // -C mode (not -CC mode), discard the comment.
781 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000782 }
783
784 ArgTokens.push_back(Tok);
785 }
786
Chris Lattnera12dd152006-07-11 04:09:02 +0000787 // Empty arguments are standard in C99 and supported as an extension in
788 // other modes.
789 if (ArgTokens.empty() && !Features.C99)
790 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000791
Chris Lattner36b6e812006-07-21 06:38:30 +0000792 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattner146762e2007-07-20 16:59:19 +0000793 Token EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000794 EOFTok.startToken();
795 EOFTok.setKind(tok::eof);
796 EOFTok.setLocation(Tok.getLocation());
797 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000798 ArgTokens.push_back(EOFTok);
799 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000800 --NumFixedArgsLeft;
801 };
802
803 // Okay, we either found the r_paren. Check to see if we parsed too few
804 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000805 unsigned MinArgsExpected = MI->getNumArgs();
806
Chris Lattner775d8322006-07-29 04:39:41 +0000807 // See MacroArgs instance var for description of this.
808 bool isVarargsElided = false;
809
Chris Lattner2ada5d32006-07-15 07:51:24 +0000810 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000811 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000812 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000813 // Varargs where the named vararg parameter is missing: ok as extension.
814 // #define A(x, ...)
815 // A("blah")
816 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000817
818 // Remember this occurred if this is a C99 macro invocation with at least
819 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000820 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000821 } else if (MI->getNumArgs() == 1) {
822 // #define A(x)
823 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000824 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000825
826 // Empty arguments are standard in C99 and supported as an extension in
827 // other modes.
828 if (ArgTokens.empty() && !Features.C99)
829 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000830 } else {
831 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000832 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000833 return 0;
834 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000835
836 // Add a marker EOF token to the end of the token list for this argument.
837 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000838 Tok.startToken();
839 Tok.setKind(tok::eof);
840 Tok.setLocation(EndLoc);
841 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000842 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000843 }
844
Chris Lattner775d8322006-07-29 04:39:41 +0000845 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000846}
847
Chris Lattnerc673f902006-06-30 06:10:41 +0000848/// ComputeDATE_TIME - Compute the current time, enter it into the specified
849/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
850/// the identifier tokens inserted.
851static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000852 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000853 time_t TT = time(0);
854 struct tm *TM = localtime(&TT);
855
856 static const char * const Months[] = {
857 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
858 };
859
860 char TmpBuffer[100];
861 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
862 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000863 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000864
865 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000866 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000867}
868
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000869/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
870/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000871void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000872 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000873 IdentifierInfo *II = Tok.getIdentifierInfo();
874 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000875
876 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
877 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000878 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000879 return Handle_Pragma(Tok);
880
Chris Lattner78186052006-07-09 00:45:31 +0000881 ++NumBuiltinMacroExpanded;
882
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000883 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000884
885 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000886 Tok.setIdentifierInfo(0);
Chris Lattner146762e2007-07-20 16:59:19 +0000887 Tok.clearFlag(Token::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000888
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000889 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000890 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000891 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000892 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000893 Tok.setKind(tok::numeric_constant);
894 Tok.setLength(Length);
895 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000896 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000897 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000898 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000899 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000900 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
901 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000902 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000903 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +0000904 }
905 }
906
Chris Lattner0766e592006-07-03 01:07:01 +0000907 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000908 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +0000909 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000910 Tok.setKind(tok::string_literal);
911 Tok.setLength(FN.size());
912 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000913 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000914 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000915 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000916 Tok.setKind(tok::string_literal);
917 Tok.setLength(strlen("\"Mmm dd yyyy\""));
918 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000919 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000920 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000921 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000922 Tok.setKind(tok::string_literal);
923 Tok.setLength(strlen("\"hh:mm:ss\""));
924 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000925 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000926 Diag(Tok, diag::ext_pp_include_level);
927
928 // Compute the include depth of this token.
929 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000930 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
931 for (; Loc.isValid(); ++Depth)
932 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +0000933
934 // __INCLUDE_LEVEL__ expands to a simple numeric value.
935 sprintf(TmpBuffer, "%u", Depth);
936 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000937 Tok.setKind(tok::numeric_constant);
938 Tok.setLength(Length);
939 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000940 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000941 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
942 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
943 Diag(Tok, diag::ext_pp_timestamp);
944
945 // Get the file that we are lexing out of. If we're currently lexing from
946 // a macro, dig into the include stack.
947 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000948 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000949
950 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000951 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +0000952
953 // If this file is older than the file it depends on, emit a diagnostic.
954 const char *Result;
955 if (CurFile) {
956 time_t TT = CurFile->getModificationTime();
957 struct tm *TM = localtime(&TT);
958 Result = asctime(TM);
959 } else {
960 Result = "??? ??? ?? ??:??:?? ????\n";
961 }
962 TmpBuffer[0] = '"';
963 strcpy(TmpBuffer+1, Result);
964 unsigned Len = strlen(TmpBuffer);
965 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000966 Tok.setKind(tok::string_literal);
967 Tok.setLength(Len);
968 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000969 } else {
970 assert(0 && "Unknown identifier!");
971 }
972}
Chris Lattner677757a2006-06-28 05:26:32 +0000973
974//===----------------------------------------------------------------------===//
975// Lexer Event Handling.
976//===----------------------------------------------------------------------===//
977
Chris Lattnercefc7682006-07-08 08:28:12 +0000978/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
979/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +0000980IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +0000981 const char *BufPtr) {
982 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
983 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
984
985 // Look up this token, see if it is a macro, or if it is a language keyword.
986 IdentifierInfo *II;
987 if (BufPtr && !Identifier.needsCleaning()) {
988 // No cleaning needed, just use the characters from the lexed buffer.
989 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
990 } else {
991 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +0000992 llvm::SmallVector<char, 64> IdentifierBuffer;
993 IdentifierBuffer.resize(Identifier.getLength());
994 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +0000995 unsigned Size = getSpelling(Identifier, TmpBuf);
996 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
997 }
Chris Lattner8c204872006-10-14 05:19:21 +0000998 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000999 return II;
1000}
1001
1002
Chris Lattner677757a2006-06-28 05:26:32 +00001003/// HandleIdentifier - This callback is invoked when the lexer reads an
1004/// identifier. This callback looks up the identifier in the map and/or
1005/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +00001006void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001007 assert(Identifier.getIdentifierInfo() &&
1008 "Can't handle identifiers without identifier info!");
1009
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001010 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001011
1012 // If this identifier was poisoned, and if it was not produced from a macro
1013 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001014 if (II.isPoisoned() && CurLexer) {
1015 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1016 Diag(Identifier, diag::err_pp_used_poisoned_id);
1017 else
1018 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1019 }
Chris Lattner677757a2006-06-28 05:26:32 +00001020
Chris Lattner78186052006-07-09 00:45:31 +00001021 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +00001022 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001023 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1024 if (MI->isEnabled()) {
1025 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1026 return;
1027 } else {
1028 // C99 6.10.3.4p2 says that a disabled macro may never again be
1029 // expanded, even if it's in a context where it could be expanded in the
1030 // future.
Chris Lattner146762e2007-07-20 16:59:19 +00001031 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001032 }
1033 }
Chris Lattner063400e2006-10-14 19:54:15 +00001034 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1035 // If this identifier is a macro on some other target, emit a diagnostic.
1036 // This diagnosic is only emitted when macro expansion is enabled, because
1037 // the macro would not have been expanded for the other target either.
1038 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1039 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1040 diag::port_target_macro_use);
1041
1042 }
Chris Lattner677757a2006-06-28 05:26:32 +00001043
Chris Lattner5b9f4892006-11-21 17:23:33 +00001044 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1045 // then we act as if it is the actual operator and not the textual
1046 // representation of it.
1047 if (II.isCPlusPlusOperatorKeyword())
1048 Identifier.setIdentifierInfo(0);
1049
Chris Lattner677757a2006-06-28 05:26:32 +00001050 // Change the kind of this identifier to the appropriate token kind, e.g.
1051 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001052 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001053
1054 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001055 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1056 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001057 if (II.isExtensionToken() && Features.C99)
1058 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001059}
1060
Chris Lattner22eb9722006-06-18 05:43:12 +00001061/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1062/// the current file. This either returns the EOF token or pops a level off
1063/// the include stack and keeps going.
Chris Lattner146762e2007-07-20 16:59:19 +00001064bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001065 assert(!CurMacroExpander &&
1066 "Ending a file when currently in a macro!");
1067
Chris Lattner371ac8a2006-07-04 07:11:10 +00001068 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001069 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001070 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001071 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001072 // Okay, this has a controlling macro, remember in PerFileInfo.
1073 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001074 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001075 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001076 }
1077 }
1078
Chris Lattner22eb9722006-06-18 05:43:12 +00001079 // If this is a #include'd file, pop it off the include stack and continue
1080 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001081 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001082 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001083 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001084
1085 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001086 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001087 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1088
1089 // Get the file entry for the current file.
1090 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001091 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001092 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001093
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001094 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1095 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001096 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001097
1098 // Client should lex another token.
1099 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001100 }
1101
Chris Lattner8c204872006-10-14 05:19:21 +00001102 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001103 CurLexer->BufferPtr = CurLexer->BufferEnd;
1104 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001105 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001106
1107 // We're done with the #included file.
1108 delete CurLexer;
1109 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001110
Chris Lattner03f83482006-07-10 06:16:26 +00001111 // This is the end of the top-level file. If the diag::pp_macro_not_used
1112 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1113 // have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001114 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1115 for (IdentifierTable::iterator I = Identifiers.begin(),
1116 E = Identifiers.end(); I != E; ++I) {
1117 const IdentifierInfo &II = I->getValue();
1118 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1119 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1120 }
1121 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001122
1123 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001124}
1125
1126/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001127/// the current macro expansion or token stream expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001128bool Preprocessor::HandleEndOfMacro(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001129 assert(CurMacroExpander && !CurLexer &&
1130 "Ending a macro when currently in a #include file!");
1131
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001132 // Delete or cache the now-dead macro expander.
1133 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1134 delete CurMacroExpander;
1135 else
1136 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001137
Chris Lattner69772b02006-07-02 20:34:39 +00001138 // Handle this like a #include file being popped off the stack.
1139 CurMacroExpander = 0;
1140 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001141}
1142
1143
1144//===----------------------------------------------------------------------===//
1145// Utility Methods for Preprocessor Directive Handling.
1146//===----------------------------------------------------------------------===//
1147
1148/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1149/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001150void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner146762e2007-07-20 16:59:19 +00001151 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001153 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001154 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001155}
1156
Chris Lattner652c1692006-11-21 23:47:30 +00001157/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1158static bool isCXXNamedOperator(const std::string &Spelling) {
1159 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1160 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1161 Spelling == "or" || Spelling == "xor";
1162}
1163
Chris Lattner22eb9722006-06-18 05:43:12 +00001164/// ReadMacroName - Lex and validate a macro name, which occurs after a
1165/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001166/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1167/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001168/// else (e.g. #ifdef).
Chris Lattner146762e2007-07-20 16:59:19 +00001169void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001170 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001171 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001172
1173 // Missing macro name?
1174 if (MacroNameTok.getKind() == tok::eom)
1175 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1176
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001177 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1178 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001179 std::string Spelling = getSpelling(MacroNameTok);
1180 if (isCXXNamedOperator(Spelling))
1181 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1182 // except for their spellings.
1183 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1184 else
1185 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001186 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001187 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001188 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001189 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001190 } else if (isDefineUndef && II->getMacroInfo() &&
1191 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001192 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001193 if (isDefineUndef == 1)
1194 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1195 else
1196 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001197 } else {
1198 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001199 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001200 }
1201
Chris Lattner22eb9722006-06-18 05:43:12 +00001202 // Invalid macro name, read and discard the rest of the line. Then set the
1203 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001204 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001205 return DiscardUntilEndOfDirective();
1206}
1207
1208/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1209/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001210void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner146762e2007-07-20 16:59:19 +00001211 Token Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001212 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001213 // There should be no tokens after the directive, but we allow them as an
1214 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001215 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1216 Lex(Tmp);
1217
Chris Lattner22eb9722006-06-18 05:43:12 +00001218 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001219 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1220 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001221 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001222}
1223
1224
1225
1226/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1227/// decided that the subsequent tokens are in the #if'd out portion of the
1228/// file. Lex the rest of the file, until we see an #endif. If
1229/// FoundNonSkipPortion is true, then we have already emitted code for part of
1230/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1231/// is true, then #else directives are ok, if not, then we have already seen one
1232/// so a #else directive is a duplicate. When this returns, the caller can lex
1233/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001234void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001235 bool FoundNonSkipPortion,
1236 bool FoundElse) {
1237 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001238 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001239 "Lexing a macro, not a file?");
1240
1241 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1242 FoundNonSkipPortion, FoundElse);
1243
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001244 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1245 // disabling warnings, etc.
1246 CurLexer->LexingRawMode = true;
Chris Lattner146762e2007-07-20 16:59:19 +00001247 Token Tok;
Chris Lattner22eb9722006-06-18 05:43:12 +00001248 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001249 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001250
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001251 // If this is the end of the buffer, we have an error.
1252 if (Tok.getKind() == tok::eof) {
1253 // Emit errors for each unterminated conditional on the stack, including
1254 // the current one.
1255 while (!CurLexer->ConditionalStack.empty()) {
1256 Diag(CurLexer->ConditionalStack.back().IfLoc,
1257 diag::err_pp_unterminated_conditional);
1258 CurLexer->ConditionalStack.pop_back();
1259 }
1260
1261 // Just return and let the caller lex after this #include.
1262 break;
1263 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001264
1265 // If this token is not a preprocessor directive, just skip it.
1266 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1267 continue;
1268
1269 // We just parsed a # character at the start of a line, so we're in
1270 // directive mode. Tell the lexer this so any newlines we see will be
1271 // converted into an EOM token (this terminates the macro).
1272 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001273 CurLexer->KeepCommentMode = false;
1274
Chris Lattner22eb9722006-06-18 05:43:12 +00001275
1276 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001277 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001278
1279 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1280 // something bogus), skip it.
1281 if (Tok.getKind() != tok::identifier) {
1282 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001283 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001284 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001285 continue;
1286 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001287
Chris Lattner22eb9722006-06-18 05:43:12 +00001288 // If the first letter isn't i or e, it isn't intesting to us. We know that
1289 // this is safe in the face of spelling differences, because there is no way
1290 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001291 // allows us to avoid looking up the identifier info for #define/#undef and
1292 // other common directives.
1293 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1294 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001295 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1296 FirstChar != 'i' && FirstChar != 'e') {
1297 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001298 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001299 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001300 continue;
1301 }
1302
Chris Lattnere60165f2006-06-22 06:36:29 +00001303 // Get the identifier name without trigraphs or embedded newlines. Note
1304 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1305 // when skipping.
1306 // TODO: could do this with zero copies in the no-clean case by using
1307 // strncmp below.
1308 char Directive[20];
1309 unsigned IdLen;
1310 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1311 IdLen = Tok.getLength();
1312 memcpy(Directive, RawCharData, IdLen);
1313 Directive[IdLen] = 0;
1314 } else {
1315 std::string DirectiveStr = getSpelling(Tok);
1316 IdLen = DirectiveStr.size();
1317 if (IdLen >= 20) {
1318 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001319 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001320 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001321 continue;
1322 }
1323 memcpy(Directive, &DirectiveStr[0], IdLen);
1324 Directive[IdLen] = 0;
1325 }
1326
Chris Lattner22eb9722006-06-18 05:43:12 +00001327 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001328 if ((IdLen == 2) || // "if"
1329 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1330 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001331 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1332 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001333 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001334 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001335 /*foundnonskip*/false,
1336 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001337 }
1338 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001339 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001340 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001341 PPConditionalInfo CondInfo;
1342 CondInfo.WasSkipping = true; // Silence bogus warning.
1343 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001344 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 assert(!InCond && "Can't be skipping if not in a conditional!");
1346
1347 // If we popped the outermost skipping block, we're done skipping!
1348 if (!CondInfo.WasSkipping)
1349 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001350 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001351 // #else directive in a skipping conditional. If not in some other
1352 // skipping conditional, and if #else hasn't already been seen, enter it
1353 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001354 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001355 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1356
1357 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001358 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001359
1360 // Note that we've seen a #else in this conditional.
1361 CondInfo.FoundElse = true;
1362
1363 // If the conditional is at the top level, and the #if block wasn't
1364 // entered, enter the #else block now.
1365 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1366 CondInfo.FoundNonSkip = true;
1367 break;
1368 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001369 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001370 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1371
1372 bool ShouldEnter;
1373 // If this is in a skipping block or if we're already handled this #if
1374 // block, don't bother parsing the condition.
1375 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001376 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001377 ShouldEnter = false;
1378 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001379 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001381 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1382 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001383 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001384 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001385 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001386 }
1387
1388 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001389 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001390
1391 // If this condition is true, enter it!
1392 if (ShouldEnter) {
1393 CondInfo.FoundNonSkip = true;
1394 break;
1395 }
1396 }
1397 }
1398
1399 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001400 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001401 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001402 }
1403
1404 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1405 // of the file, just stop skipping and return to lexing whatever came after
1406 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001407 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001408}
1409
1410//===----------------------------------------------------------------------===//
1411// Preprocessor Directive Handling.
1412//===----------------------------------------------------------------------===//
1413
1414/// HandleDirective - This callback is invoked when the lexer sees a # token
1415/// at the start of a line. This consumes the directive, modifies the
1416/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1417/// read is the correct one.
Chris Lattner146762e2007-07-20 16:59:19 +00001418void Preprocessor::HandleDirective(Token &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001419 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001420
1421 // We just parsed a # character at the start of a line, so we're in directive
1422 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001423 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001424 CurLexer->ParsingPreprocessorDirective = true;
1425
1426 ++NumDirectives;
1427
Chris Lattner371ac8a2006-07-04 07:11:10 +00001428 // We are about to read a token. For the multiple-include optimization FA to
1429 // work, we have to remember if we had read any tokens *before* this
1430 // pp-directive.
1431 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1432
Chris Lattner78186052006-07-09 00:45:31 +00001433 // Read the next token, the directive flavor. This isn't expanded due to
1434 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001435 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001436
Chris Lattner78186052006-07-09 00:45:31 +00001437 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1438 // #define A(x) #x
1439 // A(abc
1440 // #warning blah
1441 // def)
1442 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001443 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001444 Diag(Result, diag::ext_embedded_directive);
1445
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001446TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001447 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001448 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001449 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001450 case tok::comment:
1451 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1452 LexUnexpandedToken(Result);
1453 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001454
Chris Lattner22eb9722006-06-18 05:43:12 +00001455 case tok::numeric_constant:
1456 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001457 DiscardUntilEndOfDirective();
1458 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001459 default:
1460 IdentifierInfo *II = Result.getIdentifierInfo();
1461 if (II == 0) break; // Not an identifier.
1462
1463 // Ask what the preprocessor keyword ID is.
1464 switch (II->getPPKeywordID()) {
1465 default: break;
1466 // C99 6.10.1 - Conditional Inclusion.
1467 case tok::pp_if:
1468 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1469 case tok::pp_ifdef:
1470 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1471 case tok::pp_ifndef:
1472 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1473 case tok::pp_elif:
1474 return HandleElifDirective(Result);
1475 case tok::pp_else:
1476 return HandleElseDirective(Result);
1477 case tok::pp_endif:
1478 return HandleEndifDirective(Result);
1479
1480 // C99 6.10.2 - Source File Inclusion.
1481 case tok::pp_include:
1482 return HandleIncludeDirective(Result); // Handle #include.
1483
1484 // C99 6.10.3 - Macro Replacement.
1485 case tok::pp_define:
1486 return HandleDefineDirective(Result, false);
1487 case tok::pp_undef:
1488 return HandleUndefDirective(Result);
1489
1490 // C99 6.10.4 - Line Control.
1491 case tok::pp_line:
1492 // FIXME: implement #line
1493 DiscardUntilEndOfDirective();
1494 return;
1495
1496 // C99 6.10.5 - Error Directive.
1497 case tok::pp_error:
1498 return HandleUserDiagnosticDirective(Result, false);
1499
1500 // C99 6.10.6 - Pragma Directive.
1501 case tok::pp_pragma:
1502 return HandlePragmaDirective();
1503
1504 // GNU Extensions.
1505 case tok::pp_import:
1506 return HandleImportDirective(Result);
1507 case tok::pp_include_next:
1508 return HandleIncludeNextDirective(Result);
1509
1510 case tok::pp_warning:
1511 Diag(Result, diag::ext_pp_warning_directive);
1512 return HandleUserDiagnosticDirective(Result, true);
1513 case tok::pp_ident:
1514 return HandleIdentSCCSDirective(Result);
1515 case tok::pp_sccs:
1516 return HandleIdentSCCSDirective(Result);
1517 case tok::pp_assert:
1518 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001519 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001520 case tok::pp_unassert:
1521 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001522 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001523
1524 // clang extensions.
1525 case tok::pp_define_target:
1526 return HandleDefineDirective(Result, true);
1527 case tok::pp_define_other_target:
1528 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001529 }
1530 break;
1531 }
1532
1533 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001534 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001535
1536 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001537 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001538
1539 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001540}
1541
Chris Lattner146762e2007-07-20 16:59:19 +00001542void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001543 bool isWarning) {
1544 // Read the rest of the line raw. We do this because we don't want macros
1545 // to be expanded and we don't require that the tokens be valid preprocessing
1546 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1547 // collapse multiple consequtive white space between tokens, but this isn't
1548 // specified by the standard.
1549 std::string Message = CurLexer->ReadToEndOfLine();
1550
1551 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001552 return Diag(Tok, DiagID, Message);
1553}
1554
1555/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1556///
Chris Lattner146762e2007-07-20 16:59:19 +00001557void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001558 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001559 Diag(Tok, diag::ext_pp_ident_directive);
1560
Chris Lattner371ac8a2006-07-04 07:11:10 +00001561 // Read the string argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001562 Token StrTok;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001563 Lex(StrTok);
1564
1565 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001566 if (StrTok.getKind() != tok::string_literal &&
1567 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001568 return Diag(StrTok, diag::err_pp_malformed_ident);
1569
1570 // Verify that there is nothing after the string, other than EOM.
1571 CheckEndOfDirective("#ident");
1572
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001573 if (Callbacks)
1574 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001575}
1576
Chris Lattnerb8761832006-06-24 21:31:03 +00001577//===----------------------------------------------------------------------===//
1578// Preprocessor Include Directive Handling.
1579//===----------------------------------------------------------------------===//
1580
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001581/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1582/// checked and spelled filename, e.g. as an operand of #include. This returns
1583/// true if the input filename was in <>'s or false if it were in ""'s. The
1584/// caller is expected to provide a buffer that is large enough to hold the
1585/// spelling of the filename, but is also expected to handle the case when
1586/// this method decides to use a different buffer.
Chris Lattner93ab9f12007-07-23 04:15:27 +00001587bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001588 const char *&BufStart,
1589 const char *&BufEnd) {
1590 // Get the text form of the filename.
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001591 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1592
1593 // Make sure the filename is <x> or "x".
1594 bool isAngled;
1595 if (BufStart[0] == '<') {
1596 if (BufEnd[-1] != '>') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001597 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001598 BufStart = 0;
1599 return true;
1600 }
1601 isAngled = true;
1602 } else if (BufStart[0] == '"') {
1603 if (BufEnd[-1] != '"') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001604 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001605 BufStart = 0;
1606 return true;
1607 }
1608 isAngled = false;
1609 } else {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001610 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001611 BufStart = 0;
1612 return true;
1613 }
1614
1615 // Diagnose #include "" as invalid.
1616 if (BufEnd-BufStart <= 2) {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001617 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001618 BufStart = 0;
1619 return "";
1620 }
1621
1622 // Skip the brackets.
1623 ++BufStart;
1624 --BufEnd;
1625 return isAngled;
1626}
1627
Chris Lattner43eafb42007-07-23 04:56:47 +00001628/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1629/// from a macro as multiple tokens, which need to be glued together. This
1630/// occurs for code like:
1631/// #define FOO <a/b.h>
1632/// #include FOO
1633/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1634///
1635/// This code concatenates and consumes tokens up to the '>' token. It returns
1636/// false if the > was found, otherwise it returns true if it finds and consumes
1637/// the EOM marker.
1638static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1639 Preprocessor &PP) {
1640 Token CurTok;
1641
1642 PP.Lex(CurTok);
1643 while (CurTok.getKind() != tok::eom) {
1644 // Append the spelling of this token to the buffer. If there was a space
1645 // before it, add it now.
1646 if (CurTok.hasLeadingSpace())
1647 FilenameBuffer.push_back(' ');
1648
1649 // Get the spelling of the token, directly into FilenameBuffer if possible.
1650 unsigned PreAppendSize = FilenameBuffer.size();
1651 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1652
1653 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1654 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1655
1656 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1657 if (BufPtr != &FilenameBuffer[PreAppendSize])
1658 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1659
1660 // Resize FilenameBuffer to the correct size.
1661 if (CurTok.getLength() != ActualLen)
1662 FilenameBuffer.resize(PreAppendSize+ActualLen);
1663
1664 // If we found the '>' marker, return success.
1665 if (CurTok.getKind() == tok::greater)
1666 return false;
1667
1668 PP.Lex(CurTok);
1669 }
1670
1671 // If we hit the eom marker, emit an error and return true so that the caller
1672 // knows the EOM has been read.
1673 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1674 return true;
1675}
1676
Chris Lattner22eb9722006-06-18 05:43:12 +00001677/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1678/// file to be included from the lexer, then include it! This is a common
1679/// routine with functionality shared between #include, #include_next and
1680/// #import.
Chris Lattner146762e2007-07-20 16:59:19 +00001681void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001682 const DirectoryLookup *LookupFrom,
1683 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001684
Chris Lattner146762e2007-07-20 16:59:19 +00001685 Token FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001686 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001687
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001688 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001689 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner43eafb42007-07-23 04:56:47 +00001690 const char *FilenameStart, *FilenameEnd;
1691
1692 switch (FilenameTok.getKind()) {
1693 case tok::eom:
1694 // If the token kind is EOM, the error has already been diagnosed.
1695 return;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001696
Chris Lattner43eafb42007-07-23 04:56:47 +00001697 case tok::angle_string_literal:
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001698 case tok::string_literal: {
Chris Lattner43eafb42007-07-23 04:56:47 +00001699 FilenameBuffer.resize(FilenameTok.getLength());
1700 FilenameStart = &FilenameBuffer[0];
1701 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1702 FilenameEnd = FilenameStart+Len;
1703 break;
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001704 }
Chris Lattner43eafb42007-07-23 04:56:47 +00001705
1706 case tok::less:
1707 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1708 // case, glue the tokens together into FilenameBuffer and interpret those.
1709 FilenameBuffer.push_back('<');
1710 if (ConcatenateIncludeName(FilenameBuffer, *this))
1711 return; // Found <eom> but no ">"? Diagnostic already emitted.
1712 FilenameStart = &FilenameBuffer[0];
1713 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1714 break;
1715 default:
1716 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1717 DiscardUntilEndOfDirective();
1718 return;
1719 }
1720
Chris Lattner93ab9f12007-07-23 04:15:27 +00001721 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001722 FilenameStart, FilenameEnd);
1723 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1724 // error.
Chris Lattner43eafb42007-07-23 04:56:47 +00001725 if (FilenameStart == 0) {
1726 DiscardUntilEndOfDirective();
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001727 return;
Chris Lattner43eafb42007-07-23 04:56:47 +00001728 }
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001729
Chris Lattner269c2322006-06-25 06:23:00 +00001730 // Verify that there is nothing after the filename, other than EOM. Use the
1731 // preprocessor to lex this in case lexing the filename entered a macro.
1732 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001733
1734 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001735 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001736 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1737
Chris Lattner22eb9722006-06-18 05:43:12 +00001738 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001739 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001740 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001741 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001742 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001743 return Diag(FilenameTok, diag::err_pp_file_not_found,
1744 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001745
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001746 // Ask HeaderInfo if we should enter this #include file.
1747 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1748 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001749 return;
1750 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001751
1752 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001753 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001754 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001755 return Diag(FilenameTok, diag::err_pp_file_not_found,
1756 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001757
1758 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001759 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001760}
1761
1762/// HandleIncludeNextDirective - Implements #include_next.
1763///
Chris Lattner146762e2007-07-20 16:59:19 +00001764void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001765 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001766
1767 // #include_next is like #include, except that we start searching after
1768 // the current found directory. If we can't do this, issue a
1769 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001770 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001771 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001772 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001773 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001774 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001775 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001776 } else {
1777 // Start looking up in the next directory.
1778 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001779 }
1780
1781 return HandleIncludeDirective(IncludeNextTok, Lookup);
1782}
1783
1784/// HandleImportDirective - Implements #import.
1785///
Chris Lattner146762e2007-07-20 16:59:19 +00001786void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001787 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001788
1789 return HandleIncludeDirective(ImportTok, 0, true);
1790}
1791
Chris Lattnerb8761832006-06-24 21:31:03 +00001792//===----------------------------------------------------------------------===//
1793// Preprocessor Macro Directive Handling.
1794//===----------------------------------------------------------------------===//
1795
Chris Lattnercefc7682006-07-08 08:28:12 +00001796/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1797/// definition has just been read. Lex the rest of the arguments and the
1798/// closing ), updating MI with what we learn. Return true if an error occurs
1799/// parsing the arg list.
1800bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001801 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1802
Chris Lattner146762e2007-07-20 16:59:19 +00001803 Token Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001804 while (1) {
1805 LexUnexpandedToken(Tok);
1806 switch (Tok.getKind()) {
1807 case tok::r_paren:
1808 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001809 if (Arguments.empty()) { // #define FOO()
1810 MI->setArgumentList(Arguments.begin(), Arguments.end());
1811 return false;
1812 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001813 // Otherwise we have #define FOO(A,)
1814 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1815 return true;
1816 case tok::ellipsis: // #define X(... -> C99 varargs
1817 // Warn if use of C99 feature in non-C99 mode.
1818 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1819
1820 // Lex the token after the identifier.
1821 LexUnexpandedToken(Tok);
1822 if (Tok.getKind() != tok::r_paren) {
1823 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1824 return true;
1825 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001826 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001827 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001828 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001829 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001830 return false;
1831 case tok::eom: // #define X(
1832 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1833 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001834 default:
1835 // Handle keywords and identifiers here to accept things like
1836 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001837 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001838 if (II == 0) {
1839 // #define X(1
1840 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1841 return true;
1842 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001843
1844 // If this is already used as an argument, it is used multiple times (e.g.
1845 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00001846 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1847 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001848 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1849 return true;
1850 }
1851
1852 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00001853 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001854
1855 // Lex the token after the identifier.
1856 LexUnexpandedToken(Tok);
1857
1858 switch (Tok.getKind()) {
1859 default: // #define X(A B
1860 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1861 return true;
1862 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00001863 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001864 return false;
1865 case tok::comma: // #define X(A,
1866 break;
1867 case tok::ellipsis: // #define X(A... -> GCC extension
1868 // Diagnose extension.
1869 Diag(Tok, diag::ext_named_variadic_macro);
1870
1871 // Lex the token after the identifier.
1872 LexUnexpandedToken(Tok);
1873 if (Tok.getKind() != tok::r_paren) {
1874 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1875 return true;
1876 }
1877
1878 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001879 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001880 return false;
1881 }
1882 }
1883 }
1884}
1885
Chris Lattner22eb9722006-06-18 05:43:12 +00001886/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001887/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1888/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001889///
Chris Lattner146762e2007-07-20 16:59:19 +00001890void Preprocessor::HandleDefineDirective(Token &DefineTok,
Chris Lattner81278c62006-10-14 19:03:49 +00001891 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001892 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001893
Chris Lattner146762e2007-07-20 16:59:19 +00001894 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001895 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001896
1897 // Error reading macro name? If so, diagnostic already issued.
1898 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001899 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00001900
Chris Lattner457fc152006-07-29 06:30:25 +00001901 // If we are supposed to keep comments in #defines, reenable comment saving
1902 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001903 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001904
Chris Lattner063400e2006-10-14 19:54:15 +00001905 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001906 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001907 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001908
Chris Lattner063400e2006-10-14 19:54:15 +00001909 // If the identifier is an 'other target' macro, clear this bit.
1910 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1911
1912
Chris Lattner146762e2007-07-20 16:59:19 +00001913 Token Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001914 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001915
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001916 // If this is a function-like macro definition, parse the argument list,
1917 // marking each of the identifiers as being used as macro arguments. Also,
1918 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001919 if (Tok.getKind() == tok::eom) {
1920 // If there is no body to this macro, we have no special handling here.
1921 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001922 // This is a function-like macro definition. Read the argument list.
1923 MI->setIsFunctionLike();
1924 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001925 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001926 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001927 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001928 if (CurLexer->ParsingPreprocessorDirective)
1929 DiscardUntilEndOfDirective();
1930 return;
1931 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001932
Chris Lattner815a1f92006-07-08 20:48:04 +00001933 // Read the first token after the arg list for down below.
1934 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001935 } else if (!Tok.hasLeadingSpace()) {
1936 // C99 requires whitespace between the macro definition and the body. Emit
1937 // a diagnostic for something like "#define X+".
1938 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001939 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001940 } else {
1941 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1942 // one in some cases!
1943 }
1944 } else {
1945 // This is a normal token with leading space. Clear the leading space
1946 // marker on the first token to get proper expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001947 Tok.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001948 }
1949
Chris Lattner7e374832006-07-29 03:46:57 +00001950 // If this is a definition of a variadic C99 function-like macro, not using
1951 // the GNU named varargs extension, enabled __VA_ARGS__.
1952
1953 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1954 // This gets unpoisoned where it is allowed.
1955 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1956 if (MI->isC99Varargs())
1957 Ident__VA_ARGS__->setIsPoisoned(false);
1958
Chris Lattner22eb9722006-06-18 05:43:12 +00001959 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00001960 if (MI->isObjectLike()) {
1961 // Object-like macros are very simple, just read their body.
1962 while (Tok.getKind() != tok::eom) {
1963 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001964 // Get the next token of the macro.
1965 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001966 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001967
Chris Lattnera3834342007-07-14 21:54:03 +00001968 } else {
1969 // Otherwise, read the body of a function-like macro. This has to validate
1970 // the # (stringize) operator.
1971 while (Tok.getKind() != tok::eom) {
1972 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001973
Chris Lattnera3834342007-07-14 21:54:03 +00001974 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1975 // parameters in function-like macro expansions.
1976 if (Tok.getKind() != tok::hash) {
1977 // Get the next token of the macro.
1978 LexUnexpandedToken(Tok);
1979 continue;
1980 }
1981
1982 // Get the next token of the macro.
1983 LexUnexpandedToken(Tok);
1984
1985 // Not a macro arg identifier?
1986 if (!Tok.getIdentifierInfo() ||
1987 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1988 Diag(Tok, diag::err_pp_stringize_not_parameter);
1989 delete MI;
1990
1991 // Disable __VA_ARGS__ again.
1992 Ident__VA_ARGS__->setIsPoisoned(true);
1993 return;
1994 }
1995
1996 // Things look ok, add the param name token to the macro.
1997 MI->AddTokenToBody(Tok);
1998
1999 // Get the next token of the macro.
2000 LexUnexpandedToken(Tok);
2001 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002002 }
Chris Lattner7e374832006-07-29 03:46:57 +00002003
Chris Lattnerf40fe992007-07-14 22:11:41 +00002004
Chris Lattner7e374832006-07-29 03:46:57 +00002005 // Disable __VA_ARGS__ again.
2006 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002007
Chris Lattnerbff18d52006-07-06 04:49:18 +00002008 // Check that there is no paste (##) operator at the begining or end of the
2009 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00002010 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00002011 if (NumTokens != 0) {
2012 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002013 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002014 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002015 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002016 }
2017 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002018 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002019 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002020 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002021 }
2022 }
2023
Chris Lattner13044d92006-07-03 05:16:44 +00002024 // If this is the primary source file, remember that this macro hasn't been
2025 // used yet.
2026 if (isInPrimaryFile())
2027 MI->setIsUsed(false);
2028
Chris Lattner22eb9722006-06-18 05:43:12 +00002029 // Finally, if this identifier already had a macro defined for it, verify that
2030 // the macro bodies are identical and free the old definition.
2031 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00002032 if (!OtherMI->isUsed())
2033 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2034
Chris Lattner22eb9722006-06-18 05:43:12 +00002035 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00002036 // must be the same. C99 6.10.3.2.
2037 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00002038 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2039 MacroNameTok.getIdentifierInfo()->getName());
2040 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2041 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002042 delete OtherMI;
2043 }
2044
2045 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00002046}
2047
Chris Lattner063400e2006-10-14 19:54:15 +00002048/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattner146762e2007-07-20 16:59:19 +00002049void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2050 Token MacroNameTok;
Chris Lattner063400e2006-10-14 19:54:15 +00002051 ReadMacroName(MacroNameTok, 1);
2052
2053 // Error reading macro name? If so, diagnostic already issued.
2054 if (MacroNameTok.getKind() == tok::eom)
2055 return;
2056
2057 // Check to see if this is the last token on the #undef line.
2058 CheckEndOfDirective("#define_other_target");
2059
2060 // If there is already a macro defined by this name, turn it into a
2061 // target-specific define.
2062 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
2063 MI->setIsTargetSpecific(true);
2064 return;
2065 }
2066
2067 // Mark the identifier as being a macro on some other target.
2068 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2069}
2070
Chris Lattner22eb9722006-06-18 05:43:12 +00002071
2072/// HandleUndefDirective - Implements #undef.
2073///
Chris Lattner146762e2007-07-20 16:59:19 +00002074void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002075 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002076
Chris Lattner146762e2007-07-20 16:59:19 +00002077 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002078 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002079
2080 // Error reading macro name? If so, diagnostic already issued.
2081 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00002082 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002083
2084 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002085 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002086
2087 // Okay, we finally have a valid identifier to undef.
2088 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
2089
Chris Lattner063400e2006-10-14 19:54:15 +00002090 // #undef untaints an identifier if it were marked by define_other_target.
2091 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2092
Chris Lattner22eb9722006-06-18 05:43:12 +00002093 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002094 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002095
Chris Lattner13044d92006-07-03 05:16:44 +00002096 if (!MI->isUsed())
2097 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002098
2099 // Free macro definition.
2100 delete MI;
2101 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002102}
2103
2104
Chris Lattnerb8761832006-06-24 21:31:03 +00002105//===----------------------------------------------------------------------===//
2106// Preprocessor Conditional Directive Handling.
2107//===----------------------------------------------------------------------===//
2108
Chris Lattner22eb9722006-06-18 05:43:12 +00002109/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002110/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2111/// if any tokens have been returned or pp-directives activated before this
2112/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002113///
Chris Lattner146762e2007-07-20 16:59:19 +00002114void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Chris Lattner371ac8a2006-07-04 07:11:10 +00002115 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002116 ++NumIf;
Chris Lattner146762e2007-07-20 16:59:19 +00002117 Token DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002118
Chris Lattner146762e2007-07-20 16:59:19 +00002119 Token MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002120 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002121
2122 // Error reading macro name? If so, diagnostic already issued.
2123 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00002124 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002125
2126 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002127 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2128
2129 // If the start of a top-level #ifdef, inform MIOpt.
2130 if (!ReadAnyTokensBeforeDirective &&
2131 CurLexer->getConditionalStackDepth() == 0) {
2132 assert(isIfndef && "#ifdef shouldn't reach here");
2133 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2134 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002135
Chris Lattner063400e2006-10-14 19:54:15 +00002136 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2137 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00002138
Chris Lattner81278c62006-10-14 19:03:49 +00002139 // If there is a macro, process it.
2140 if (MI) {
2141 // Mark it used.
2142 MI->setIsUsed(true);
2143
2144 // If this is the first use of a target-specific macro, warn about it.
2145 if (MI->isTargetSpecific()) {
2146 MI->setIsTargetSpecific(false); // Don't warn on second use.
2147 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2148 diag::port_target_macro_use);
2149 }
Chris Lattner063400e2006-10-14 19:54:15 +00002150 } else {
2151 // Use of a target-specific macro for some other target? If so, warn.
2152 if (MII->isOtherTargetMacro()) {
2153 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2154 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2155 diag::port_target_macro_use);
2156 }
Chris Lattner81278c62006-10-14 19:03:49 +00002157 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002158
Chris Lattner22eb9722006-06-18 05:43:12 +00002159 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002160 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002161 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002162 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002163 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002164 } else {
2165 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002166 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002167 /*Foundnonskip*/false,
2168 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002169 }
2170}
2171
2172/// HandleIfDirective - Implements the #if directive.
2173///
Chris Lattner146762e2007-07-20 16:59:19 +00002174void Preprocessor::HandleIfDirective(Token &IfToken,
Chris Lattnera8654ca2006-07-04 17:42:08 +00002175 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002176 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002177
Chris Lattner371ac8a2006-07-04 07:11:10 +00002178 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002179 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002180 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002181
2182 // Should we include the stuff contained by this directive?
2183 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002184 // If this condition is equivalent to #ifndef X, and if this is the first
2185 // directive seen, handle it for the multiple-include optimization.
2186 if (!ReadAnyTokensBeforeDirective &&
2187 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2188 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2189
Chris Lattner22eb9722006-06-18 05:43:12 +00002190 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002191 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002192 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002193 } else {
2194 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002195 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002196 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002197 }
2198}
2199
2200/// HandleEndifDirective - Implements the #endif directive.
2201///
Chris Lattner146762e2007-07-20 16:59:19 +00002202void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002203 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002204
Chris Lattner22eb9722006-06-18 05:43:12 +00002205 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002206 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002207
2208 PPConditionalInfo CondInfo;
2209 if (CurLexer->popConditionalLevel(CondInfo)) {
2210 // No conditionals on the stack: this is an #endif without an #if.
2211 return Diag(EndifToken, diag::err_pp_endif_without_if);
2212 }
2213
Chris Lattner371ac8a2006-07-04 07:11:10 +00002214 // If this the end of a top-level #endif, inform MIOpt.
2215 if (CurLexer->getConditionalStackDepth() == 0)
2216 CurLexer->MIOpt.ExitTopLevelConditional();
2217
Chris Lattner538d7f32006-07-20 04:31:52 +00002218 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002219 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002220}
2221
2222
Chris Lattner146762e2007-07-20 16:59:19 +00002223void Preprocessor::HandleElseDirective(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002224 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002225
Chris Lattner22eb9722006-06-18 05:43:12 +00002226 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002227 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002228
2229 PPConditionalInfo CI;
2230 if (CurLexer->popConditionalLevel(CI))
2231 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002232
2233 // If this is a top-level #else, inform the MIOpt.
2234 if (CurLexer->getConditionalStackDepth() == 0)
2235 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002236
2237 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002238 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002239
2240 // Finally, skip the rest of the contents of this block and return the first
2241 // token after it.
2242 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2243 /*FoundElse*/true);
2244}
2245
Chris Lattner146762e2007-07-20 16:59:19 +00002246void Preprocessor::HandleElifDirective(Token &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002247 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002248
Chris Lattner22eb9722006-06-18 05:43:12 +00002249 // #elif directive in a non-skipping conditional... start skipping.
2250 // We don't care what the condition is, because we will always skip it (since
2251 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002252 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002253
2254 PPConditionalInfo CI;
2255 if (CurLexer->popConditionalLevel(CI))
2256 return Diag(ElifToken, diag::pp_err_elif_without_if);
2257
Chris Lattner371ac8a2006-07-04 07:11:10 +00002258 // If this is a top-level #elif, inform the MIOpt.
2259 if (CurLexer->getConditionalStackDepth() == 0)
2260 CurLexer->MIOpt.FoundTopLevelElse();
2261
Chris Lattner22eb9722006-06-18 05:43:12 +00002262 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002263 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002264
2265 // Finally, skip the rest of the contents of this block and return the first
2266 // token after it.
2267 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2268 /*FoundElse*/CI.FoundElse);
2269}
Chris Lattnerb8761832006-06-24 21:31:03 +00002270