blob: 93017937d532cde6aabb7454e5ab05a79e578c4a [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) {
557 // If we ran off the end of the lexer or macro expander, walk the include
558 // stack, looking for whatever will return the next token.
559 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
560 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
561 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000562 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000563 else
564 Val = Entry.TheMacroExpander->isNextTokenLParen();
565 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000566 }
567
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000568 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
569 // have found something that isn't a '(' or we found the end of the
570 // translation unit. In either case, return false.
571 if (Val != 1)
572 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000573
574 LexerToken Tok;
575 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000576 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
577 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000578}
Chris Lattner677757a2006-06-28 05:26:32 +0000579
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000580/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
581/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000582bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000583 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000584
585 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
586 if (MI->isBuiltinMacro()) {
587 ExpandBuiltinMacro(Identifier);
588 return false;
589 }
590
Chris Lattner81278c62006-10-14 19:03:49 +0000591 // If this is the first use of a target-specific macro, warn about it.
592 if (MI->isTargetSpecific()) {
593 MI->setIsTargetSpecific(false); // Don't warn on second use.
594 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
595 diag::port_target_macro_use);
596 }
597
Chris Lattneree8760b2006-07-15 07:42:55 +0000598 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000599 /// for each macro argument, the list of tokens that were provided to the
600 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000601 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000602
603 // If this is a function-like macro, read the arguments.
604 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000605 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
606 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000607 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000608 return true;
609
Chris Lattner78186052006-07-09 00:45:31 +0000610 // Remember that we are now parsing the arguments to a macro invocation.
611 // Preprocessor directives used inside macro arguments are not portable, and
612 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000613 InMacroArgs = true;
614 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000615
616 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000617 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000618
619 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000620 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000621
622 ++NumFnMacroExpanded;
623 } else {
624 ++NumMacroExpanded;
625 }
Chris Lattner13044d92006-07-03 05:16:44 +0000626
627 // Notice that this macro has been used.
628 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000629
630 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000631
632 // If this macro expands to no tokens, don't bother to push it onto the
633 // expansion stack, only to take it right back off.
634 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000635 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000636 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000637
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000638 // Ignore this macro use, just return the next token in the current
639 // buffer.
640 bool HadLeadingSpace = Identifier.hasLeadingSpace();
641 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
642
643 Lex(Identifier);
644
645 // If the identifier isn't on some OTHER line, inherit the leading
646 // whitespace/first-on-a-line property of this token. This handles
647 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
648 // empty.
649 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000650 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
651 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000652 }
653 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000654 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000655
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000656 } else if (MI->getNumTokens() == 1 &&
657 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000658 // Otherwise, if this macro expands into a single trivially-expanded
659 // token: expand it now. This handles common cases like
660 // "#define VAL 42".
661
662 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
663 // identifier to the expanded token.
664 bool isAtStartOfLine = Identifier.isAtStartOfLine();
665 bool hasLeadingSpace = Identifier.hasLeadingSpace();
666
667 // Remember where the token is instantiated.
668 SourceLocation InstantiateLoc = Identifier.getLocation();
669
670 // Replace the result token.
671 Identifier = MI->getReplacementToken(0);
672
673 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000674 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
675 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000676
677 // Update the tokens location to include both its logical and physical
678 // locations.
679 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000680 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000681 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000682
Chris Lattner6e4bf522006-07-27 06:59:25 +0000683 // If this is #define X X, we must mark the result as unexpandible.
684 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
685 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000686 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000687
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000688 // Since this is not an identifier token, it can't be macro expanded, so
689 // we're done.
690 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000691 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000692 }
693
Chris Lattner78186052006-07-09 00:45:31 +0000694 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000695 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000696
697 // Now that the macro is at the top of the include stack, ask the
698 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000699 Lex(Identifier);
700 return false;
701}
702
Chris Lattneree8760b2006-07-15 07:42:55 +0000703/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000704/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000705/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000706MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
707 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000708 // The number of fixed arguments to parse.
709 unsigned NumFixedArgsLeft = MI->getNumArgs();
710 bool isVariadic = MI->isVariadic();
711
Chris Lattner78186052006-07-09 00:45:31 +0000712 // Outer loop, while there are more arguments, keep reading them.
713 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000714 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000715 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000716
717 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000718 // argument is separated by an EOF token. Use a SmallVector so we can avoid
719 // heap allocations in the common case.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000720 llvm::SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000721
722 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000723 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000724 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
725 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000726
Chris Lattner78186052006-07-09 00:45:31 +0000727 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000728 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
729 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000730 LexUnexpandedToken(Tok);
731
732 if (Tok.getKind() == tok::eof) {
733 Diag(MacroName, diag::err_unterm_macro_invoc);
734 // Do not lose the EOF. Return it to the client.
735 MacroName = Tok;
736 return 0;
737 } else if (Tok.getKind() == tok::r_paren) {
738 // If we found the ) token, the macro arg list is done.
739 if (NumParens-- == 0)
740 break;
741 } else if (Tok.getKind() == tok::l_paren) {
742 ++NumParens;
743 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
744 // Comma ends this argument if there are more fixed arguments expected.
745 if (NumFixedArgsLeft)
746 break;
747
Chris Lattner2ada5d32006-07-15 07:51:24 +0000748 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000749 if (!isVariadic) {
750 // Emit the diagnostic at the macro name in case there is a missing ).
751 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000752 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000753 return 0;
754 }
755 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000756 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000757 // If this is a comment token in the argument list and we're just in
758 // -C mode (not -CC mode), discard the comment.
759 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000760 }
761
762 ArgTokens.push_back(Tok);
763 }
764
Chris Lattnera12dd152006-07-11 04:09:02 +0000765 // Empty arguments are standard in C99 and supported as an extension in
766 // other modes.
767 if (ArgTokens.empty() && !Features.C99)
768 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000769
Chris Lattner36b6e812006-07-21 06:38:30 +0000770 // Add a marker EOF token to the end of the token list for this argument.
771 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000772 EOFTok.startToken();
773 EOFTok.setKind(tok::eof);
774 EOFTok.setLocation(Tok.getLocation());
775 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000776 ArgTokens.push_back(EOFTok);
777 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000778 --NumFixedArgsLeft;
779 };
780
781 // Okay, we either found the r_paren. Check to see if we parsed too few
782 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000783 unsigned MinArgsExpected = MI->getNumArgs();
784
Chris Lattner775d8322006-07-29 04:39:41 +0000785 // See MacroArgs instance var for description of this.
786 bool isVarargsElided = false;
787
Chris Lattner2ada5d32006-07-15 07:51:24 +0000788 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000789 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000790 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000791 // Varargs where the named vararg parameter is missing: ok as extension.
792 // #define A(x, ...)
793 // A("blah")
794 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000795
796 // Remember this occurred if this is a C99 macro invocation with at least
797 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000798 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000799 } else if (MI->getNumArgs() == 1) {
800 // #define A(x)
801 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000802 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000803
804 // Empty arguments are standard in C99 and supported as an extension in
805 // other modes.
806 if (ArgTokens.empty() && !Features.C99)
807 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000808 } else {
809 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000810 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000811 return 0;
812 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000813
814 // Add a marker EOF token to the end of the token list for this argument.
815 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000816 Tok.startToken();
817 Tok.setKind(tok::eof);
818 Tok.setLocation(EndLoc);
819 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000820 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000821 }
822
Chris Lattner775d8322006-07-29 04:39:41 +0000823 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000824}
825
Chris Lattnerc673f902006-06-30 06:10:41 +0000826/// ComputeDATE_TIME - Compute the current time, enter it into the specified
827/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
828/// the identifier tokens inserted.
829static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000830 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000831 time_t TT = time(0);
832 struct tm *TM = localtime(&TT);
833
834 static const char * const Months[] = {
835 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
836 };
837
838 char TmpBuffer[100];
839 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
840 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000841 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000842
843 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000844 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000845}
846
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000847/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
848/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000849void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000850 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000851 IdentifierInfo *II = Tok.getIdentifierInfo();
852 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000853
854 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
855 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000856 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000857 return Handle_Pragma(Tok);
858
Chris Lattner78186052006-07-09 00:45:31 +0000859 ++NumBuiltinMacroExpanded;
860
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000861 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000862
863 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000864 Tok.setIdentifierInfo(0);
865 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000866
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000867 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000868 // __LINE__ expands to a simple numeric value.
869 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
870 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000871 Tok.setKind(tok::numeric_constant);
872 Tok.setLength(Length);
873 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000874 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000875 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000876 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000877 Diag(Tok, diag::ext_pp_base_file);
878 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
879 while (NextLoc.getFileID() != 0) {
880 Loc = NextLoc;
881 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
882 }
883 }
884
Chris Lattner0766e592006-07-03 01:07:01 +0000885 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
886 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000887 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000888 Tok.setKind(tok::string_literal);
889 Tok.setLength(FN.size());
890 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000891 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000892 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000893 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000894 Tok.setKind(tok::string_literal);
895 Tok.setLength(strlen("\"Mmm dd yyyy\""));
896 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000897 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000898 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000899 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000900 Tok.setKind(tok::string_literal);
901 Tok.setLength(strlen("\"hh:mm:ss\""));
902 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000903 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000904 Diag(Tok, diag::ext_pp_include_level);
905
906 // Compute the include depth of this token.
907 unsigned Depth = 0;
908 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
909 for (; Loc.getFileID() != 0; ++Depth)
910 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
911
912 // __INCLUDE_LEVEL__ expands to a simple numeric value.
913 sprintf(TmpBuffer, "%u", Depth);
914 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000915 Tok.setKind(tok::numeric_constant);
916 Tok.setLength(Length);
917 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000918 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000919 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
920 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
921 Diag(Tok, diag::ext_pp_timestamp);
922
923 // Get the file that we are lexing out of. If we're currently lexing from
924 // a macro, dig into the include stack.
925 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000926 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000927
928 if (TheLexer)
929 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
930
931 // If this file is older than the file it depends on, emit a diagnostic.
932 const char *Result;
933 if (CurFile) {
934 time_t TT = CurFile->getModificationTime();
935 struct tm *TM = localtime(&TT);
936 Result = asctime(TM);
937 } else {
938 Result = "??? ??? ?? ??:??:?? ????\n";
939 }
940 TmpBuffer[0] = '"';
941 strcpy(TmpBuffer+1, Result);
942 unsigned Len = strlen(TmpBuffer);
943 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000944 Tok.setKind(tok::string_literal);
945 Tok.setLength(Len);
946 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000947 } else {
948 assert(0 && "Unknown identifier!");
949 }
950}
Chris Lattner677757a2006-06-28 05:26:32 +0000951
952//===----------------------------------------------------------------------===//
953// Lexer Event Handling.
954//===----------------------------------------------------------------------===//
955
Chris Lattnercefc7682006-07-08 08:28:12 +0000956/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
957/// identifier information for the token and install it into the token.
958IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
959 const char *BufPtr) {
960 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
961 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
962
963 // Look up this token, see if it is a macro, or if it is a language keyword.
964 IdentifierInfo *II;
965 if (BufPtr && !Identifier.needsCleaning()) {
966 // No cleaning needed, just use the characters from the lexed buffer.
967 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
968 } else {
969 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +0000970 llvm::SmallVector<char, 64> IdentifierBuffer;
971 IdentifierBuffer.resize(Identifier.getLength());
972 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +0000973 unsigned Size = getSpelling(Identifier, TmpBuf);
974 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
975 }
Chris Lattner8c204872006-10-14 05:19:21 +0000976 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000977 return II;
978}
979
980
Chris Lattner677757a2006-06-28 05:26:32 +0000981/// HandleIdentifier - This callback is invoked when the lexer reads an
982/// identifier. This callback looks up the identifier in the map and/or
983/// potentially macro expands it or turns it into a named token (like 'for').
984void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000985 assert(Identifier.getIdentifierInfo() &&
986 "Can't handle identifiers without identifier info!");
987
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000988 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000989
990 // If this identifier was poisoned, and if it was not produced from a macro
991 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000992 if (II.isPoisoned() && CurLexer) {
993 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
994 Diag(Identifier, diag::err_pp_used_poisoned_id);
995 else
996 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
997 }
Chris Lattner677757a2006-06-28 05:26:32 +0000998
Chris Lattner78186052006-07-09 00:45:31 +0000999 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +00001000 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001001 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1002 if (MI->isEnabled()) {
1003 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1004 return;
1005 } else {
1006 // C99 6.10.3.4p2 says that a disabled macro may never again be
1007 // expanded, even if it's in a context where it could be expanded in the
1008 // future.
Chris Lattner8c204872006-10-14 05:19:21 +00001009 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001010 }
1011 }
Chris Lattner063400e2006-10-14 19:54:15 +00001012 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1013 // If this identifier is a macro on some other target, emit a diagnostic.
1014 // This diagnosic is only emitted when macro expansion is enabled, because
1015 // the macro would not have been expanded for the other target either.
1016 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1017 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1018 diag::port_target_macro_use);
1019
1020 }
Chris Lattner677757a2006-06-28 05:26:32 +00001021
Chris Lattner5b9f4892006-11-21 17:23:33 +00001022 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1023 // then we act as if it is the actual operator and not the textual
1024 // representation of it.
1025 if (II.isCPlusPlusOperatorKeyword())
1026 Identifier.setIdentifierInfo(0);
1027
Chris Lattner677757a2006-06-28 05:26:32 +00001028 // Change the kind of this identifier to the appropriate token kind, e.g.
1029 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001030 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001031
1032 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001033 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1034 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001035 if (II.isExtensionToken() && Features.C99)
1036 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001037}
1038
Chris Lattner22eb9722006-06-18 05:43:12 +00001039/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1040/// the current file. This either returns the EOF token or pops a level off
1041/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001042bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001043 assert(!CurMacroExpander &&
1044 "Ending a file when currently in a macro!");
1045
Chris Lattner371ac8a2006-07-04 07:11:10 +00001046 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001047 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001048 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001049 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001050 // Okay, this has a controlling macro, remember in PerFileInfo.
1051 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001052 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1053 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001054 }
1055 }
1056
Chris Lattner22eb9722006-06-18 05:43:12 +00001057 // If this is a #include'd file, pop it off the include stack and continue
1058 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001059 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001060 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001061 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001062
1063 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001064 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001065 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1066
1067 // Get the file entry for the current file.
1068 if (const FileEntry *FE =
1069 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001070 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001071
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001072 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1073 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001074 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001075
1076 // Client should lex another token.
1077 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001078 }
1079
Chris Lattner8c204872006-10-14 05:19:21 +00001080 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001081 CurLexer->BufferPtr = CurLexer->BufferEnd;
1082 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001083 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001084
1085 // We're done with the #included file.
1086 delete CurLexer;
1087 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001088
Chris Lattner03f83482006-07-10 06:16:26 +00001089 // This is the end of the top-level file. If the diag::pp_macro_not_used
1090 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1091 // have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001092 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1093 for (IdentifierTable::iterator I = Identifiers.begin(),
1094 E = Identifiers.end(); I != E; ++I) {
1095 const IdentifierInfo &II = I->getValue();
1096 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1097 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1098 }
1099 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001100
1101 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001102}
1103
1104/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001105/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001106bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001107 assert(CurMacroExpander && !CurLexer &&
1108 "Ending a macro when currently in a #include file!");
1109
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001110 // Delete or cache the now-dead macro expander.
1111 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1112 delete CurMacroExpander;
1113 else
1114 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001115
Chris Lattner69772b02006-07-02 20:34:39 +00001116 // Handle this like a #include file being popped off the stack.
1117 CurMacroExpander = 0;
1118 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001119}
1120
1121
1122//===----------------------------------------------------------------------===//
1123// Utility Methods for Preprocessor Directive Handling.
1124//===----------------------------------------------------------------------===//
1125
1126/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1127/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001128void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001129 LexerToken Tmp;
1130 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001131 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001132 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001133}
1134
Chris Lattner652c1692006-11-21 23:47:30 +00001135/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1136static bool isCXXNamedOperator(const std::string &Spelling) {
1137 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1138 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1139 Spelling == "or" || Spelling == "xor";
1140}
1141
Chris Lattner22eb9722006-06-18 05:43:12 +00001142/// ReadMacroName - Lex and validate a macro name, which occurs after a
1143/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001144/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1145/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001146/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001147void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001148 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001149 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001150
1151 // Missing macro name?
1152 if (MacroNameTok.getKind() == tok::eom)
1153 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1154
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001155 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1156 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001157 std::string Spelling = getSpelling(MacroNameTok);
1158 if (isCXXNamedOperator(Spelling))
1159 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1160 // except for their spellings.
1161 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1162 else
1163 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001164 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001165 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001166 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001167 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001168 } else if (isDefineUndef && II->getMacroInfo() &&
1169 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001170 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001171 if (isDefineUndef == 1)
1172 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1173 else
1174 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001175 } else {
1176 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001177 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001178 }
1179
Chris Lattner22eb9722006-06-18 05:43:12 +00001180 // Invalid macro name, read and discard the rest of the line. Then set the
1181 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001182 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001183 return DiscardUntilEndOfDirective();
1184}
1185
1186/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1187/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001188void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001189 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001190 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001191 // There should be no tokens after the directive, but we allow them as an
1192 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001193 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1194 Lex(Tmp);
1195
Chris Lattner22eb9722006-06-18 05:43:12 +00001196 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001197 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1198 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001199 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001200}
1201
1202
1203
1204/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1205/// decided that the subsequent tokens are in the #if'd out portion of the
1206/// file. Lex the rest of the file, until we see an #endif. If
1207/// FoundNonSkipPortion is true, then we have already emitted code for part of
1208/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1209/// is true, then #else directives are ok, if not, then we have already seen one
1210/// so a #else directive is a duplicate. When this returns, the caller can lex
1211/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001212void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001213 bool FoundNonSkipPortion,
1214 bool FoundElse) {
1215 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001216 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001217 "Lexing a macro, not a file?");
1218
1219 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1220 FoundNonSkipPortion, FoundElse);
1221
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001222 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1223 // disabling warnings, etc.
1224 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001225 LexerToken Tok;
1226 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001227 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001228
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001229 // If this is the end of the buffer, we have an error.
1230 if (Tok.getKind() == tok::eof) {
1231 // Emit errors for each unterminated conditional on the stack, including
1232 // the current one.
1233 while (!CurLexer->ConditionalStack.empty()) {
1234 Diag(CurLexer->ConditionalStack.back().IfLoc,
1235 diag::err_pp_unterminated_conditional);
1236 CurLexer->ConditionalStack.pop_back();
1237 }
1238
1239 // Just return and let the caller lex after this #include.
1240 break;
1241 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001242
1243 // If this token is not a preprocessor directive, just skip it.
1244 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1245 continue;
1246
1247 // We just parsed a # character at the start of a line, so we're in
1248 // directive mode. Tell the lexer this so any newlines we see will be
1249 // converted into an EOM token (this terminates the macro).
1250 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001251 CurLexer->KeepCommentMode = false;
1252
Chris Lattner22eb9722006-06-18 05:43:12 +00001253
1254 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001255 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001256
1257 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1258 // something bogus), skip it.
1259 if (Tok.getKind() != tok::identifier) {
1260 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001261 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001262 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001263 continue;
1264 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001265
Chris Lattner22eb9722006-06-18 05:43:12 +00001266 // If the first letter isn't i or e, it isn't intesting to us. We know that
1267 // this is safe in the face of spelling differences, because there is no way
1268 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001269 // allows us to avoid looking up the identifier info for #define/#undef and
1270 // other common directives.
1271 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1272 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001273 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1274 FirstChar != 'i' && FirstChar != 'e') {
1275 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001276 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001277 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001278 continue;
1279 }
1280
Chris Lattnere60165f2006-06-22 06:36:29 +00001281 // Get the identifier name without trigraphs or embedded newlines. Note
1282 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1283 // when skipping.
1284 // TODO: could do this with zero copies in the no-clean case by using
1285 // strncmp below.
1286 char Directive[20];
1287 unsigned IdLen;
1288 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1289 IdLen = Tok.getLength();
1290 memcpy(Directive, RawCharData, IdLen);
1291 Directive[IdLen] = 0;
1292 } else {
1293 std::string DirectiveStr = getSpelling(Tok);
1294 IdLen = DirectiveStr.size();
1295 if (IdLen >= 20) {
1296 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001297 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001298 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001299 continue;
1300 }
1301 memcpy(Directive, &DirectiveStr[0], IdLen);
1302 Directive[IdLen] = 0;
1303 }
1304
Chris Lattner22eb9722006-06-18 05:43:12 +00001305 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001306 if ((IdLen == 2) || // "if"
1307 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1308 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001309 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1310 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001311 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001312 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001313 /*foundnonskip*/false,
1314 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001315 }
1316 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001317 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001318 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001319 PPConditionalInfo CondInfo;
1320 CondInfo.WasSkipping = true; // Silence bogus warning.
1321 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001322 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001323 assert(!InCond && "Can't be skipping if not in a conditional!");
1324
1325 // If we popped the outermost skipping block, we're done skipping!
1326 if (!CondInfo.WasSkipping)
1327 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001328 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001329 // #else directive in a skipping conditional. If not in some other
1330 // skipping conditional, and if #else hasn't already been seen, enter it
1331 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001332 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001333 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1334
1335 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001336 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001337
1338 // Note that we've seen a #else in this conditional.
1339 CondInfo.FoundElse = true;
1340
1341 // If the conditional is at the top level, and the #if block wasn't
1342 // entered, enter the #else block now.
1343 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1344 CondInfo.FoundNonSkip = true;
1345 break;
1346 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001347 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001348 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1349
1350 bool ShouldEnter;
1351 // If this is in a skipping block or if we're already handled this #if
1352 // block, don't bother parsing the condition.
1353 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001354 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001355 ShouldEnter = false;
1356 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001357 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001358 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001359 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1360 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001361 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001362 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001363 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001364 }
1365
1366 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001367 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001368
1369 // If this condition is true, enter it!
1370 if (ShouldEnter) {
1371 CondInfo.FoundNonSkip = true;
1372 break;
1373 }
1374 }
1375 }
1376
1377 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001378 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001379 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 }
1381
1382 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1383 // of the file, just stop skipping and return to lexing whatever came after
1384 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001385 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001386}
1387
1388//===----------------------------------------------------------------------===//
1389// Preprocessor Directive Handling.
1390//===----------------------------------------------------------------------===//
1391
1392/// HandleDirective - This callback is invoked when the lexer sees a # token
1393/// at the start of a line. This consumes the directive, modifies the
1394/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1395/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001396void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001397 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001398
1399 // We just parsed a # character at the start of a line, so we're in directive
1400 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001401 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001402 CurLexer->ParsingPreprocessorDirective = true;
1403
1404 ++NumDirectives;
1405
Chris Lattner371ac8a2006-07-04 07:11:10 +00001406 // We are about to read a token. For the multiple-include optimization FA to
1407 // work, we have to remember if we had read any tokens *before* this
1408 // pp-directive.
1409 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1410
Chris Lattner78186052006-07-09 00:45:31 +00001411 // Read the next token, the directive flavor. This isn't expanded due to
1412 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001413 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001414
Chris Lattner78186052006-07-09 00:45:31 +00001415 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1416 // #define A(x) #x
1417 // A(abc
1418 // #warning blah
1419 // def)
1420 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001421 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001422 Diag(Result, diag::ext_embedded_directive);
1423
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001424TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001426 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001427 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001428 case tok::comment:
1429 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1430 LexUnexpandedToken(Result);
1431 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001432
Chris Lattner22eb9722006-06-18 05:43:12 +00001433 case tok::numeric_constant:
1434 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001435 DiscardUntilEndOfDirective();
1436 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001437 default:
1438 IdentifierInfo *II = Result.getIdentifierInfo();
1439 if (II == 0) break; // Not an identifier.
1440
1441 // Ask what the preprocessor keyword ID is.
1442 switch (II->getPPKeywordID()) {
1443 default: break;
1444 // C99 6.10.1 - Conditional Inclusion.
1445 case tok::pp_if:
1446 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1447 case tok::pp_ifdef:
1448 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1449 case tok::pp_ifndef:
1450 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1451 case tok::pp_elif:
1452 return HandleElifDirective(Result);
1453 case tok::pp_else:
1454 return HandleElseDirective(Result);
1455 case tok::pp_endif:
1456 return HandleEndifDirective(Result);
1457
1458 // C99 6.10.2 - Source File Inclusion.
1459 case tok::pp_include:
1460 return HandleIncludeDirective(Result); // Handle #include.
1461
1462 // C99 6.10.3 - Macro Replacement.
1463 case tok::pp_define:
1464 return HandleDefineDirective(Result, false);
1465 case tok::pp_undef:
1466 return HandleUndefDirective(Result);
1467
1468 // C99 6.10.4 - Line Control.
1469 case tok::pp_line:
1470 // FIXME: implement #line
1471 DiscardUntilEndOfDirective();
1472 return;
1473
1474 // C99 6.10.5 - Error Directive.
1475 case tok::pp_error:
1476 return HandleUserDiagnosticDirective(Result, false);
1477
1478 // C99 6.10.6 - Pragma Directive.
1479 case tok::pp_pragma:
1480 return HandlePragmaDirective();
1481
1482 // GNU Extensions.
1483 case tok::pp_import:
1484 return HandleImportDirective(Result);
1485 case tok::pp_include_next:
1486 return HandleIncludeNextDirective(Result);
1487
1488 case tok::pp_warning:
1489 Diag(Result, diag::ext_pp_warning_directive);
1490 return HandleUserDiagnosticDirective(Result, true);
1491 case tok::pp_ident:
1492 return HandleIdentSCCSDirective(Result);
1493 case tok::pp_sccs:
1494 return HandleIdentSCCSDirective(Result);
1495 case tok::pp_assert:
1496 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001497 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001498 case tok::pp_unassert:
1499 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001500 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001501
1502 // clang extensions.
1503 case tok::pp_define_target:
1504 return HandleDefineDirective(Result, true);
1505 case tok::pp_define_other_target:
1506 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001507 }
1508 break;
1509 }
1510
1511 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001512 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001513
1514 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001515 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001516
1517 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001518}
1519
Chris Lattner01d66cc2006-07-03 22:16:27 +00001520void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001521 bool isWarning) {
1522 // Read the rest of the line raw. We do this because we don't want macros
1523 // to be expanded and we don't require that the tokens be valid preprocessing
1524 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1525 // collapse multiple consequtive white space between tokens, but this isn't
1526 // specified by the standard.
1527 std::string Message = CurLexer->ReadToEndOfLine();
1528
1529 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001530 return Diag(Tok, DiagID, Message);
1531}
1532
1533/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1534///
1535void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001536 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001537 Diag(Tok, diag::ext_pp_ident_directive);
1538
Chris Lattner371ac8a2006-07-04 07:11:10 +00001539 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001540 LexerToken StrTok;
1541 Lex(StrTok);
1542
1543 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001544 if (StrTok.getKind() != tok::string_literal &&
1545 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001546 return Diag(StrTok, diag::err_pp_malformed_ident);
1547
1548 // Verify that there is nothing after the string, other than EOM.
1549 CheckEndOfDirective("#ident");
1550
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001551 if (Callbacks)
1552 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001553}
1554
Chris Lattnerb8761832006-06-24 21:31:03 +00001555//===----------------------------------------------------------------------===//
1556// Preprocessor Include Directive Handling.
1557//===----------------------------------------------------------------------===//
1558
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001559/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1560/// checked and spelled filename, e.g. as an operand of #include. This returns
1561/// true if the input filename was in <>'s or false if it were in ""'s. The
1562/// caller is expected to provide a buffer that is large enough to hold the
1563/// spelling of the filename, but is also expected to handle the case when
1564/// this method decides to use a different buffer.
1565bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1566 const char *&BufStart,
1567 const char *&BufEnd) {
1568 // Get the text form of the filename.
1569 unsigned Len = getSpelling(FilenameTok, BufStart);
1570 BufEnd = BufStart+Len;
1571 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1572
1573 // Make sure the filename is <x> or "x".
1574 bool isAngled;
1575 if (BufStart[0] == '<') {
1576 if (BufEnd[-1] != '>') {
1577 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1578 BufStart = 0;
1579 return true;
1580 }
1581 isAngled = true;
1582 } else if (BufStart[0] == '"') {
1583 if (BufEnd[-1] != '"') {
1584 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1585 BufStart = 0;
1586 return true;
1587 }
1588 isAngled = false;
1589 } else {
1590 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1591 BufStart = 0;
1592 return true;
1593 }
1594
1595 // Diagnose #include "" as invalid.
1596 if (BufEnd-BufStart <= 2) {
1597 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1598 BufStart = 0;
1599 return "";
1600 }
1601
1602 // Skip the brackets.
1603 ++BufStart;
1604 --BufEnd;
1605 return isAngled;
1606}
1607
Chris Lattner22eb9722006-06-18 05:43:12 +00001608/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1609/// file to be included from the lexer, then include it! This is a common
1610/// routine with functionality shared between #include, #include_next and
1611/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001612void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001613 const DirectoryLookup *LookupFrom,
1614 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001615
Chris Lattner22eb9722006-06-18 05:43:12 +00001616 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001617 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001618
1619 // If the token kind is EOM, the error has already been diagnosed.
1620 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001621 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001622
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001623 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001624 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001625 FilenameBuffer.resize(FilenameTok.getLength());
1626
1627 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1628 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1629 FilenameStart, FilenameEnd);
1630 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1631 // error.
1632 if (FilenameStart == 0)
1633 return;
1634
Chris Lattner269c2322006-06-25 06:23:00 +00001635 // Verify that there is nothing after the filename, other than EOM. Use the
1636 // preprocessor to lex this in case lexing the filename entered a macro.
1637 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001638
1639 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001640 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001641 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1642
Chris Lattner22eb9722006-06-18 05:43:12 +00001643 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001644 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001645 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001646 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001647 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001648 return Diag(FilenameTok, diag::err_pp_file_not_found,
1649 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001650
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001651 // Ask HeaderInfo if we should enter this #include file.
1652 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1653 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001654 return;
1655 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001656
1657 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001658 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001659 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001660 return Diag(FilenameTok, diag::err_pp_file_not_found,
1661 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001662
1663 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001664 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001665}
1666
1667/// HandleIncludeNextDirective - Implements #include_next.
1668///
Chris Lattnercb283342006-06-18 06:48:37 +00001669void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1670 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001671
1672 // #include_next is like #include, except that we start searching after
1673 // the current found directory. If we can't do this, issue a
1674 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001675 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001676 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001677 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001678 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001679 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001680 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001681 } else {
1682 // Start looking up in the next directory.
1683 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001684 }
1685
1686 return HandleIncludeDirective(IncludeNextTok, Lookup);
1687}
1688
1689/// HandleImportDirective - Implements #import.
1690///
Chris Lattnercb283342006-06-18 06:48:37 +00001691void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1692 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001693
1694 return HandleIncludeDirective(ImportTok, 0, true);
1695}
1696
Chris Lattnerb8761832006-06-24 21:31:03 +00001697//===----------------------------------------------------------------------===//
1698// Preprocessor Macro Directive Handling.
1699//===----------------------------------------------------------------------===//
1700
Chris Lattnercefc7682006-07-08 08:28:12 +00001701/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1702/// definition has just been read. Lex the rest of the arguments and the
1703/// closing ), updating MI with what we learn. Return true if an error occurs
1704/// parsing the arg list.
1705bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001706 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1707
Chris Lattnercefc7682006-07-08 08:28:12 +00001708 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001709 while (1) {
1710 LexUnexpandedToken(Tok);
1711 switch (Tok.getKind()) {
1712 case tok::r_paren:
1713 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001714 if (Arguments.empty()) { // #define FOO()
1715 MI->setArgumentList(Arguments.begin(), Arguments.end());
1716 return false;
1717 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001718 // Otherwise we have #define FOO(A,)
1719 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1720 return true;
1721 case tok::ellipsis: // #define X(... -> C99 varargs
1722 // Warn if use of C99 feature in non-C99 mode.
1723 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1724
1725 // Lex the token after the identifier.
1726 LexUnexpandedToken(Tok);
1727 if (Tok.getKind() != tok::r_paren) {
1728 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1729 return true;
1730 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001731 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001732 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001733 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001734 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001735 return false;
1736 case tok::eom: // #define X(
1737 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1738 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001739 default:
1740 // Handle keywords and identifiers here to accept things like
1741 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001742 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001743 if (II == 0) {
1744 // #define X(1
1745 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1746 return true;
1747 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001748
1749 // If this is already used as an argument, it is used multiple times (e.g.
1750 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00001751 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1752 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001753 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1754 return true;
1755 }
1756
1757 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00001758 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001759
1760 // Lex the token after the identifier.
1761 LexUnexpandedToken(Tok);
1762
1763 switch (Tok.getKind()) {
1764 default: // #define X(A B
1765 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1766 return true;
1767 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00001768 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001769 return false;
1770 case tok::comma: // #define X(A,
1771 break;
1772 case tok::ellipsis: // #define X(A... -> GCC extension
1773 // Diagnose extension.
1774 Diag(Tok, diag::ext_named_variadic_macro);
1775
1776 // Lex the token after the identifier.
1777 LexUnexpandedToken(Tok);
1778 if (Tok.getKind() != tok::r_paren) {
1779 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1780 return true;
1781 }
1782
1783 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001784 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001785 return false;
1786 }
1787 }
1788 }
1789}
1790
Chris Lattner22eb9722006-06-18 05:43:12 +00001791/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001792/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1793/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001794///
Chris Lattner81278c62006-10-14 19:03:49 +00001795void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1796 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001797 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001798
Chris Lattner22eb9722006-06-18 05:43:12 +00001799 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001800 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001801
1802 // Error reading macro name? If so, diagnostic already issued.
1803 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001804 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00001805
Chris Lattner457fc152006-07-29 06:30:25 +00001806 // If we are supposed to keep comments in #defines, reenable comment saving
1807 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001808 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001809
Chris Lattner063400e2006-10-14 19:54:15 +00001810 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001811 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001812 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001813
Chris Lattner063400e2006-10-14 19:54:15 +00001814 // If the identifier is an 'other target' macro, clear this bit.
1815 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1816
1817
Chris Lattner22eb9722006-06-18 05:43:12 +00001818 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001819 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001820
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001821 // If this is a function-like macro definition, parse the argument list,
1822 // marking each of the identifiers as being used as macro arguments. Also,
1823 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001824 if (Tok.getKind() == tok::eom) {
1825 // If there is no body to this macro, we have no special handling here.
1826 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001827 // This is a function-like macro definition. Read the argument list.
1828 MI->setIsFunctionLike();
1829 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001830 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001831 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001832 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001833 if (CurLexer->ParsingPreprocessorDirective)
1834 DiscardUntilEndOfDirective();
1835 return;
1836 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001837
Chris Lattner815a1f92006-07-08 20:48:04 +00001838 // Read the first token after the arg list for down below.
1839 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001840 } else if (!Tok.hasLeadingSpace()) {
1841 // C99 requires whitespace between the macro definition and the body. Emit
1842 // a diagnostic for something like "#define X+".
1843 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001844 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001845 } else {
1846 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1847 // one in some cases!
1848 }
1849 } else {
1850 // This is a normal token with leading space. Clear the leading space
1851 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001852 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001853 }
1854
Chris Lattner7e374832006-07-29 03:46:57 +00001855 // If this is a definition of a variadic C99 function-like macro, not using
1856 // the GNU named varargs extension, enabled __VA_ARGS__.
1857
1858 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1859 // This gets unpoisoned where it is allowed.
1860 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1861 if (MI->isC99Varargs())
1862 Ident__VA_ARGS__->setIsPoisoned(false);
1863
Chris Lattner22eb9722006-06-18 05:43:12 +00001864 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00001865 if (MI->isObjectLike()) {
1866 // Object-like macros are very simple, just read their body.
1867 while (Tok.getKind() != tok::eom) {
1868 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001869 // Get the next token of the macro.
1870 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001871 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001872
Chris Lattnera3834342007-07-14 21:54:03 +00001873 } else {
1874 // Otherwise, read the body of a function-like macro. This has to validate
1875 // the # (stringize) operator.
1876 while (Tok.getKind() != tok::eom) {
1877 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001878
Chris Lattnera3834342007-07-14 21:54:03 +00001879 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1880 // parameters in function-like macro expansions.
1881 if (Tok.getKind() != tok::hash) {
1882 // Get the next token of the macro.
1883 LexUnexpandedToken(Tok);
1884 continue;
1885 }
1886
1887 // Get the next token of the macro.
1888 LexUnexpandedToken(Tok);
1889
1890 // Not a macro arg identifier?
1891 if (!Tok.getIdentifierInfo() ||
1892 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1893 Diag(Tok, diag::err_pp_stringize_not_parameter);
1894 delete MI;
1895
1896 // Disable __VA_ARGS__ again.
1897 Ident__VA_ARGS__->setIsPoisoned(true);
1898 return;
1899 }
1900
1901 // Things look ok, add the param name token to the macro.
1902 MI->AddTokenToBody(Tok);
1903
1904 // Get the next token of the macro.
1905 LexUnexpandedToken(Tok);
1906 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001907 }
Chris Lattner7e374832006-07-29 03:46:57 +00001908
Chris Lattnerf40fe992007-07-14 22:11:41 +00001909
Chris Lattner7e374832006-07-29 03:46:57 +00001910 // Disable __VA_ARGS__ again.
1911 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001912
Chris Lattnerbff18d52006-07-06 04:49:18 +00001913 // Check that there is no paste (##) operator at the begining or end of the
1914 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001915 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001916 if (NumTokens != 0) {
1917 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001918 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001919 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001920 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001921 }
1922 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001923 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001924 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001925 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001926 }
1927 }
1928
Chris Lattner13044d92006-07-03 05:16:44 +00001929 // If this is the primary source file, remember that this macro hasn't been
1930 // used yet.
1931 if (isInPrimaryFile())
1932 MI->setIsUsed(false);
1933
Chris Lattner22eb9722006-06-18 05:43:12 +00001934 // Finally, if this identifier already had a macro defined for it, verify that
1935 // the macro bodies are identical and free the old definition.
1936 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001937 if (!OtherMI->isUsed())
1938 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1939
Chris Lattner22eb9722006-06-18 05:43:12 +00001940 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001941 // must be the same. C99 6.10.3.2.
1942 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001943 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1944 MacroNameTok.getIdentifierInfo()->getName());
1945 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1946 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001947 delete OtherMI;
1948 }
1949
1950 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001951}
1952
Chris Lattner063400e2006-10-14 19:54:15 +00001953/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1954void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1955 LexerToken MacroNameTok;
1956 ReadMacroName(MacroNameTok, 1);
1957
1958 // Error reading macro name? If so, diagnostic already issued.
1959 if (MacroNameTok.getKind() == tok::eom)
1960 return;
1961
1962 // Check to see if this is the last token on the #undef line.
1963 CheckEndOfDirective("#define_other_target");
1964
1965 // If there is already a macro defined by this name, turn it into a
1966 // target-specific define.
1967 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1968 MI->setIsTargetSpecific(true);
1969 return;
1970 }
1971
1972 // Mark the identifier as being a macro on some other target.
1973 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1974}
1975
Chris Lattner22eb9722006-06-18 05:43:12 +00001976
1977/// HandleUndefDirective - Implements #undef.
1978///
Chris Lattnercb283342006-06-18 06:48:37 +00001979void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001980 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001981
Chris Lattner22eb9722006-06-18 05:43:12 +00001982 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001983 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001984
1985 // Error reading macro name? If so, diagnostic already issued.
1986 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001987 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001988
1989 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001990 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001991
1992 // Okay, we finally have a valid identifier to undef.
1993 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1994
Chris Lattner063400e2006-10-14 19:54:15 +00001995 // #undef untaints an identifier if it were marked by define_other_target.
1996 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1997
Chris Lattner22eb9722006-06-18 05:43:12 +00001998 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001999 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002000
Chris Lattner13044d92006-07-03 05:16:44 +00002001 if (!MI->isUsed())
2002 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002003
2004 // Free macro definition.
2005 delete MI;
2006 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002007}
2008
2009
Chris Lattnerb8761832006-06-24 21:31:03 +00002010//===----------------------------------------------------------------------===//
2011// Preprocessor Conditional Directive Handling.
2012//===----------------------------------------------------------------------===//
2013
Chris Lattner22eb9722006-06-18 05:43:12 +00002014/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002015/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2016/// if any tokens have been returned or pp-directives activated before this
2017/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002018///
Chris Lattner371ac8a2006-07-04 07:11:10 +00002019void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
2020 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002021 ++NumIf;
2022 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002023
Chris Lattner22eb9722006-06-18 05:43:12 +00002024 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002025 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002026
2027 // Error reading macro name? If so, diagnostic already issued.
2028 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00002029 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002030
2031 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002032 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2033
2034 // If the start of a top-level #ifdef, inform MIOpt.
2035 if (!ReadAnyTokensBeforeDirective &&
2036 CurLexer->getConditionalStackDepth() == 0) {
2037 assert(isIfndef && "#ifdef shouldn't reach here");
2038 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2039 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002040
Chris Lattner063400e2006-10-14 19:54:15 +00002041 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2042 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00002043
Chris Lattner81278c62006-10-14 19:03:49 +00002044 // If there is a macro, process it.
2045 if (MI) {
2046 // Mark it used.
2047 MI->setIsUsed(true);
2048
2049 // If this is the first use of a target-specific macro, warn about it.
2050 if (MI->isTargetSpecific()) {
2051 MI->setIsTargetSpecific(false); // Don't warn on second use.
2052 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2053 diag::port_target_macro_use);
2054 }
Chris Lattner063400e2006-10-14 19:54:15 +00002055 } else {
2056 // Use of a target-specific macro for some other target? If so, warn.
2057 if (MII->isOtherTargetMacro()) {
2058 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2059 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2060 diag::port_target_macro_use);
2061 }
Chris Lattner81278c62006-10-14 19:03:49 +00002062 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002063
Chris Lattner22eb9722006-06-18 05:43:12 +00002064 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002065 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002066 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002067 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002068 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002069 } else {
2070 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002071 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002072 /*Foundnonskip*/false,
2073 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002074 }
2075}
2076
2077/// HandleIfDirective - Implements the #if directive.
2078///
Chris Lattnera8654ca2006-07-04 17:42:08 +00002079void Preprocessor::HandleIfDirective(LexerToken &IfToken,
2080 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002081 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002082
Chris Lattner371ac8a2006-07-04 07:11:10 +00002083 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002084 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002085 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002086
2087 // Should we include the stuff contained by this directive?
2088 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002089 // If this condition is equivalent to #ifndef X, and if this is the first
2090 // directive seen, handle it for the multiple-include optimization.
2091 if (!ReadAnyTokensBeforeDirective &&
2092 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2093 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2094
Chris Lattner22eb9722006-06-18 05:43:12 +00002095 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002096 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002097 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002098 } else {
2099 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002100 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002101 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002102 }
2103}
2104
2105/// HandleEndifDirective - Implements the #endif directive.
2106///
Chris Lattnercb283342006-06-18 06:48:37 +00002107void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002108 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002109
Chris Lattner22eb9722006-06-18 05:43:12 +00002110 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002111 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002112
2113 PPConditionalInfo CondInfo;
2114 if (CurLexer->popConditionalLevel(CondInfo)) {
2115 // No conditionals on the stack: this is an #endif without an #if.
2116 return Diag(EndifToken, diag::err_pp_endif_without_if);
2117 }
2118
Chris Lattner371ac8a2006-07-04 07:11:10 +00002119 // If this the end of a top-level #endif, inform MIOpt.
2120 if (CurLexer->getConditionalStackDepth() == 0)
2121 CurLexer->MIOpt.ExitTopLevelConditional();
2122
Chris Lattner538d7f32006-07-20 04:31:52 +00002123 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002124 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002125}
2126
2127
Chris Lattnercb283342006-06-18 06:48:37 +00002128void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002129 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002130
Chris Lattner22eb9722006-06-18 05:43:12 +00002131 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002132 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002133
2134 PPConditionalInfo CI;
2135 if (CurLexer->popConditionalLevel(CI))
2136 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002137
2138 // If this is a top-level #else, inform the MIOpt.
2139 if (CurLexer->getConditionalStackDepth() == 0)
2140 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002141
2142 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002143 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002144
2145 // Finally, skip the rest of the contents of this block and return the first
2146 // token after it.
2147 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2148 /*FoundElse*/true);
2149}
2150
Chris Lattnercb283342006-06-18 06:48:37 +00002151void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002152 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002153
Chris Lattner22eb9722006-06-18 05:43:12 +00002154 // #elif directive in a non-skipping conditional... start skipping.
2155 // We don't care what the condition is, because we will always skip it (since
2156 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002157 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002158
2159 PPConditionalInfo CI;
2160 if (CurLexer->popConditionalLevel(CI))
2161 return Diag(ElifToken, diag::pp_err_elif_without_if);
2162
Chris Lattner371ac8a2006-07-04 07:11:10 +00002163 // If this is a top-level #elif, inform the MIOpt.
2164 if (CurLexer->getConditionalStackDepth() == 0)
2165 CurLexer->MIOpt.FoundTopLevelElse();
2166
Chris Lattner22eb9722006-06-18 05:43:12 +00002167 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002168 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002169
2170 // Finally, skip the rest of the contents of this block and return the first
2171 // token after it.
2172 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2173 /*FoundElse*/CI.FoundElse);
2174}
Chris Lattnerb8761832006-06-24 21:31:03 +00002175