blob: bc7ad12e5647ea67ee80fd33ac2e086d73fee59f [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
108/// the specified LexerToken's location, translating the token's start
109/// 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
119void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
120 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.
179std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
180 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.
212unsigned Preprocessor::getSpelling(const LexerToken &Tok,
213 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();
220 return Tok.getLength();
221 }
222
223 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000224 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225
226 // If this token contains nothing interesting, return it directly.
227 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000228 Buffer = TokStart;
229 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000230 }
231 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000232 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000233 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
234 Ptr != End; ) {
235 unsigned CharSize;
236 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
237 Ptr += CharSize;
238 }
239 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
240 "NeedsCleaning flag set on something that didn't need cleaning!");
241
242 return OutBuf-Buffer;
243}
244
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000245
246/// CreateString - Plop the specified string into a scratch buffer and return a
247/// location for it. If specified, the source location provides a source
248/// location for the token.
249SourceLocation Preprocessor::
250CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
251 if (SLoc.isValid())
252 return ScratchBuf->getToken(Buf, Len, SLoc);
253 return ScratchBuf->getToken(Buf, Len);
254}
255
256
Chris Lattner8a7003c2007-07-16 06:48:38 +0000257/// AdvanceToTokenCharacter - Given a location that specifies the start of a
258/// token, return a new location that specifies a character within the token.
259SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
260 unsigned CharNo) {
261 // If they request the first char of the token, we're trivially done.
262 if (CharNo == 0) return TokStart;
263
264 // Figure out how many physical characters away the specified logical
265 // character is. This needs to take into consideration newlines and
266 // trigraphs.
267 const char *TokStartPtr = SourceMgr.getCharacterData(TokStart);
268 const char *TokPtr = TokStartPtr;
269
270 // The usual case is that tokens don't contain anything interesting. Skip
271 // over the uninteresting characters. If a token only consists of simple
272 // chars, this method is extremely fast.
273 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
274 ++TokPtr, --CharNo;
275
276 // If we have a character that may be a trigraph or escaped newline, create a
277 // lexer to parse it correctly.
278 unsigned FileID = TokStart.getFileID();
279 const llvm::MemoryBuffer *SrcBuf = SourceMgr.getBuffer(FileID);
280 if (CharNo != 0) {
281 // Create a lexer starting at this token position.
282 Lexer TheLexer(SrcBuf, FileID, *this, TokPtr);
283 LexerToken Tok;
284 // Skip over characters the remaining characters.
285 for (; CharNo; --CharNo)
286 TheLexer.getAndAdvanceChar(TokPtr, Tok);
287 }
288 return SourceLocation(FileID, TokPtr-SrcBuf->getBufferStart());
289}
290
291
292
Chris Lattnerd01e2912006-06-18 16:22:51 +0000293//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000294// Source File Location Methods.
295//===----------------------------------------------------------------------===//
296
Chris Lattner22eb9722006-06-18 05:43:12 +0000297/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
298/// return null on failure. isAngled indicates whether the file reference is
299/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000300const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
301 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000302 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000303 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000304 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000305 // If the header lookup mechanism may be relative to the current file, pass in
306 // info about where the current file is.
307 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000308 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000309 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000310 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000311 }
312
Chris Lattner63dd32b2006-10-20 04:42:40 +0000313 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000314 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000315 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000316 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
317 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000318 if (FE) return FE;
319
320 // Otherwise, see if this is a subframework header. If so, this is relative
321 // to one of the headers on the #include stack. Walk the list of the current
322 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000323 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000324 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000325 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
326 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000327 return FE;
328 }
329
330 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
331 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000332 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000333 CurFileEnt =
334 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000335 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
336 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000337 return FE;
338 }
339 }
340
341 // Otherwise, we really couldn't find the file.
342 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000343}
344
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000345/// isInPrimaryFile - Return true if we're in the top-level file, not in a
346/// #include.
347bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000348 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000349 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000350
Chris Lattner13044d92006-07-03 05:16:44 +0000351 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000352 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000353 if (IncludeMacroStack[i].TheLexer &&
354 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
355 return IncludeMacroStack[i].TheLexer->isMainFile();
356 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000357}
358
359/// getCurrentLexer - Return the current file lexer being lexed from. Note
360/// that this ignores any potentially active macro expansions and _Pragma
361/// expansions going on at the time.
362Lexer *Preprocessor::getCurrentFileLexer() const {
363 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
364
365 // Look for a stacked lexer.
366 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000367 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000368 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
369 return L;
370 }
371 return 0;
372}
373
374
Chris Lattner22eb9722006-06-18 05:43:12 +0000375/// EnterSourceFile - Add a source file to the top of the include stack and
376/// start lexing tokens from it instead of the current buffer. Return true
377/// on failure.
378void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000379 const DirectoryLookup *CurDir,
380 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000381 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000382 ++NumEnteredSourceFiles;
383
Chris Lattner69772b02006-07-02 20:34:39 +0000384 if (MaxIncludeStackDepth < IncludeMacroStack.size())
385 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000386
Chris Lattner23b7eb62007-06-15 23:05:46 +0000387 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000388 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000389 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000390 EnterSourceFileWithLexer(TheLexer, CurDir);
391}
Chris Lattner22eb9722006-06-18 05:43:12 +0000392
Chris Lattner69772b02006-07-02 20:34:39 +0000393/// EnterSourceFile - Add a source file to the top of the include stack and
394/// start lexing tokens from it instead of the current buffer.
395void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
396 const DirectoryLookup *CurDir) {
397
398 // Add the current lexer to the include stack.
399 if (CurLexer || CurMacroExpander)
400 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
401 CurMacroExpander));
402
403 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000404 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000405 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000406
407 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000408 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000409 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
410
411 // Get the file entry for the current file.
412 if (const FileEntry *FE =
413 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000414 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000415
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000416 Callbacks->FileChanged(SourceLocation(CurLexer->getCurFileID(), 0),
417 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000418 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000419}
420
Chris Lattner69772b02006-07-02 20:34:39 +0000421
422
Chris Lattner22eb9722006-06-18 05:43:12 +0000423/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000424/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000425void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000426 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
427 CurMacroExpander));
428 CurLexer = 0;
429 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000430
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000431 if (NumCachedMacroExpanders == 0) {
432 CurMacroExpander = new MacroExpander(Tok, Args, *this);
433 } else {
434 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
435 CurMacroExpander->Init(Tok, Args);
436 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000437}
438
Chris Lattner7667d0d2006-07-16 18:16:58 +0000439/// EnterTokenStream - Add a "macro" context to the top of the include stack,
440/// which will cause the lexer to start returning the specified tokens. Note
441/// that these tokens will be re-macro-expanded when/if expansion is enabled.
442/// This method assumes that the specified stream of tokens has a permanent
443/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000444void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000445 // Save our current state.
446 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
447 CurMacroExpander));
448 CurLexer = 0;
449 CurDirLookup = 0;
450
451 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000452 if (NumCachedMacroExpanders == 0) {
453 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
454 } else {
455 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
456 CurMacroExpander->Init(Toks, NumToks);
457 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000458}
459
460/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
461/// lexer stack. This should only be used in situations where the current
462/// state of the top-of-stack lexer is known.
463void Preprocessor::RemoveTopOfLexerStack() {
464 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000465
466 if (CurMacroExpander) {
467 // Delete or cache the now-dead macro expander.
468 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
469 delete CurMacroExpander;
470 else
471 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
472 } else {
473 delete CurLexer;
474 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000475 CurLexer = IncludeMacroStack.back().TheLexer;
476 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
477 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
478 IncludeMacroStack.pop_back();
479}
480
Chris Lattner22eb9722006-06-18 05:43:12 +0000481//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000482// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000483//===----------------------------------------------------------------------===//
484
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000485/// RegisterBuiltinMacro - Register the specified identifier in the identifier
486/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000487IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000488 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000489 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000490
491 // Mark it as being a macro that is builtin.
492 MacroInfo *MI = new MacroInfo(SourceLocation());
493 MI->setIsBuiltinMacro();
494 Id->setMacroInfo(MI);
495 return Id;
496}
497
498
Chris Lattner677757a2006-06-28 05:26:32 +0000499/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
500/// identifier table.
501void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000502 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000503 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000504 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
505 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000506 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000507
508 // GCC Extensions.
509 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
510 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000511 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000512}
513
Chris Lattnerc2395832006-07-09 00:57:04 +0000514/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
515/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000516static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
517 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000518 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
519
520 // If the token isn't an identifier, it's always literally expanded.
521 if (II == 0) return true;
522
523 // If the identifier is a macro, and if that macro is enabled, it may be
524 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000525 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
526 // Fast expanding "#define X X" is ok, because X would be disabled.
527 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000528 return false;
529
530 // If this is an object-like macro invocation, it is safe to trivially expand
531 // it.
532 if (MI->isObjectLike()) return true;
533
534 // If this is a function-like macro invocation, it's safe to trivially expand
535 // as long as the identifier is not a macro argument.
536 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
537 I != E; ++I)
538 if (*I == II)
539 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000540
Chris Lattnerc2395832006-07-09 00:57:04 +0000541 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000542}
543
Chris Lattnerc2395832006-07-09 00:57:04 +0000544
Chris Lattnerafe603f2006-07-11 04:02:46 +0000545/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
546/// lexed is a '('. If so, consume the token and return true, if not, this
547/// method should have no observable side-effect on the lexed tokens.
548bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000549 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000550 unsigned Val;
551 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000552 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000553 else
554 Val = CurMacroExpander->isNextTokenLParen();
555
556 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000557 // We have run off the end. If it's a source file we don't
558 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
559 // macro stack.
560 if (CurLexer)
561 return false;
562 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000563 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
564 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000565 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000566 else
567 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000568
569 if (Val != 2)
570 break;
571
572 // Ran off the end of a source file?
573 if (Entry.TheLexer)
574 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000575 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000576 }
577
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000578 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
579 // have found something that isn't a '(' or we found the end of the
580 // translation unit. In either case, return false.
581 if (Val != 1)
582 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000583
584 LexerToken Tok;
585 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000586 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
587 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000588}
Chris Lattner677757a2006-06-28 05:26:32 +0000589
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000590/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
591/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000592bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000593 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000594
595 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
596 if (MI->isBuiltinMacro()) {
597 ExpandBuiltinMacro(Identifier);
598 return false;
599 }
600
Chris Lattner81278c62006-10-14 19:03:49 +0000601 // If this is the first use of a target-specific macro, warn about it.
602 if (MI->isTargetSpecific()) {
603 MI->setIsTargetSpecific(false); // Don't warn on second use.
604 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
605 diag::port_target_macro_use);
606 }
607
Chris Lattneree8760b2006-07-15 07:42:55 +0000608 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000609 /// for each macro argument, the list of tokens that were provided to the
610 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000611 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000612
613 // If this is a function-like macro, read the arguments.
614 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000615 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
616 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000617 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000618 return true;
619
Chris Lattner78186052006-07-09 00:45:31 +0000620 // Remember that we are now parsing the arguments to a macro invocation.
621 // Preprocessor directives used inside macro arguments are not portable, and
622 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000623 InMacroArgs = true;
624 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000625
626 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000627 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000628
629 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000630 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000631
632 ++NumFnMacroExpanded;
633 } else {
634 ++NumMacroExpanded;
635 }
Chris Lattner13044d92006-07-03 05:16:44 +0000636
637 // Notice that this macro has been used.
638 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000639
640 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000641
642 // If this macro expands to no tokens, don't bother to push it onto the
643 // expansion stack, only to take it right back off.
644 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000645 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000646 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000647
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000648 // Ignore this macro use, just return the next token in the current
649 // buffer.
650 bool HadLeadingSpace = Identifier.hasLeadingSpace();
651 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
652
653 Lex(Identifier);
654
655 // If the identifier isn't on some OTHER line, inherit the leading
656 // whitespace/first-on-a-line property of this token. This handles
657 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
658 // empty.
659 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000660 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
661 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000662 }
663 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000664 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000665
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000666 } else if (MI->getNumTokens() == 1 &&
667 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000668 // Otherwise, if this macro expands into a single trivially-expanded
669 // token: expand it now. This handles common cases like
670 // "#define VAL 42".
671
672 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
673 // identifier to the expanded token.
674 bool isAtStartOfLine = Identifier.isAtStartOfLine();
675 bool hasLeadingSpace = Identifier.hasLeadingSpace();
676
677 // Remember where the token is instantiated.
678 SourceLocation InstantiateLoc = Identifier.getLocation();
679
680 // Replace the result token.
681 Identifier = MI->getReplacementToken(0);
682
683 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000684 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
685 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000686
687 // Update the tokens location to include both its logical and physical
688 // locations.
689 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000690 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000691 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000692
Chris Lattner6e4bf522006-07-27 06:59:25 +0000693 // If this is #define X X, we must mark the result as unexpandible.
694 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
695 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000696 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000697
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000698 // Since this is not an identifier token, it can't be macro expanded, so
699 // we're done.
700 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000701 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000702 }
703
Chris Lattner78186052006-07-09 00:45:31 +0000704 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000705 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000706
707 // Now that the macro is at the top of the include stack, ask the
708 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000709 Lex(Identifier);
710 return false;
711}
712
Chris Lattneree8760b2006-07-15 07:42:55 +0000713/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000714/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000715/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000716MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
717 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000718 // The number of fixed arguments to parse.
719 unsigned NumFixedArgsLeft = MI->getNumArgs();
720 bool isVariadic = MI->isVariadic();
721
Chris Lattner78186052006-07-09 00:45:31 +0000722 // Outer loop, while there are more arguments, keep reading them.
723 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000724 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000725 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000726
727 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000728 // argument is separated by an EOF token. Use a SmallVector so we can avoid
729 // heap allocations in the common case.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000730 llvm::SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000731
732 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000733 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000734 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
735 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000736
Chris Lattner78186052006-07-09 00:45:31 +0000737 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000738 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
739 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000740 LexUnexpandedToken(Tok);
741
742 if (Tok.getKind() == tok::eof) {
743 Diag(MacroName, diag::err_unterm_macro_invoc);
744 // Do not lose the EOF. Return it to the client.
745 MacroName = Tok;
746 return 0;
747 } else if (Tok.getKind() == tok::r_paren) {
748 // If we found the ) token, the macro arg list is done.
749 if (NumParens-- == 0)
750 break;
751 } else if (Tok.getKind() == tok::l_paren) {
752 ++NumParens;
753 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
754 // Comma ends this argument if there are more fixed arguments expected.
755 if (NumFixedArgsLeft)
756 break;
757
Chris Lattner2ada5d32006-07-15 07:51:24 +0000758 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000759 if (!isVariadic) {
760 // Emit the diagnostic at the macro name in case there is a missing ).
761 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000762 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000763 return 0;
764 }
765 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000766 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000767 // If this is a comment token in the argument list and we're just in
768 // -C mode (not -CC mode), discard the comment.
769 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000770 }
771
772 ArgTokens.push_back(Tok);
773 }
774
Chris Lattnera12dd152006-07-11 04:09:02 +0000775 // Empty arguments are standard in C99 and supported as an extension in
776 // other modes.
777 if (ArgTokens.empty() && !Features.C99)
778 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000779
Chris Lattner36b6e812006-07-21 06:38:30 +0000780 // Add a marker EOF token to the end of the token list for this argument.
781 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000782 EOFTok.startToken();
783 EOFTok.setKind(tok::eof);
784 EOFTok.setLocation(Tok.getLocation());
785 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000786 ArgTokens.push_back(EOFTok);
787 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000788 --NumFixedArgsLeft;
789 };
790
791 // Okay, we either found the r_paren. Check to see if we parsed too few
792 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000793 unsigned MinArgsExpected = MI->getNumArgs();
794
Chris Lattner775d8322006-07-29 04:39:41 +0000795 // See MacroArgs instance var for description of this.
796 bool isVarargsElided = false;
797
Chris Lattner2ada5d32006-07-15 07:51:24 +0000798 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000799 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000800 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000801 // Varargs where the named vararg parameter is missing: ok as extension.
802 // #define A(x, ...)
803 // A("blah")
804 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000805
806 // Remember this occurred if this is a C99 macro invocation with at least
807 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000808 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000809 } else if (MI->getNumArgs() == 1) {
810 // #define A(x)
811 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000812 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000813
814 // Empty arguments are standard in C99 and supported as an extension in
815 // other modes.
816 if (ArgTokens.empty() && !Features.C99)
817 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000818 } else {
819 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000820 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000821 return 0;
822 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000823
824 // Add a marker EOF token to the end of the token list for this argument.
825 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000826 Tok.startToken();
827 Tok.setKind(tok::eof);
828 Tok.setLocation(EndLoc);
829 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000830 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000831 }
832
Chris Lattner775d8322006-07-29 04:39:41 +0000833 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000834}
835
Chris Lattnerc673f902006-06-30 06:10:41 +0000836/// ComputeDATE_TIME - Compute the current time, enter it into the specified
837/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
838/// the identifier tokens inserted.
839static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000840 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000841 time_t TT = time(0);
842 struct tm *TM = localtime(&TT);
843
844 static const char * const Months[] = {
845 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
846 };
847
848 char TmpBuffer[100];
849 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
850 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000851 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000852
853 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000854 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000855}
856
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000857/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
858/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000859void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000860 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000861 IdentifierInfo *II = Tok.getIdentifierInfo();
862 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000863
864 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
865 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000866 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000867 return Handle_Pragma(Tok);
868
Chris Lattner78186052006-07-09 00:45:31 +0000869 ++NumBuiltinMacroExpanded;
870
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000871 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000872
873 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000874 Tok.setIdentifierInfo(0);
875 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000876
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000877 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000878 // __LINE__ expands to a simple numeric value.
879 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
880 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000881 Tok.setKind(tok::numeric_constant);
882 Tok.setLength(Length);
883 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000884 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000885 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000886 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000887 Diag(Tok, diag::ext_pp_base_file);
888 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
889 while (NextLoc.getFileID() != 0) {
890 Loc = NextLoc;
891 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
892 }
893 }
894
Chris Lattner0766e592006-07-03 01:07:01 +0000895 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
896 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000897 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000898 Tok.setKind(tok::string_literal);
899 Tok.setLength(FN.size());
900 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000901 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000902 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000903 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000904 Tok.setKind(tok::string_literal);
905 Tok.setLength(strlen("\"Mmm dd yyyy\""));
906 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000907 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000908 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000909 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000910 Tok.setKind(tok::string_literal);
911 Tok.setLength(strlen("\"hh:mm:ss\""));
912 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000913 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000914 Diag(Tok, diag::ext_pp_include_level);
915
916 // Compute the include depth of this token.
917 unsigned Depth = 0;
918 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
919 for (; Loc.getFileID() != 0; ++Depth)
920 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
921
922 // __INCLUDE_LEVEL__ expands to a simple numeric value.
923 sprintf(TmpBuffer, "%u", Depth);
924 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000925 Tok.setKind(tok::numeric_constant);
926 Tok.setLength(Length);
927 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000928 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000929 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
930 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
931 Diag(Tok, diag::ext_pp_timestamp);
932
933 // Get the file that we are lexing out of. If we're currently lexing from
934 // a macro, dig into the include stack.
935 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000936 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000937
938 if (TheLexer)
939 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
940
941 // If this file is older than the file it depends on, emit a diagnostic.
942 const char *Result;
943 if (CurFile) {
944 time_t TT = CurFile->getModificationTime();
945 struct tm *TM = localtime(&TT);
946 Result = asctime(TM);
947 } else {
948 Result = "??? ??? ?? ??:??:?? ????\n";
949 }
950 TmpBuffer[0] = '"';
951 strcpy(TmpBuffer+1, Result);
952 unsigned Len = strlen(TmpBuffer);
953 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000954 Tok.setKind(tok::string_literal);
955 Tok.setLength(Len);
956 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000957 } else {
958 assert(0 && "Unknown identifier!");
959 }
960}
Chris Lattner677757a2006-06-28 05:26:32 +0000961
962//===----------------------------------------------------------------------===//
963// Lexer Event Handling.
964//===----------------------------------------------------------------------===//
965
Chris Lattnercefc7682006-07-08 08:28:12 +0000966/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
967/// identifier information for the token and install it into the token.
968IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
969 const char *BufPtr) {
970 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
971 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
972
973 // Look up this token, see if it is a macro, or if it is a language keyword.
974 IdentifierInfo *II;
975 if (BufPtr && !Identifier.needsCleaning()) {
976 // No cleaning needed, just use the characters from the lexed buffer.
977 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
978 } else {
979 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +0000980 llvm::SmallVector<char, 64> IdentifierBuffer;
981 IdentifierBuffer.resize(Identifier.getLength());
982 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +0000983 unsigned Size = getSpelling(Identifier, TmpBuf);
984 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
985 }
Chris Lattner8c204872006-10-14 05:19:21 +0000986 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000987 return II;
988}
989
990
Chris Lattner677757a2006-06-28 05:26:32 +0000991/// HandleIdentifier - This callback is invoked when the lexer reads an
992/// identifier. This callback looks up the identifier in the map and/or
993/// potentially macro expands it or turns it into a named token (like 'for').
994void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000995 assert(Identifier.getIdentifierInfo() &&
996 "Can't handle identifiers without identifier info!");
997
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000998 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000999
1000 // If this identifier was poisoned, and if it was not produced from a macro
1001 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001002 if (II.isPoisoned() && CurLexer) {
1003 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1004 Diag(Identifier, diag::err_pp_used_poisoned_id);
1005 else
1006 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1007 }
Chris Lattner677757a2006-06-28 05:26:32 +00001008
Chris Lattner78186052006-07-09 00:45:31 +00001009 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +00001010 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001011 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1012 if (MI->isEnabled()) {
1013 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1014 return;
1015 } else {
1016 // C99 6.10.3.4p2 says that a disabled macro may never again be
1017 // expanded, even if it's in a context where it could be expanded in the
1018 // future.
Chris Lattner8c204872006-10-14 05:19:21 +00001019 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001020 }
1021 }
Chris Lattner063400e2006-10-14 19:54:15 +00001022 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1023 // If this identifier is a macro on some other target, emit a diagnostic.
1024 // This diagnosic is only emitted when macro expansion is enabled, because
1025 // the macro would not have been expanded for the other target either.
1026 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1027 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1028 diag::port_target_macro_use);
1029
1030 }
Chris Lattner677757a2006-06-28 05:26:32 +00001031
Chris Lattner5b9f4892006-11-21 17:23:33 +00001032 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1033 // then we act as if it is the actual operator and not the textual
1034 // representation of it.
1035 if (II.isCPlusPlusOperatorKeyword())
1036 Identifier.setIdentifierInfo(0);
1037
Chris Lattner677757a2006-06-28 05:26:32 +00001038 // Change the kind of this identifier to the appropriate token kind, e.g.
1039 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001040 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001041
1042 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001043 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1044 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001045 if (II.isExtensionToken() && Features.C99)
1046 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001047}
1048
Chris Lattner22eb9722006-06-18 05:43:12 +00001049/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1050/// the current file. This either returns the EOF token or pops a level off
1051/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001052bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001053 assert(!CurMacroExpander &&
1054 "Ending a file when currently in a macro!");
1055
Chris Lattner371ac8a2006-07-04 07:11:10 +00001056 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001057 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001058 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001059 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001060 // Okay, this has a controlling macro, remember in PerFileInfo.
1061 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001062 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1063 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001064 }
1065 }
1066
Chris Lattner22eb9722006-06-18 05:43:12 +00001067 // If this is a #include'd file, pop it off the include stack and continue
1068 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001069 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001070 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001071 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001072
1073 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001074 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001075 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1076
1077 // Get the file entry for the current file.
1078 if (const FileEntry *FE =
1079 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001080 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001081
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001082 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1083 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001084 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001085
1086 // Client should lex another token.
1087 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001088 }
1089
Chris Lattner8c204872006-10-14 05:19:21 +00001090 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001091 CurLexer->BufferPtr = CurLexer->BufferEnd;
1092 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001093 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001094
1095 // We're done with the #included file.
1096 delete CurLexer;
1097 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001098
Chris Lattner03f83482006-07-10 06:16:26 +00001099 // This is the end of the top-level file. If the diag::pp_macro_not_used
1100 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1101 // have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001102 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1103 for (IdentifierTable::iterator I = Identifiers.begin(),
1104 E = Identifiers.end(); I != E; ++I) {
1105 const IdentifierInfo &II = I->getValue();
1106 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1107 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1108 }
1109 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001110
1111 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001112}
1113
1114/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001115/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001116bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001117 assert(CurMacroExpander && !CurLexer &&
1118 "Ending a macro when currently in a #include file!");
1119
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001120 // Delete or cache the now-dead macro expander.
1121 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1122 delete CurMacroExpander;
1123 else
1124 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001125
Chris Lattner69772b02006-07-02 20:34:39 +00001126 // Handle this like a #include file being popped off the stack.
1127 CurMacroExpander = 0;
1128 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001129}
1130
1131
1132//===----------------------------------------------------------------------===//
1133// Utility Methods for Preprocessor Directive Handling.
1134//===----------------------------------------------------------------------===//
1135
1136/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1137/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001138void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001139 LexerToken Tmp;
1140 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001141 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001142 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001143}
1144
Chris Lattner652c1692006-11-21 23:47:30 +00001145/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1146static bool isCXXNamedOperator(const std::string &Spelling) {
1147 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1148 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1149 Spelling == "or" || Spelling == "xor";
1150}
1151
Chris Lattner22eb9722006-06-18 05:43:12 +00001152/// ReadMacroName - Lex and validate a macro name, which occurs after a
1153/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001154/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1155/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001156/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001157void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001158 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001159 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001160
1161 // Missing macro name?
1162 if (MacroNameTok.getKind() == tok::eom)
1163 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1164
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001165 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1166 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001167 std::string Spelling = getSpelling(MacroNameTok);
1168 if (isCXXNamedOperator(Spelling))
1169 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1170 // except for their spellings.
1171 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1172 else
1173 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001174 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001175 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001176 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001177 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001178 } else if (isDefineUndef && II->getMacroInfo() &&
1179 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001180 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001181 if (isDefineUndef == 1)
1182 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1183 else
1184 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001185 } else {
1186 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001187 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001188 }
1189
Chris Lattner22eb9722006-06-18 05:43:12 +00001190 // Invalid macro name, read and discard the rest of the line. Then set the
1191 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001192 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001193 return DiscardUntilEndOfDirective();
1194}
1195
1196/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1197/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001198void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001199 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001200 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001201 // There should be no tokens after the directive, but we allow them as an
1202 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001203 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1204 Lex(Tmp);
1205
Chris Lattner22eb9722006-06-18 05:43:12 +00001206 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001207 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1208 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001209 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001210}
1211
1212
1213
1214/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1215/// decided that the subsequent tokens are in the #if'd out portion of the
1216/// file. Lex the rest of the file, until we see an #endif. If
1217/// FoundNonSkipPortion is true, then we have already emitted code for part of
1218/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1219/// is true, then #else directives are ok, if not, then we have already seen one
1220/// so a #else directive is a duplicate. When this returns, the caller can lex
1221/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001222void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001223 bool FoundNonSkipPortion,
1224 bool FoundElse) {
1225 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001226 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001227 "Lexing a macro, not a file?");
1228
1229 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1230 FoundNonSkipPortion, FoundElse);
1231
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001232 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1233 // disabling warnings, etc.
1234 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001235 LexerToken Tok;
1236 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001237 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001238
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001239 // If this is the end of the buffer, we have an error.
1240 if (Tok.getKind() == tok::eof) {
1241 // Emit errors for each unterminated conditional on the stack, including
1242 // the current one.
1243 while (!CurLexer->ConditionalStack.empty()) {
1244 Diag(CurLexer->ConditionalStack.back().IfLoc,
1245 diag::err_pp_unterminated_conditional);
1246 CurLexer->ConditionalStack.pop_back();
1247 }
1248
1249 // Just return and let the caller lex after this #include.
1250 break;
1251 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001252
1253 // If this token is not a preprocessor directive, just skip it.
1254 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1255 continue;
1256
1257 // We just parsed a # character at the start of a line, so we're in
1258 // directive mode. Tell the lexer this so any newlines we see will be
1259 // converted into an EOM token (this terminates the macro).
1260 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001261 CurLexer->KeepCommentMode = false;
1262
Chris Lattner22eb9722006-06-18 05:43:12 +00001263
1264 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001265 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001266
1267 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1268 // something bogus), skip it.
1269 if (Tok.getKind() != tok::identifier) {
1270 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001271 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001272 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001273 continue;
1274 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001275
Chris Lattner22eb9722006-06-18 05:43:12 +00001276 // If the first letter isn't i or e, it isn't intesting to us. We know that
1277 // this is safe in the face of spelling differences, because there is no way
1278 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001279 // allows us to avoid looking up the identifier info for #define/#undef and
1280 // other common directives.
1281 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1282 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001283 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1284 FirstChar != 'i' && FirstChar != 'e') {
1285 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001286 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001287 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001288 continue;
1289 }
1290
Chris Lattnere60165f2006-06-22 06:36:29 +00001291 // Get the identifier name without trigraphs or embedded newlines. Note
1292 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1293 // when skipping.
1294 // TODO: could do this with zero copies in the no-clean case by using
1295 // strncmp below.
1296 char Directive[20];
1297 unsigned IdLen;
1298 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1299 IdLen = Tok.getLength();
1300 memcpy(Directive, RawCharData, IdLen);
1301 Directive[IdLen] = 0;
1302 } else {
1303 std::string DirectiveStr = getSpelling(Tok);
1304 IdLen = DirectiveStr.size();
1305 if (IdLen >= 20) {
1306 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001307 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001308 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001309 continue;
1310 }
1311 memcpy(Directive, &DirectiveStr[0], IdLen);
1312 Directive[IdLen] = 0;
1313 }
1314
Chris Lattner22eb9722006-06-18 05:43:12 +00001315 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001316 if ((IdLen == 2) || // "if"
1317 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1318 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001319 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1320 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001321 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001322 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001323 /*foundnonskip*/false,
1324 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001325 }
1326 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001327 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001328 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001329 PPConditionalInfo CondInfo;
1330 CondInfo.WasSkipping = true; // Silence bogus warning.
1331 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001332 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001333 assert(!InCond && "Can't be skipping if not in a conditional!");
1334
1335 // If we popped the outermost skipping block, we're done skipping!
1336 if (!CondInfo.WasSkipping)
1337 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001338 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001339 // #else directive in a skipping conditional. If not in some other
1340 // skipping conditional, and if #else hasn't already been seen, enter it
1341 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001342 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001343 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1344
1345 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001346 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001347
1348 // Note that we've seen a #else in this conditional.
1349 CondInfo.FoundElse = true;
1350
1351 // If the conditional is at the top level, and the #if block wasn't
1352 // entered, enter the #else block now.
1353 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1354 CondInfo.FoundNonSkip = true;
1355 break;
1356 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001357 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001358 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1359
1360 bool ShouldEnter;
1361 // If this is in a skipping block or if we're already handled this #if
1362 // block, don't bother parsing the condition.
1363 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001364 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001365 ShouldEnter = false;
1366 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001367 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001368 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001369 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1370 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001371 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001372 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001373 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001374 }
1375
1376 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001377 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001378
1379 // If this condition is true, enter it!
1380 if (ShouldEnter) {
1381 CondInfo.FoundNonSkip = true;
1382 break;
1383 }
1384 }
1385 }
1386
1387 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001388 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001389 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001390 }
1391
1392 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1393 // of the file, just stop skipping and return to lexing whatever came after
1394 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001395 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001396}
1397
1398//===----------------------------------------------------------------------===//
1399// Preprocessor Directive Handling.
1400//===----------------------------------------------------------------------===//
1401
1402/// HandleDirective - This callback is invoked when the lexer sees a # token
1403/// at the start of a line. This consumes the directive, modifies the
1404/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1405/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001406void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001407 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001408
1409 // We just parsed a # character at the start of a line, so we're in directive
1410 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001411 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001412 CurLexer->ParsingPreprocessorDirective = true;
1413
1414 ++NumDirectives;
1415
Chris Lattner371ac8a2006-07-04 07:11:10 +00001416 // We are about to read a token. For the multiple-include optimization FA to
1417 // work, we have to remember if we had read any tokens *before* this
1418 // pp-directive.
1419 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1420
Chris Lattner78186052006-07-09 00:45:31 +00001421 // Read the next token, the directive flavor. This isn't expanded due to
1422 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001423 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001424
Chris Lattner78186052006-07-09 00:45:31 +00001425 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1426 // #define A(x) #x
1427 // A(abc
1428 // #warning blah
1429 // def)
1430 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001431 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001432 Diag(Result, diag::ext_embedded_directive);
1433
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001434TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001435 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001436 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001437 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001438 case tok::comment:
1439 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1440 LexUnexpandedToken(Result);
1441 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001442
Chris Lattner22eb9722006-06-18 05:43:12 +00001443 case tok::numeric_constant:
1444 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001445 DiscardUntilEndOfDirective();
1446 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001447 default:
1448 IdentifierInfo *II = Result.getIdentifierInfo();
1449 if (II == 0) break; // Not an identifier.
1450
1451 // Ask what the preprocessor keyword ID is.
1452 switch (II->getPPKeywordID()) {
1453 default: break;
1454 // C99 6.10.1 - Conditional Inclusion.
1455 case tok::pp_if:
1456 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1457 case tok::pp_ifdef:
1458 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1459 case tok::pp_ifndef:
1460 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1461 case tok::pp_elif:
1462 return HandleElifDirective(Result);
1463 case tok::pp_else:
1464 return HandleElseDirective(Result);
1465 case tok::pp_endif:
1466 return HandleEndifDirective(Result);
1467
1468 // C99 6.10.2 - Source File Inclusion.
1469 case tok::pp_include:
1470 return HandleIncludeDirective(Result); // Handle #include.
1471
1472 // C99 6.10.3 - Macro Replacement.
1473 case tok::pp_define:
1474 return HandleDefineDirective(Result, false);
1475 case tok::pp_undef:
1476 return HandleUndefDirective(Result);
1477
1478 // C99 6.10.4 - Line Control.
1479 case tok::pp_line:
1480 // FIXME: implement #line
1481 DiscardUntilEndOfDirective();
1482 return;
1483
1484 // C99 6.10.5 - Error Directive.
1485 case tok::pp_error:
1486 return HandleUserDiagnosticDirective(Result, false);
1487
1488 // C99 6.10.6 - Pragma Directive.
1489 case tok::pp_pragma:
1490 return HandlePragmaDirective();
1491
1492 // GNU Extensions.
1493 case tok::pp_import:
1494 return HandleImportDirective(Result);
1495 case tok::pp_include_next:
1496 return HandleIncludeNextDirective(Result);
1497
1498 case tok::pp_warning:
1499 Diag(Result, diag::ext_pp_warning_directive);
1500 return HandleUserDiagnosticDirective(Result, true);
1501 case tok::pp_ident:
1502 return HandleIdentSCCSDirective(Result);
1503 case tok::pp_sccs:
1504 return HandleIdentSCCSDirective(Result);
1505 case tok::pp_assert:
1506 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001507 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001508 case tok::pp_unassert:
1509 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001510 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001511
1512 // clang extensions.
1513 case tok::pp_define_target:
1514 return HandleDefineDirective(Result, true);
1515 case tok::pp_define_other_target:
1516 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001517 }
1518 break;
1519 }
1520
1521 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001522 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001523
1524 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001525 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001526
1527 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001528}
1529
Chris Lattner01d66cc2006-07-03 22:16:27 +00001530void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001531 bool isWarning) {
1532 // Read the rest of the line raw. We do this because we don't want macros
1533 // to be expanded and we don't require that the tokens be valid preprocessing
1534 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1535 // collapse multiple consequtive white space between tokens, but this isn't
1536 // specified by the standard.
1537 std::string Message = CurLexer->ReadToEndOfLine();
1538
1539 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001540 return Diag(Tok, DiagID, Message);
1541}
1542
1543/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1544///
1545void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001546 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001547 Diag(Tok, diag::ext_pp_ident_directive);
1548
Chris Lattner371ac8a2006-07-04 07:11:10 +00001549 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001550 LexerToken StrTok;
1551 Lex(StrTok);
1552
1553 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001554 if (StrTok.getKind() != tok::string_literal &&
1555 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001556 return Diag(StrTok, diag::err_pp_malformed_ident);
1557
1558 // Verify that there is nothing after the string, other than EOM.
1559 CheckEndOfDirective("#ident");
1560
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001561 if (Callbacks)
1562 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001563}
1564
Chris Lattnerb8761832006-06-24 21:31:03 +00001565//===----------------------------------------------------------------------===//
1566// Preprocessor Include Directive Handling.
1567//===----------------------------------------------------------------------===//
1568
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001569/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1570/// checked and spelled filename, e.g. as an operand of #include. This returns
1571/// true if the input filename was in <>'s or false if it were in ""'s. The
1572/// caller is expected to provide a buffer that is large enough to hold the
1573/// spelling of the filename, but is also expected to handle the case when
1574/// this method decides to use a different buffer.
1575bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1576 const char *&BufStart,
1577 const char *&BufEnd) {
1578 // Get the text form of the filename.
1579 unsigned Len = getSpelling(FilenameTok, BufStart);
1580 BufEnd = BufStart+Len;
1581 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1582
1583 // Make sure the filename is <x> or "x".
1584 bool isAngled;
1585 if (BufStart[0] == '<') {
1586 if (BufEnd[-1] != '>') {
1587 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1588 BufStart = 0;
1589 return true;
1590 }
1591 isAngled = true;
1592 } else if (BufStart[0] == '"') {
1593 if (BufEnd[-1] != '"') {
1594 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1595 BufStart = 0;
1596 return true;
1597 }
1598 isAngled = false;
1599 } else {
1600 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1601 BufStart = 0;
1602 return true;
1603 }
1604
1605 // Diagnose #include "" as invalid.
1606 if (BufEnd-BufStart <= 2) {
1607 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1608 BufStart = 0;
1609 return "";
1610 }
1611
1612 // Skip the brackets.
1613 ++BufStart;
1614 --BufEnd;
1615 return isAngled;
1616}
1617
Chris Lattner22eb9722006-06-18 05:43:12 +00001618/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1619/// file to be included from the lexer, then include it! This is a common
1620/// routine with functionality shared between #include, #include_next and
1621/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001622void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001623 const DirectoryLookup *LookupFrom,
1624 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001625
Chris Lattner22eb9722006-06-18 05:43:12 +00001626 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001627 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001628
1629 // If the token kind is EOM, the error has already been diagnosed.
1630 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001631 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001632
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001633 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001634 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001635 FilenameBuffer.resize(FilenameTok.getLength());
1636
1637 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1638 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1639 FilenameStart, FilenameEnd);
1640 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1641 // error.
1642 if (FilenameStart == 0)
1643 return;
1644
Chris Lattner269c2322006-06-25 06:23:00 +00001645 // Verify that there is nothing after the filename, other than EOM. Use the
1646 // preprocessor to lex this in case lexing the filename entered a macro.
1647 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001648
1649 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001650 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001651 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1652
Chris Lattner22eb9722006-06-18 05:43:12 +00001653 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001654 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001655 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001656 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001657 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001658 return Diag(FilenameTok, diag::err_pp_file_not_found,
1659 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001660
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001661 // Ask HeaderInfo if we should enter this #include file.
1662 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1663 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001664 return;
1665 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001666
1667 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001668 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001669 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001670 return Diag(FilenameTok, diag::err_pp_file_not_found,
1671 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001672
1673 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001674 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001675}
1676
1677/// HandleIncludeNextDirective - Implements #include_next.
1678///
Chris Lattnercb283342006-06-18 06:48:37 +00001679void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1680 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001681
1682 // #include_next is like #include, except that we start searching after
1683 // the current found directory. If we can't do this, issue a
1684 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001685 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001686 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001687 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001688 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001689 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001690 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001691 } else {
1692 // Start looking up in the next directory.
1693 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001694 }
1695
1696 return HandleIncludeDirective(IncludeNextTok, Lookup);
1697}
1698
1699/// HandleImportDirective - Implements #import.
1700///
Chris Lattnercb283342006-06-18 06:48:37 +00001701void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1702 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001703
1704 return HandleIncludeDirective(ImportTok, 0, true);
1705}
1706
Chris Lattnerb8761832006-06-24 21:31:03 +00001707//===----------------------------------------------------------------------===//
1708// Preprocessor Macro Directive Handling.
1709//===----------------------------------------------------------------------===//
1710
Chris Lattnercefc7682006-07-08 08:28:12 +00001711/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1712/// definition has just been read. Lex the rest of the arguments and the
1713/// closing ), updating MI with what we learn. Return true if an error occurs
1714/// parsing the arg list.
1715bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001716 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1717
Chris Lattnercefc7682006-07-08 08:28:12 +00001718 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001719 while (1) {
1720 LexUnexpandedToken(Tok);
1721 switch (Tok.getKind()) {
1722 case tok::r_paren:
1723 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001724 if (Arguments.empty()) { // #define FOO()
1725 MI->setArgumentList(Arguments.begin(), Arguments.end());
1726 return false;
1727 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001728 // Otherwise we have #define FOO(A,)
1729 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1730 return true;
1731 case tok::ellipsis: // #define X(... -> C99 varargs
1732 // Warn if use of C99 feature in non-C99 mode.
1733 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1734
1735 // Lex the token after the identifier.
1736 LexUnexpandedToken(Tok);
1737 if (Tok.getKind() != tok::r_paren) {
1738 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1739 return true;
1740 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001741 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001742 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001743 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001744 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001745 return false;
1746 case tok::eom: // #define X(
1747 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1748 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001749 default:
1750 // Handle keywords and identifiers here to accept things like
1751 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001752 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001753 if (II == 0) {
1754 // #define X(1
1755 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1756 return true;
1757 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001758
1759 // If this is already used as an argument, it is used multiple times (e.g.
1760 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00001761 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1762 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001763 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1764 return true;
1765 }
1766
1767 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00001768 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001769
1770 // Lex the token after the identifier.
1771 LexUnexpandedToken(Tok);
1772
1773 switch (Tok.getKind()) {
1774 default: // #define X(A B
1775 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1776 return true;
1777 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00001778 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001779 return false;
1780 case tok::comma: // #define X(A,
1781 break;
1782 case tok::ellipsis: // #define X(A... -> GCC extension
1783 // Diagnose extension.
1784 Diag(Tok, diag::ext_named_variadic_macro);
1785
1786 // Lex the token after the identifier.
1787 LexUnexpandedToken(Tok);
1788 if (Tok.getKind() != tok::r_paren) {
1789 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1790 return true;
1791 }
1792
1793 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001794 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001795 return false;
1796 }
1797 }
1798 }
1799}
1800
Chris Lattner22eb9722006-06-18 05:43:12 +00001801/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001802/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1803/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001804///
Chris Lattner81278c62006-10-14 19:03:49 +00001805void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1806 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001807 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001808
Chris Lattner22eb9722006-06-18 05:43:12 +00001809 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001810 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001811
1812 // Error reading macro name? If so, diagnostic already issued.
1813 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001814 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00001815
Chris Lattner457fc152006-07-29 06:30:25 +00001816 // If we are supposed to keep comments in #defines, reenable comment saving
1817 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001818 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001819
Chris Lattner063400e2006-10-14 19:54:15 +00001820 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001821 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001822 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001823
Chris Lattner063400e2006-10-14 19:54:15 +00001824 // If the identifier is an 'other target' macro, clear this bit.
1825 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1826
1827
Chris Lattner22eb9722006-06-18 05:43:12 +00001828 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001829 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001830
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001831 // If this is a function-like macro definition, parse the argument list,
1832 // marking each of the identifiers as being used as macro arguments. Also,
1833 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001834 if (Tok.getKind() == tok::eom) {
1835 // If there is no body to this macro, we have no special handling here.
1836 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001837 // This is a function-like macro definition. Read the argument list.
1838 MI->setIsFunctionLike();
1839 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001840 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001841 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001842 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001843 if (CurLexer->ParsingPreprocessorDirective)
1844 DiscardUntilEndOfDirective();
1845 return;
1846 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001847
Chris Lattner815a1f92006-07-08 20:48:04 +00001848 // Read the first token after the arg list for down below.
1849 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001850 } else if (!Tok.hasLeadingSpace()) {
1851 // C99 requires whitespace between the macro definition and the body. Emit
1852 // a diagnostic for something like "#define X+".
1853 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001854 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001855 } else {
1856 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1857 // one in some cases!
1858 }
1859 } else {
1860 // This is a normal token with leading space. Clear the leading space
1861 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001862 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001863 }
1864
Chris Lattner7e374832006-07-29 03:46:57 +00001865 // If this is a definition of a variadic C99 function-like macro, not using
1866 // the GNU named varargs extension, enabled __VA_ARGS__.
1867
1868 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1869 // This gets unpoisoned where it is allowed.
1870 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1871 if (MI->isC99Varargs())
1872 Ident__VA_ARGS__->setIsPoisoned(false);
1873
Chris Lattner22eb9722006-06-18 05:43:12 +00001874 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00001875 if (MI->isObjectLike()) {
1876 // Object-like macros are very simple, just read their body.
1877 while (Tok.getKind() != tok::eom) {
1878 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001879 // Get the next token of the macro.
1880 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001881 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001882
Chris Lattnera3834342007-07-14 21:54:03 +00001883 } else {
1884 // Otherwise, read the body of a function-like macro. This has to validate
1885 // the # (stringize) operator.
1886 while (Tok.getKind() != tok::eom) {
1887 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001888
Chris Lattnera3834342007-07-14 21:54:03 +00001889 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1890 // parameters in function-like macro expansions.
1891 if (Tok.getKind() != tok::hash) {
1892 // Get the next token of the macro.
1893 LexUnexpandedToken(Tok);
1894 continue;
1895 }
1896
1897 // Get the next token of the macro.
1898 LexUnexpandedToken(Tok);
1899
1900 // Not a macro arg identifier?
1901 if (!Tok.getIdentifierInfo() ||
1902 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1903 Diag(Tok, diag::err_pp_stringize_not_parameter);
1904 delete MI;
1905
1906 // Disable __VA_ARGS__ again.
1907 Ident__VA_ARGS__->setIsPoisoned(true);
1908 return;
1909 }
1910
1911 // Things look ok, add the param name token to the macro.
1912 MI->AddTokenToBody(Tok);
1913
1914 // Get the next token of the macro.
1915 LexUnexpandedToken(Tok);
1916 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001917 }
Chris Lattner7e374832006-07-29 03:46:57 +00001918
Chris Lattnerf40fe992007-07-14 22:11:41 +00001919
Chris Lattner7e374832006-07-29 03:46:57 +00001920 // Disable __VA_ARGS__ again.
1921 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001922
Chris Lattnerbff18d52006-07-06 04:49:18 +00001923 // Check that there is no paste (##) operator at the begining or end of the
1924 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001925 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001926 if (NumTokens != 0) {
1927 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001928 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001929 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001930 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001931 }
1932 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001933 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001934 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001935 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001936 }
1937 }
1938
Chris Lattner13044d92006-07-03 05:16:44 +00001939 // If this is the primary source file, remember that this macro hasn't been
1940 // used yet.
1941 if (isInPrimaryFile())
1942 MI->setIsUsed(false);
1943
Chris Lattner22eb9722006-06-18 05:43:12 +00001944 // Finally, if this identifier already had a macro defined for it, verify that
1945 // the macro bodies are identical and free the old definition.
1946 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001947 if (!OtherMI->isUsed())
1948 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1949
Chris Lattner22eb9722006-06-18 05:43:12 +00001950 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001951 // must be the same. C99 6.10.3.2.
1952 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001953 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1954 MacroNameTok.getIdentifierInfo()->getName());
1955 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1956 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001957 delete OtherMI;
1958 }
1959
1960 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001961}
1962
Chris Lattner063400e2006-10-14 19:54:15 +00001963/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1964void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1965 LexerToken MacroNameTok;
1966 ReadMacroName(MacroNameTok, 1);
1967
1968 // Error reading macro name? If so, diagnostic already issued.
1969 if (MacroNameTok.getKind() == tok::eom)
1970 return;
1971
1972 // Check to see if this is the last token on the #undef line.
1973 CheckEndOfDirective("#define_other_target");
1974
1975 // If there is already a macro defined by this name, turn it into a
1976 // target-specific define.
1977 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1978 MI->setIsTargetSpecific(true);
1979 return;
1980 }
1981
1982 // Mark the identifier as being a macro on some other target.
1983 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1984}
1985
Chris Lattner22eb9722006-06-18 05:43:12 +00001986
1987/// HandleUndefDirective - Implements #undef.
1988///
Chris Lattnercb283342006-06-18 06:48:37 +00001989void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001990 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001991
Chris Lattner22eb9722006-06-18 05:43:12 +00001992 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001993 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001994
1995 // Error reading macro name? If so, diagnostic already issued.
1996 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001997 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001998
1999 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002000 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002001
2002 // Okay, we finally have a valid identifier to undef.
2003 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
2004
Chris Lattner063400e2006-10-14 19:54:15 +00002005 // #undef untaints an identifier if it were marked by define_other_target.
2006 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2007
Chris Lattner22eb9722006-06-18 05:43:12 +00002008 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002009 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002010
Chris Lattner13044d92006-07-03 05:16:44 +00002011 if (!MI->isUsed())
2012 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002013
2014 // Free macro definition.
2015 delete MI;
2016 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002017}
2018
2019
Chris Lattnerb8761832006-06-24 21:31:03 +00002020//===----------------------------------------------------------------------===//
2021// Preprocessor Conditional Directive Handling.
2022//===----------------------------------------------------------------------===//
2023
Chris Lattner22eb9722006-06-18 05:43:12 +00002024/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002025/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2026/// if any tokens have been returned or pp-directives activated before this
2027/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002028///
Chris Lattner371ac8a2006-07-04 07:11:10 +00002029void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
2030 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002031 ++NumIf;
2032 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002033
Chris Lattner22eb9722006-06-18 05:43:12 +00002034 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002035 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002036
2037 // Error reading macro name? If so, diagnostic already issued.
2038 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00002039 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002040
2041 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002042 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2043
2044 // If the start of a top-level #ifdef, inform MIOpt.
2045 if (!ReadAnyTokensBeforeDirective &&
2046 CurLexer->getConditionalStackDepth() == 0) {
2047 assert(isIfndef && "#ifdef shouldn't reach here");
2048 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2049 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002050
Chris Lattner063400e2006-10-14 19:54:15 +00002051 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2052 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00002053
Chris Lattner81278c62006-10-14 19:03:49 +00002054 // If there is a macro, process it.
2055 if (MI) {
2056 // Mark it used.
2057 MI->setIsUsed(true);
2058
2059 // If this is the first use of a target-specific macro, warn about it.
2060 if (MI->isTargetSpecific()) {
2061 MI->setIsTargetSpecific(false); // Don't warn on second use.
2062 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2063 diag::port_target_macro_use);
2064 }
Chris Lattner063400e2006-10-14 19:54:15 +00002065 } else {
2066 // Use of a target-specific macro for some other target? If so, warn.
2067 if (MII->isOtherTargetMacro()) {
2068 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2069 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2070 diag::port_target_macro_use);
2071 }
Chris Lattner81278c62006-10-14 19:03:49 +00002072 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002073
Chris Lattner22eb9722006-06-18 05:43:12 +00002074 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002075 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002076 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002077 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002078 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002079 } else {
2080 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002081 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002082 /*Foundnonskip*/false,
2083 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002084 }
2085}
2086
2087/// HandleIfDirective - Implements the #if directive.
2088///
Chris Lattnera8654ca2006-07-04 17:42:08 +00002089void Preprocessor::HandleIfDirective(LexerToken &IfToken,
2090 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002091 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002092
Chris Lattner371ac8a2006-07-04 07:11:10 +00002093 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002094 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002095 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002096
2097 // Should we include the stuff contained by this directive?
2098 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002099 // If this condition is equivalent to #ifndef X, and if this is the first
2100 // directive seen, handle it for the multiple-include optimization.
2101 if (!ReadAnyTokensBeforeDirective &&
2102 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2103 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2104
Chris Lattner22eb9722006-06-18 05:43:12 +00002105 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002106 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002107 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002108 } else {
2109 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002110 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002111 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002112 }
2113}
2114
2115/// HandleEndifDirective - Implements the #endif directive.
2116///
Chris Lattnercb283342006-06-18 06:48:37 +00002117void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002118 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002119
Chris Lattner22eb9722006-06-18 05:43:12 +00002120 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002121 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002122
2123 PPConditionalInfo CondInfo;
2124 if (CurLexer->popConditionalLevel(CondInfo)) {
2125 // No conditionals on the stack: this is an #endif without an #if.
2126 return Diag(EndifToken, diag::err_pp_endif_without_if);
2127 }
2128
Chris Lattner371ac8a2006-07-04 07:11:10 +00002129 // If this the end of a top-level #endif, inform MIOpt.
2130 if (CurLexer->getConditionalStackDepth() == 0)
2131 CurLexer->MIOpt.ExitTopLevelConditional();
2132
Chris Lattner538d7f32006-07-20 04:31:52 +00002133 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002134 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002135}
2136
2137
Chris Lattnercb283342006-06-18 06:48:37 +00002138void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002139 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002140
Chris Lattner22eb9722006-06-18 05:43:12 +00002141 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002142 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002143
2144 PPConditionalInfo CI;
2145 if (CurLexer->popConditionalLevel(CI))
2146 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002147
2148 // If this is a top-level #else, inform the MIOpt.
2149 if (CurLexer->getConditionalStackDepth() == 0)
2150 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002151
2152 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002153 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002154
2155 // Finally, skip the rest of the contents of this block and return the first
2156 // token after it.
2157 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2158 /*FoundElse*/true);
2159}
2160
Chris Lattnercb283342006-06-18 06:48:37 +00002161void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002162 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002163
Chris Lattner22eb9722006-06-18 05:43:12 +00002164 // #elif directive in a non-skipping conditional... start skipping.
2165 // We don't care what the condition is, because we will always skip it (since
2166 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002167 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002168
2169 PPConditionalInfo CI;
2170 if (CurLexer->popConditionalLevel(CI))
2171 return Diag(ElifToken, diag::pp_err_elif_without_if);
2172
Chris Lattner371ac8a2006-07-04 07:11:10 +00002173 // If this is a top-level #elif, inform the MIOpt.
2174 if (CurLexer->getConditionalStackDepth() == 0)
2175 CurLexer->MIOpt.FoundTopLevelElse();
2176
Chris Lattner22eb9722006-06-18 05:43:12 +00002177 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002178 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002179
2180 // Finally, skip the rest of the contents of this block and return the first
2181 // token after it.
2182 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2183 /*FoundElse*/CI.FoundElse);
2184}
Chris Lattnerb8761832006-06-24 21:31:03 +00002185