blob: ee031691979964e4e0f73772b3c5f98dee56f09d [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 Lattner22eb9722006-06-18 05:43:12 +000039#include <iostream>
40using namespace llvm;
41using namespace clang;
42
43//===----------------------------------------------------------------------===//
44
Chris Lattner02dffbd2006-10-14 07:50:21 +000045Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
46 TargetInfo &target,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000047 FileManager &FM, SourceManager &SM,
48 HeaderSearch &Headers)
Chris Lattner02dffbd2006-10-14 07:50:21 +000049 : Diags(diags), Features(opts), Target(target), FileMgr(FM), SourceMgr(SM),
Chris Lattner25e0d542006-10-18 06:07:05 +000050 HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000051 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000052 ScratchBuf = new ScratchBuffer(SourceMgr);
53
Chris Lattner22eb9722006-06-18 05:43:12 +000054 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000055 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000056 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000057 NumEnteredSourceFiles = 0;
58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000059 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000060 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000061 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000062
Chris Lattner22eb9722006-06-18 05:43:12 +000063 // Macro expansion is enabled.
64 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000065 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000066
Chris Lattner8ff71992006-07-06 05:17:39 +000067 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
68 // This gets unpoisoned where it is allowed.
69 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
70
Chris Lattnerb8761832006-06-24 21:31:03 +000071 // Initialize the pragma handlers.
72 PragmaHandlers = new PragmaNamespace(0);
73 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000074
75 // Initialize builtin macros like __LINE__ and friends.
76 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000077}
78
79Preprocessor::~Preprocessor() {
80 // Free any active lexers.
81 delete CurLexer;
82
Chris Lattner69772b02006-07-02 20:34:39 +000083 while (!IncludeMacroStack.empty()) {
84 delete IncludeMacroStack.back().TheLexer;
85 delete IncludeMacroStack.back().TheMacroExpander;
86 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000087 }
Chris Lattnerb8761832006-06-24 21:31:03 +000088
89 // Release pragma information.
90 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000091
92 // Delete the scratch buffer info.
93 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000094}
95
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000096PPCallbacks::~PPCallbacks() {
97}
Chris Lattner87d3bec2006-10-17 03:44:32 +000098
Chris Lattner22eb9722006-06-18 05:43:12 +000099/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
100/// the specified LexerToken's location, translating the token's start
101/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000102void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000103 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000104 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000105}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000106
107void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
108 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
109 << getSpelling(Tok) << "'";
110
111 if (!DumpFlags) return;
112 std::cerr << "\t";
113 if (Tok.isAtStartOfLine())
114 std::cerr << " [StartOfLine]";
115 if (Tok.hasLeadingSpace())
116 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000117 if (Tok.isExpandDisabled())
118 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000119 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000120 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000121 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
122 << "']";
123 }
124}
125
126void Preprocessor::DumpMacro(const MacroInfo &MI) const {
127 std::cerr << "MACRO: ";
128 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
129 DumpToken(MI.getReplacementToken(i));
130 std::cerr << " ";
131 }
132 std::cerr << "\n";
133}
134
Chris Lattner22eb9722006-06-18 05:43:12 +0000135void Preprocessor::PrintStats() {
136 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000137 std::cerr << NumDirectives << " directives found:\n";
138 std::cerr << " " << NumDefined << " #define.\n";
139 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000140 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000141 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
142 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
143 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
144 std::cerr << " " << NumElse << " #else/#elif.\n";
145 std::cerr << " " << NumEndif << " #endif.\n";
146 std::cerr << " " << NumPragma << " #pragma.\n";
147 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
148
Chris Lattner78186052006-07-09 00:45:31 +0000149 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
150 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000151 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000152 std::cerr << (NumFastTokenPaste+NumTokenPaste)
153 << " token paste (##) operations performed, "
154 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000155}
156
157//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000158// Token Spelling
159//===----------------------------------------------------------------------===//
160
161
162/// getSpelling() - Return the 'spelling' of this token. The spelling of a
163/// token are the characters used to represent the token in the source file
164/// after trigraph expansion and escaped-newline folding. In particular, this
165/// wants to get the true, uncanonicalized, spelling of things like digraphs
166/// UCNs, etc.
167std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
168 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
169
170 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000171 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000172 if (!Tok.needsCleaning())
173 return std::string(TokStart, TokStart+Tok.getLength());
174
Chris Lattnerd01e2912006-06-18 16:22:51 +0000175 std::string Result;
176 Result.reserve(Tok.getLength());
177
Chris Lattneref9eae12006-07-04 22:33:12 +0000178 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000179 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
180 Ptr != End; ) {
181 unsigned CharSize;
182 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
183 Ptr += CharSize;
184 }
185 assert(Result.size() != unsigned(Tok.getLength()) &&
186 "NeedsCleaning flag set on something that didn't need cleaning!");
187 return Result;
188}
189
190/// getSpelling - This method is used to get the spelling of a token into a
191/// preallocated buffer, instead of as an std::string. The caller is required
192/// to allocate enough space for the token, which is guaranteed to be at least
193/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000194///
195/// Note that this method may do two possible things: it may either fill in
196/// the buffer specified with characters, or it may *change the input pointer*
197/// to point to a constant buffer with the data already in it (avoiding a
198/// copy). The caller is not allowed to modify the returned buffer pointer
199/// if an internal buffer is returned.
200unsigned Preprocessor::getSpelling(const LexerToken &Tok,
201 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000202 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
203
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000204 // If this token is an identifier, just return the string from the identifier
205 // table, which is very quick.
206 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
207 Buffer = II->getName();
208 return Tok.getLength();
209 }
210
211 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000212 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000213
214 // If this token contains nothing interesting, return it directly.
215 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000216 Buffer = TokStart;
217 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218 }
219 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000220 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
222 Ptr != End; ) {
223 unsigned CharSize;
224 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
225 Ptr += CharSize;
226 }
227 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
228 "NeedsCleaning flag set on something that didn't need cleaning!");
229
230 return OutBuf-Buffer;
231}
232
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000233
234/// CreateString - Plop the specified string into a scratch buffer and return a
235/// location for it. If specified, the source location provides a source
236/// location for the token.
237SourceLocation Preprocessor::
238CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
239 if (SLoc.isValid())
240 return ScratchBuf->getToken(Buf, Len, SLoc);
241 return ScratchBuf->getToken(Buf, Len);
242}
243
244
Chris Lattnerd01e2912006-06-18 16:22:51 +0000245//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000246// Source File Location Methods.
247//===----------------------------------------------------------------------===//
248
Chris Lattner22eb9722006-06-18 05:43:12 +0000249/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
250/// return null on failure. isAngled indicates whether the file reference is
251/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000252const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
253 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000254 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000255 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000256 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000257 // If the header lookup mechanism may be relative to the current file, pass in
258 // info about where the current file is.
259 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000260 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000261 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000262 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000263 }
264
Chris Lattner63dd32b2006-10-20 04:42:40 +0000265 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000266 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000267 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000268 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
269 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000270 if (FE) return FE;
271
272 // Otherwise, see if this is a subframework header. If so, this is relative
273 // to one of the headers on the #include stack. Walk the list of the current
274 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000275 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000276 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000277 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
278 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000279 return FE;
280 }
281
282 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
283 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000284 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000285 CurFileEnt =
286 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000287 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
288 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000289 return FE;
290 }
291 }
292
293 // Otherwise, we really couldn't find the file.
294 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000295}
296
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000297/// isInPrimaryFile - Return true if we're in the top-level file, not in a
298/// #include.
299bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000300 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000301 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000302
Chris Lattner13044d92006-07-03 05:16:44 +0000303 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000304 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000305 if (IncludeMacroStack[i].TheLexer &&
306 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
307 return IncludeMacroStack[i].TheLexer->isMainFile();
308 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000309}
310
311/// getCurrentLexer - Return the current file lexer being lexed from. Note
312/// that this ignores any potentially active macro expansions and _Pragma
313/// expansions going on at the time.
314Lexer *Preprocessor::getCurrentFileLexer() const {
315 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
316
317 // Look for a stacked lexer.
318 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000319 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000320 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
321 return L;
322 }
323 return 0;
324}
325
326
Chris Lattner22eb9722006-06-18 05:43:12 +0000327/// EnterSourceFile - Add a source file to the top of the include stack and
328/// start lexing tokens from it instead of the current buffer. Return true
329/// on failure.
330void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000331 const DirectoryLookup *CurDir,
332 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000333 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000334 ++NumEnteredSourceFiles;
335
Chris Lattner69772b02006-07-02 20:34:39 +0000336 if (MaxIncludeStackDepth < IncludeMacroStack.size())
337 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000338
Chris Lattner22eb9722006-06-18 05:43:12 +0000339 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000340 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000341 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000342 EnterSourceFileWithLexer(TheLexer, CurDir);
343}
Chris Lattner22eb9722006-06-18 05:43:12 +0000344
Chris Lattner69772b02006-07-02 20:34:39 +0000345/// EnterSourceFile - Add a source file to the top of the include stack and
346/// start lexing tokens from it instead of the current buffer.
347void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
348 const DirectoryLookup *CurDir) {
349
350 // Add the current lexer to the include stack.
351 if (CurLexer || CurMacroExpander)
352 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
353 CurMacroExpander));
354
355 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000356 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000357 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000358
359 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000360 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000361 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
362
363 // Get the file entry for the current file.
364 if (const FileEntry *FE =
365 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000366 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000367
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000368 Callbacks->FileChanged(SourceLocation(CurLexer->getCurFileID(), 0),
369 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000370 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000371}
372
Chris Lattner69772b02006-07-02 20:34:39 +0000373
374
Chris Lattner22eb9722006-06-18 05:43:12 +0000375/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000376/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000377void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000378 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
379 CurMacroExpander));
380 CurLexer = 0;
381 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000382
Chris Lattneree8760b2006-07-15 07:42:55 +0000383 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000384}
385
Chris Lattner7667d0d2006-07-16 18:16:58 +0000386/// EnterTokenStream - Add a "macro" context to the top of the include stack,
387/// which will cause the lexer to start returning the specified tokens. Note
388/// that these tokens will be re-macro-expanded when/if expansion is enabled.
389/// This method assumes that the specified stream of tokens has a permanent
390/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000391void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000392 // Save our current state.
393 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
394 CurMacroExpander));
395 CurLexer = 0;
396 CurDirLookup = 0;
397
398 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000399 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000400}
401
402/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
403/// lexer stack. This should only be used in situations where the current
404/// state of the top-of-stack lexer is known.
405void Preprocessor::RemoveTopOfLexerStack() {
406 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
407 delete CurLexer;
408 delete CurMacroExpander;
409 CurLexer = IncludeMacroStack.back().TheLexer;
410 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
411 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
412 IncludeMacroStack.pop_back();
413}
414
Chris Lattner22eb9722006-06-18 05:43:12 +0000415//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000416// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000417//===----------------------------------------------------------------------===//
418
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000419/// RegisterBuiltinMacro - Register the specified identifier in the identifier
420/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000421IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000422 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000423 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000424
425 // Mark it as being a macro that is builtin.
426 MacroInfo *MI = new MacroInfo(SourceLocation());
427 MI->setIsBuiltinMacro();
428 Id->setMacroInfo(MI);
429 return Id;
430}
431
432
Chris Lattner677757a2006-06-28 05:26:32 +0000433/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
434/// identifier table.
435void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000436 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000437 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000438 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
439 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000440 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000441
442 // GCC Extensions.
443 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
444 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000445 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000446}
447
Chris Lattnerc2395832006-07-09 00:57:04 +0000448/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
449/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000450static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
451 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000452 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
453
454 // If the token isn't an identifier, it's always literally expanded.
455 if (II == 0) return true;
456
457 // If the identifier is a macro, and if that macro is enabled, it may be
458 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000459 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
460 // Fast expanding "#define X X" is ok, because X would be disabled.
461 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000462 return false;
463
464 // If this is an object-like macro invocation, it is safe to trivially expand
465 // it.
466 if (MI->isObjectLike()) return true;
467
468 // If this is a function-like macro invocation, it's safe to trivially expand
469 // as long as the identifier is not a macro argument.
470 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
471 I != E; ++I)
472 if (*I == II)
473 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000474
Chris Lattnerc2395832006-07-09 00:57:04 +0000475 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000476}
477
Chris Lattnerc2395832006-07-09 00:57:04 +0000478
Chris Lattnerafe603f2006-07-11 04:02:46 +0000479/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
480/// lexed is a '('. If so, consume the token and return true, if not, this
481/// method should have no observable side-effect on the lexed tokens.
482bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000483 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000484 unsigned Val;
485 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000486 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000487 else
488 Val = CurMacroExpander->isNextTokenLParen();
489
490 if (Val == 2) {
491 // If we ran off the end of the lexer or macro expander, walk the include
492 // stack, looking for whatever will return the next token.
493 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
494 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
495 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000496 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000497 else
498 Val = Entry.TheMacroExpander->isNextTokenLParen();
499 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000500 }
501
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000502 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
503 // have found something that isn't a '(' or we found the end of the
504 // translation unit. In either case, return false.
505 if (Val != 1)
506 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000507
508 LexerToken Tok;
509 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000510 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
511 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000512}
Chris Lattner677757a2006-06-28 05:26:32 +0000513
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000514/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
515/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000516bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000517 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000518
519 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
520 if (MI->isBuiltinMacro()) {
521 ExpandBuiltinMacro(Identifier);
522 return false;
523 }
524
Chris Lattner81278c62006-10-14 19:03:49 +0000525 // If this is the first use of a target-specific macro, warn about it.
526 if (MI->isTargetSpecific()) {
527 MI->setIsTargetSpecific(false); // Don't warn on second use.
528 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
529 diag::port_target_macro_use);
530 }
531
Chris Lattneree8760b2006-07-15 07:42:55 +0000532 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000533 /// for each macro argument, the list of tokens that were provided to the
534 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000535 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000536
537 // If this is a function-like macro, read the arguments.
538 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000539 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
540 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000541 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000542 return true;
543
Chris Lattner78186052006-07-09 00:45:31 +0000544 // Remember that we are now parsing the arguments to a macro invocation.
545 // Preprocessor directives used inside macro arguments are not portable, and
546 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000547 InMacroArgs = true;
548 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000549
550 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000551 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000552
553 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000554 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000555
556 ++NumFnMacroExpanded;
557 } else {
558 ++NumMacroExpanded;
559 }
Chris Lattner13044d92006-07-03 05:16:44 +0000560
561 // Notice that this macro has been used.
562 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000563
564 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000565
566 // If this macro expands to no tokens, don't bother to push it onto the
567 // expansion stack, only to take it right back off.
568 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000569 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000570 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000571
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000572 // Ignore this macro use, just return the next token in the current
573 // buffer.
574 bool HadLeadingSpace = Identifier.hasLeadingSpace();
575 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
576
577 Lex(Identifier);
578
579 // If the identifier isn't on some OTHER line, inherit the leading
580 // whitespace/first-on-a-line property of this token. This handles
581 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
582 // empty.
583 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000584 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
585 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000586 }
587 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000588 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000589
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000590 } else if (MI->getNumTokens() == 1 &&
591 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000592 // Otherwise, if this macro expands into a single trivially-expanded
593 // token: expand it now. This handles common cases like
594 // "#define VAL 42".
595
596 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
597 // identifier to the expanded token.
598 bool isAtStartOfLine = Identifier.isAtStartOfLine();
599 bool hasLeadingSpace = Identifier.hasLeadingSpace();
600
601 // Remember where the token is instantiated.
602 SourceLocation InstantiateLoc = Identifier.getLocation();
603
604 // Replace the result token.
605 Identifier = MI->getReplacementToken(0);
606
607 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000608 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
609 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000610
611 // Update the tokens location to include both its logical and physical
612 // locations.
613 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000614 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000615 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000616
Chris Lattner6e4bf522006-07-27 06:59:25 +0000617 // If this is #define X X, we must mark the result as unexpandible.
618 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
619 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000620 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000621
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000622 // Since this is not an identifier token, it can't be macro expanded, so
623 // we're done.
624 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000625 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000626 }
627
Chris Lattner78186052006-07-09 00:45:31 +0000628 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000629 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000630
631 // Now that the macro is at the top of the include stack, ask the
632 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000633 Lex(Identifier);
634 return false;
635}
636
Chris Lattneree8760b2006-07-15 07:42:55 +0000637/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000638/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000639/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000640MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
641 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000642 // The number of fixed arguments to parse.
643 unsigned NumFixedArgsLeft = MI->getNumArgs();
644 bool isVariadic = MI->isVariadic();
645
Chris Lattner78186052006-07-09 00:45:31 +0000646 // Outer loop, while there are more arguments, keep reading them.
647 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000648 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000649 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000650
651 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000652 // argument is separated by an EOF token. Use a SmallVector so we can avoid
653 // heap allocations in the common case.
654 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000655
656 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000657 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000658 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
659 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000660
Chris Lattner78186052006-07-09 00:45:31 +0000661 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000662 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
663 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000664 LexUnexpandedToken(Tok);
665
666 if (Tok.getKind() == tok::eof) {
667 Diag(MacroName, diag::err_unterm_macro_invoc);
668 // Do not lose the EOF. Return it to the client.
669 MacroName = Tok;
670 return 0;
671 } else if (Tok.getKind() == tok::r_paren) {
672 // If we found the ) token, the macro arg list is done.
673 if (NumParens-- == 0)
674 break;
675 } else if (Tok.getKind() == tok::l_paren) {
676 ++NumParens;
677 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
678 // Comma ends this argument if there are more fixed arguments expected.
679 if (NumFixedArgsLeft)
680 break;
681
Chris Lattner2ada5d32006-07-15 07:51:24 +0000682 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000683 if (!isVariadic) {
684 // Emit the diagnostic at the macro name in case there is a missing ).
685 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000686 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000687 return 0;
688 }
689 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000690 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
691 // If this is a comment token in the argument list and we're just in
692 // -C mode (not -CC mode), discard the comment.
693 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000694 }
695
696 ArgTokens.push_back(Tok);
697 }
698
Chris Lattnera12dd152006-07-11 04:09:02 +0000699 // Empty arguments are standard in C99 and supported as an extension in
700 // other modes.
701 if (ArgTokens.empty() && !Features.C99)
702 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000703
Chris Lattner36b6e812006-07-21 06:38:30 +0000704 // Add a marker EOF token to the end of the token list for this argument.
705 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000706 EOFTok.startToken();
707 EOFTok.setKind(tok::eof);
708 EOFTok.setLocation(Tok.getLocation());
709 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000710 ArgTokens.push_back(EOFTok);
711 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000712 --NumFixedArgsLeft;
713 };
714
715 // Okay, we either found the r_paren. Check to see if we parsed too few
716 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000717 unsigned MinArgsExpected = MI->getNumArgs();
718
Chris Lattner775d8322006-07-29 04:39:41 +0000719 // See MacroArgs instance var for description of this.
720 bool isVarargsElided = false;
721
Chris Lattner2ada5d32006-07-15 07:51:24 +0000722 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000723 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000724 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000725 // Varargs where the named vararg parameter is missing: ok as extension.
726 // #define A(x, ...)
727 // A("blah")
728 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000729
730 // Remember this occurred if this is a C99 macro invocation with at least
731 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000732 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000733 } else if (MI->getNumArgs() == 1) {
734 // #define A(x)
735 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000736 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000737
738 // Empty arguments are standard in C99 and supported as an extension in
739 // other modes.
740 if (ArgTokens.empty() && !Features.C99)
741 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000742 } else {
743 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000744 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000745 return 0;
746 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000747
748 // Add a marker EOF token to the end of the token list for this argument.
749 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000750 Tok.startToken();
751 Tok.setKind(tok::eof);
752 Tok.setLocation(EndLoc);
753 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000754 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000755 }
756
Chris Lattner775d8322006-07-29 04:39:41 +0000757 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000758}
759
Chris Lattnerc673f902006-06-30 06:10:41 +0000760/// ComputeDATE_TIME - Compute the current time, enter it into the specified
761/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
762/// the identifier tokens inserted.
763static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000764 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000765 time_t TT = time(0);
766 struct tm *TM = localtime(&TT);
767
768 static const char * const Months[] = {
769 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
770 };
771
772 char TmpBuffer[100];
773 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
774 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000775 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000776
777 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000778 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000779}
780
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000781/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
782/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000783void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000784 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000785 IdentifierInfo *II = Tok.getIdentifierInfo();
786 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000787
788 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
789 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000790 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000791 return Handle_Pragma(Tok);
792
Chris Lattner78186052006-07-09 00:45:31 +0000793 ++NumBuiltinMacroExpanded;
794
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000795 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000796
797 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000798 Tok.setIdentifierInfo(0);
799 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000800
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000801 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000802 // __LINE__ expands to a simple numeric value.
803 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
804 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000805 Tok.setKind(tok::numeric_constant);
806 Tok.setLength(Length);
807 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000808 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000809 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000810 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000811 Diag(Tok, diag::ext_pp_base_file);
812 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
813 while (NextLoc.getFileID() != 0) {
814 Loc = NextLoc;
815 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
816 }
817 }
818
Chris Lattner0766e592006-07-03 01:07:01 +0000819 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
820 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000821 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000822 Tok.setKind(tok::string_literal);
823 Tok.setLength(FN.size());
824 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000825 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000826 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000827 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000828 Tok.setKind(tok::string_literal);
829 Tok.setLength(strlen("\"Mmm dd yyyy\""));
830 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000831 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000832 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000833 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000834 Tok.setKind(tok::string_literal);
835 Tok.setLength(strlen("\"hh:mm:ss\""));
836 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000837 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000838 Diag(Tok, diag::ext_pp_include_level);
839
840 // Compute the include depth of this token.
841 unsigned Depth = 0;
842 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
843 for (; Loc.getFileID() != 0; ++Depth)
844 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
845
846 // __INCLUDE_LEVEL__ expands to a simple numeric value.
847 sprintf(TmpBuffer, "%u", Depth);
848 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000849 Tok.setKind(tok::numeric_constant);
850 Tok.setLength(Length);
851 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000852 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000853 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
854 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
855 Diag(Tok, diag::ext_pp_timestamp);
856
857 // Get the file that we are lexing out of. If we're currently lexing from
858 // a macro, dig into the include stack.
859 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000860 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000861
862 if (TheLexer)
863 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
864
865 // If this file is older than the file it depends on, emit a diagnostic.
866 const char *Result;
867 if (CurFile) {
868 time_t TT = CurFile->getModificationTime();
869 struct tm *TM = localtime(&TT);
870 Result = asctime(TM);
871 } else {
872 Result = "??? ??? ?? ??:??:?? ????\n";
873 }
874 TmpBuffer[0] = '"';
875 strcpy(TmpBuffer+1, Result);
876 unsigned Len = strlen(TmpBuffer);
877 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000878 Tok.setKind(tok::string_literal);
879 Tok.setLength(Len);
880 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000881 } else {
882 assert(0 && "Unknown identifier!");
883 }
884}
Chris Lattner677757a2006-06-28 05:26:32 +0000885
Chris Lattner13044d92006-07-03 05:16:44 +0000886namespace {
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000887struct UnusedIdentifierReporter : public CStringMapVisitor {
Chris Lattner13044d92006-07-03 05:16:44 +0000888 Preprocessor &PP;
889 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
890
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000891 void Visit(const char *Key, void *Value) const {
892 IdentifierInfo &II = *static_cast<IdentifierInfo*>(Value);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000893 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
894 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000895 }
896};
897}
898
Chris Lattner677757a2006-06-28 05:26:32 +0000899//===----------------------------------------------------------------------===//
900// Lexer Event Handling.
901//===----------------------------------------------------------------------===//
902
Chris Lattnercefc7682006-07-08 08:28:12 +0000903/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
904/// identifier information for the token and install it into the token.
905IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
906 const char *BufPtr) {
907 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
908 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
909
910 // Look up this token, see if it is a macro, or if it is a language keyword.
911 IdentifierInfo *II;
912 if (BufPtr && !Identifier.needsCleaning()) {
913 // No cleaning needed, just use the characters from the lexed buffer.
914 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
915 } else {
916 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
917 const char *TmpBuf = (char*)alloca(Identifier.getLength());
918 unsigned Size = getSpelling(Identifier, TmpBuf);
919 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
920 }
Chris Lattner8c204872006-10-14 05:19:21 +0000921 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000922 return II;
923}
924
925
Chris Lattner677757a2006-06-28 05:26:32 +0000926/// HandleIdentifier - This callback is invoked when the lexer reads an
927/// identifier. This callback looks up the identifier in the map and/or
928/// potentially macro expands it or turns it into a named token (like 'for').
929void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000930 assert(Identifier.getIdentifierInfo() &&
931 "Can't handle identifiers without identifier info!");
932
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000933 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000934
935 // If this identifier was poisoned, and if it was not produced from a macro
936 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000937 if (II.isPoisoned() && CurLexer) {
938 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
939 Diag(Identifier, diag::err_pp_used_poisoned_id);
940 else
941 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
942 }
Chris Lattner677757a2006-06-28 05:26:32 +0000943
Chris Lattner78186052006-07-09 00:45:31 +0000944 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000945 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000946 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
947 if (MI->isEnabled()) {
948 if (!HandleMacroExpandedIdentifier(Identifier, MI))
949 return;
950 } else {
951 // C99 6.10.3.4p2 says that a disabled macro may never again be
952 // expanded, even if it's in a context where it could be expanded in the
953 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000954 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000955 }
956 }
Chris Lattner063400e2006-10-14 19:54:15 +0000957 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
958 // If this identifier is a macro on some other target, emit a diagnostic.
959 // This diagnosic is only emitted when macro expansion is enabled, because
960 // the macro would not have been expanded for the other target either.
961 II.setIsOtherTargetMacro(false); // Don't warn on second use.
962 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
963 diag::port_target_macro_use);
964
965 }
Chris Lattner677757a2006-06-28 05:26:32 +0000966
967 // Change the kind of this identifier to the appropriate token kind, e.g.
968 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000969 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000970
971 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000972 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000973}
974
Chris Lattner22eb9722006-06-18 05:43:12 +0000975/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
976/// the current file. This either returns the EOF token or pops a level off
977/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000978bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000979 assert(!CurMacroExpander &&
980 "Ending a file when currently in a macro!");
981
Chris Lattner371ac8a2006-07-04 07:11:10 +0000982 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000983 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000984 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000985 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000986 // Okay, this has a controlling macro, remember in PerFileInfo.
987 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000988 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
989 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000990 }
991 }
992
Chris Lattner22eb9722006-06-18 05:43:12 +0000993 // If this is a #include'd file, pop it off the include stack and continue
994 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000995 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000996 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000997 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +0000998
999 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001000 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001001 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1002
1003 // Get the file entry for the current file.
1004 if (const FileEntry *FE =
1005 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001006 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001007
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001008 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1009 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001010 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001011
1012 // Client should lex another token.
1013 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001014 }
1015
Chris Lattner8c204872006-10-14 05:19:21 +00001016 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001017 CurLexer->BufferPtr = CurLexer->BufferEnd;
1018 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001019 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001020
1021 // We're done with the #included file.
1022 delete CurLexer;
1023 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001024
Chris Lattner03f83482006-07-10 06:16:26 +00001025 // This is the end of the top-level file. If the diag::pp_macro_not_used
1026 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1027 // have not been used.
1028 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1029 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001030
1031 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001032}
1033
1034/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001035/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001036bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001037 assert(CurMacroExpander && !CurLexer &&
1038 "Ending a macro when currently in a #include file!");
1039
Chris Lattner22eb9722006-06-18 05:43:12 +00001040 delete CurMacroExpander;
1041
Chris Lattner69772b02006-07-02 20:34:39 +00001042 // Handle this like a #include file being popped off the stack.
1043 CurMacroExpander = 0;
1044 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001045}
1046
1047
1048//===----------------------------------------------------------------------===//
1049// Utility Methods for Preprocessor Directive Handling.
1050//===----------------------------------------------------------------------===//
1051
1052/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1053/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001054void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001055 LexerToken Tmp;
1056 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001057 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001058 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001059}
1060
1061/// ReadMacroName - Lex and validate a macro name, which occurs after a
1062/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001063/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1064/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001065/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001066void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001067 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001068 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001069
1070 // Missing macro name?
1071 if (MacroNameTok.getKind() == tok::eom)
1072 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1073
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001074 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1075 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001076 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001077 // Fall through on error.
1078 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001079 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001080
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001081 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1082 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001083 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001084 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001085 } else if (isDefineUndef && II->getMacroInfo() &&
1086 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001087 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001088 if (isDefineUndef == 1)
1089 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1090 else
1091 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001092 } else {
1093 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001094 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001095 }
1096
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 // Invalid macro name, read and discard the rest of the line. Then set the
1098 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001099 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001100 return DiscardUntilEndOfDirective();
1101}
1102
1103/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1104/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001105void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001106 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001107 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001108 // There should be no tokens after the directive, but we allow them as an
1109 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001110 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1111 Lex(Tmp);
1112
Chris Lattner22eb9722006-06-18 05:43:12 +00001113 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001114 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1115 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001116 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001117}
1118
1119
1120
1121/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1122/// decided that the subsequent tokens are in the #if'd out portion of the
1123/// file. Lex the rest of the file, until we see an #endif. If
1124/// FoundNonSkipPortion is true, then we have already emitted code for part of
1125/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1126/// is true, then #else directives are ok, if not, then we have already seen one
1127/// so a #else directive is a duplicate. When this returns, the caller can lex
1128/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001129void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001130 bool FoundNonSkipPortion,
1131 bool FoundElse) {
1132 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001133 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001134 "Lexing a macro, not a file?");
1135
1136 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1137 FoundNonSkipPortion, FoundElse);
1138
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001139 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1140 // disabling warnings, etc.
1141 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001142 LexerToken Tok;
1143 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001144 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001145
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001146 // If this is the end of the buffer, we have an error.
1147 if (Tok.getKind() == tok::eof) {
1148 // Emit errors for each unterminated conditional on the stack, including
1149 // the current one.
1150 while (!CurLexer->ConditionalStack.empty()) {
1151 Diag(CurLexer->ConditionalStack.back().IfLoc,
1152 diag::err_pp_unterminated_conditional);
1153 CurLexer->ConditionalStack.pop_back();
1154 }
1155
1156 // Just return and let the caller lex after this #include.
1157 break;
1158 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001159
1160 // If this token is not a preprocessor directive, just skip it.
1161 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1162 continue;
1163
1164 // We just parsed a # character at the start of a line, so we're in
1165 // directive mode. Tell the lexer this so any newlines we see will be
1166 // converted into an EOM token (this terminates the macro).
1167 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001168 CurLexer->KeepCommentMode = false;
1169
Chris Lattner22eb9722006-06-18 05:43:12 +00001170
1171 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001172 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001173
1174 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1175 // something bogus), skip it.
1176 if (Tok.getKind() != tok::identifier) {
1177 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001178 // Restore comment saving mode.
1179 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001180 continue;
1181 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001182
Chris Lattner22eb9722006-06-18 05:43:12 +00001183 // If the first letter isn't i or e, it isn't intesting to us. We know that
1184 // this is safe in the face of spelling differences, because there is no way
1185 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001186 // allows us to avoid looking up the identifier info for #define/#undef and
1187 // other common directives.
1188 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1189 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001190 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1191 FirstChar != 'i' && FirstChar != 'e') {
1192 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001193 // Restore comment saving mode.
1194 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001195 continue;
1196 }
1197
Chris Lattnere60165f2006-06-22 06:36:29 +00001198 // Get the identifier name without trigraphs or embedded newlines. Note
1199 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1200 // when skipping.
1201 // TODO: could do this with zero copies in the no-clean case by using
1202 // strncmp below.
1203 char Directive[20];
1204 unsigned IdLen;
1205 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1206 IdLen = Tok.getLength();
1207 memcpy(Directive, RawCharData, IdLen);
1208 Directive[IdLen] = 0;
1209 } else {
1210 std::string DirectiveStr = getSpelling(Tok);
1211 IdLen = DirectiveStr.size();
1212 if (IdLen >= 20) {
1213 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001214 // Restore comment saving mode.
1215 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001216 continue;
1217 }
1218 memcpy(Directive, &DirectiveStr[0], IdLen);
1219 Directive[IdLen] = 0;
1220 }
1221
Chris Lattner22eb9722006-06-18 05:43:12 +00001222 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001223 if ((IdLen == 2) || // "if"
1224 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1225 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001226 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1227 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001228 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001229 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001230 /*foundnonskip*/false,
1231 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001232 }
1233 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001234 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001235 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001236 PPConditionalInfo CondInfo;
1237 CondInfo.WasSkipping = true; // Silence bogus warning.
1238 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001239 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001240 assert(!InCond && "Can't be skipping if not in a conditional!");
1241
1242 // If we popped the outermost skipping block, we're done skipping!
1243 if (!CondInfo.WasSkipping)
1244 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001245 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001246 // #else directive in a skipping conditional. If not in some other
1247 // skipping conditional, and if #else hasn't already been seen, enter it
1248 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001249 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001250 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1251
1252 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001253 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001254
1255 // Note that we've seen a #else in this conditional.
1256 CondInfo.FoundElse = true;
1257
1258 // If the conditional is at the top level, and the #if block wasn't
1259 // entered, enter the #else block now.
1260 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1261 CondInfo.FoundNonSkip = true;
1262 break;
1263 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001264 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001265 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1266
1267 bool ShouldEnter;
1268 // If this is in a skipping block or if we're already handled this #if
1269 // block, don't bother parsing the condition.
1270 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001271 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001272 ShouldEnter = false;
1273 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001274 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001275 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001276 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1277 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001278 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001279 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001280 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001281 }
1282
1283 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001284 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001285
1286 // If this condition is true, enter it!
1287 if (ShouldEnter) {
1288 CondInfo.FoundNonSkip = true;
1289 break;
1290 }
1291 }
1292 }
1293
1294 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001295 // Restore comment saving mode.
1296 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001297 }
1298
1299 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1300 // of the file, just stop skipping and return to lexing whatever came after
1301 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001302 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001303}
1304
1305//===----------------------------------------------------------------------===//
1306// Preprocessor Directive Handling.
1307//===----------------------------------------------------------------------===//
1308
1309/// HandleDirective - This callback is invoked when the lexer sees a # token
1310/// at the start of a line. This consumes the directive, modifies the
1311/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1312/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001313void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001314 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001315
1316 // We just parsed a # character at the start of a line, so we're in directive
1317 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001318 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001319 CurLexer->ParsingPreprocessorDirective = true;
1320
1321 ++NumDirectives;
1322
Chris Lattner371ac8a2006-07-04 07:11:10 +00001323 // We are about to read a token. For the multiple-include optimization FA to
1324 // work, we have to remember if we had read any tokens *before* this
1325 // pp-directive.
1326 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1327
Chris Lattner78186052006-07-09 00:45:31 +00001328 // Read the next token, the directive flavor. This isn't expanded due to
1329 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001330 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001331
Chris Lattner78186052006-07-09 00:45:31 +00001332 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1333 // #define A(x) #x
1334 // A(abc
1335 // #warning blah
1336 // def)
1337 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001338 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001339 Diag(Result, diag::ext_embedded_directive);
1340
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001341TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001342 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001343 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001344 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001345 case tok::comment:
1346 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1347 LexUnexpandedToken(Result);
1348 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001349
Chris Lattner22eb9722006-06-18 05:43:12 +00001350 case tok::numeric_constant:
1351 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001352 DiscardUntilEndOfDirective();
1353 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001354 default:
1355 IdentifierInfo *II = Result.getIdentifierInfo();
1356 if (II == 0) break; // Not an identifier.
1357
1358 // Ask what the preprocessor keyword ID is.
1359 switch (II->getPPKeywordID()) {
1360 default: break;
1361 // C99 6.10.1 - Conditional Inclusion.
1362 case tok::pp_if:
1363 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1364 case tok::pp_ifdef:
1365 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1366 case tok::pp_ifndef:
1367 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1368 case tok::pp_elif:
1369 return HandleElifDirective(Result);
1370 case tok::pp_else:
1371 return HandleElseDirective(Result);
1372 case tok::pp_endif:
1373 return HandleEndifDirective(Result);
1374
1375 // C99 6.10.2 - Source File Inclusion.
1376 case tok::pp_include:
1377 return HandleIncludeDirective(Result); // Handle #include.
1378
1379 // C99 6.10.3 - Macro Replacement.
1380 case tok::pp_define:
1381 return HandleDefineDirective(Result, false);
1382 case tok::pp_undef:
1383 return HandleUndefDirective(Result);
1384
1385 // C99 6.10.4 - Line Control.
1386 case tok::pp_line:
1387 // FIXME: implement #line
1388 DiscardUntilEndOfDirective();
1389 return;
1390
1391 // C99 6.10.5 - Error Directive.
1392 case tok::pp_error:
1393 return HandleUserDiagnosticDirective(Result, false);
1394
1395 // C99 6.10.6 - Pragma Directive.
1396 case tok::pp_pragma:
1397 return HandlePragmaDirective();
1398
1399 // GNU Extensions.
1400 case tok::pp_import:
1401 return HandleImportDirective(Result);
1402 case tok::pp_include_next:
1403 return HandleIncludeNextDirective(Result);
1404
1405 case tok::pp_warning:
1406 Diag(Result, diag::ext_pp_warning_directive);
1407 return HandleUserDiagnosticDirective(Result, true);
1408 case tok::pp_ident:
1409 return HandleIdentSCCSDirective(Result);
1410 case tok::pp_sccs:
1411 return HandleIdentSCCSDirective(Result);
1412 case tok::pp_assert:
1413 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001414 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001415 case tok::pp_unassert:
1416 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001417 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001418
1419 // clang extensions.
1420 case tok::pp_define_target:
1421 return HandleDefineDirective(Result, true);
1422 case tok::pp_define_other_target:
1423 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001424 }
1425 break;
1426 }
1427
1428 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001429 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001430
1431 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001432 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001433
1434 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001435}
1436
Chris Lattner01d66cc2006-07-03 22:16:27 +00001437void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001438 bool isWarning) {
1439 // Read the rest of the line raw. We do this because we don't want macros
1440 // to be expanded and we don't require that the tokens be valid preprocessing
1441 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1442 // collapse multiple consequtive white space between tokens, but this isn't
1443 // specified by the standard.
1444 std::string Message = CurLexer->ReadToEndOfLine();
1445
1446 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001447 return Diag(Tok, DiagID, Message);
1448}
1449
1450/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1451///
1452void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001453 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001454 Diag(Tok, diag::ext_pp_ident_directive);
1455
Chris Lattner371ac8a2006-07-04 07:11:10 +00001456 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001457 LexerToken StrTok;
1458 Lex(StrTok);
1459
1460 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001461 if (StrTok.getKind() != tok::string_literal &&
1462 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001463 return Diag(StrTok, diag::err_pp_malformed_ident);
1464
1465 // Verify that there is nothing after the string, other than EOM.
1466 CheckEndOfDirective("#ident");
1467
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001468 if (Callbacks)
1469 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001470}
1471
Chris Lattnerb8761832006-06-24 21:31:03 +00001472//===----------------------------------------------------------------------===//
1473// Preprocessor Include Directive Handling.
1474//===----------------------------------------------------------------------===//
1475
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001476/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1477/// checked and spelled filename, e.g. as an operand of #include. This returns
1478/// true if the input filename was in <>'s or false if it were in ""'s. The
1479/// caller is expected to provide a buffer that is large enough to hold the
1480/// spelling of the filename, but is also expected to handle the case when
1481/// this method decides to use a different buffer.
1482bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1483 const char *&BufStart,
1484 const char *&BufEnd) {
1485 // Get the text form of the filename.
1486 unsigned Len = getSpelling(FilenameTok, BufStart);
1487 BufEnd = BufStart+Len;
1488 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1489
1490 // Make sure the filename is <x> or "x".
1491 bool isAngled;
1492 if (BufStart[0] == '<') {
1493 if (BufEnd[-1] != '>') {
1494 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1495 BufStart = 0;
1496 return true;
1497 }
1498 isAngled = true;
1499 } else if (BufStart[0] == '"') {
1500 if (BufEnd[-1] != '"') {
1501 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1502 BufStart = 0;
1503 return true;
1504 }
1505 isAngled = false;
1506 } else {
1507 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1508 BufStart = 0;
1509 return true;
1510 }
1511
1512 // Diagnose #include "" as invalid.
1513 if (BufEnd-BufStart <= 2) {
1514 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1515 BufStart = 0;
1516 return "";
1517 }
1518
1519 // Skip the brackets.
1520 ++BufStart;
1521 --BufEnd;
1522 return isAngled;
1523}
1524
Chris Lattner22eb9722006-06-18 05:43:12 +00001525/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1526/// file to be included from the lexer, then include it! This is a common
1527/// routine with functionality shared between #include, #include_next and
1528/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001529void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001530 const DirectoryLookup *LookupFrom,
1531 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001532
Chris Lattner22eb9722006-06-18 05:43:12 +00001533 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001534 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001535
1536 // If the token kind is EOM, the error has already been diagnosed.
1537 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001538 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001539
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001540 // Reserve a buffer to get the spelling.
1541 SmallVector<char, 128> FilenameBuffer;
1542 FilenameBuffer.resize(FilenameTok.getLength());
1543
1544 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1545 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1546 FilenameStart, FilenameEnd);
1547 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1548 // error.
1549 if (FilenameStart == 0)
1550 return;
1551
Chris Lattner269c2322006-06-25 06:23:00 +00001552 // Verify that there is nothing after the filename, other than EOM. Use the
1553 // preprocessor to lex this in case lexing the filename entered a macro.
1554 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001555
1556 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001557 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001558 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1559
Chris Lattner22eb9722006-06-18 05:43:12 +00001560 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001561 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001562 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001563 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001564 if (File == 0)
1565 return Diag(FilenameTok, diag::err_pp_file_not_found);
1566
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001567 // Ask HeaderInfo if we should enter this #include file.
1568 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1569 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001570 return;
1571 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001572
1573 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001574 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001575 if (FileID == 0)
1576 return Diag(FilenameTok, diag::err_pp_file_not_found);
1577
1578 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001579 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001580}
1581
1582/// HandleIncludeNextDirective - Implements #include_next.
1583///
Chris Lattnercb283342006-06-18 06:48:37 +00001584void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1585 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001586
1587 // #include_next is like #include, except that we start searching after
1588 // the current found directory. If we can't do this, issue a
1589 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001590 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001591 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001592 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001593 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001594 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001595 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001596 } else {
1597 // Start looking up in the next directory.
1598 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001599 }
1600
1601 return HandleIncludeDirective(IncludeNextTok, Lookup);
1602}
1603
1604/// HandleImportDirective - Implements #import.
1605///
Chris Lattnercb283342006-06-18 06:48:37 +00001606void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1607 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001608
1609 return HandleIncludeDirective(ImportTok, 0, true);
1610}
1611
Chris Lattnerb8761832006-06-24 21:31:03 +00001612//===----------------------------------------------------------------------===//
1613// Preprocessor Macro Directive Handling.
1614//===----------------------------------------------------------------------===//
1615
Chris Lattnercefc7682006-07-08 08:28:12 +00001616/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1617/// definition has just been read. Lex the rest of the arguments and the
1618/// closing ), updating MI with what we learn. Return true if an error occurs
1619/// parsing the arg list.
1620bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1621 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001622 while (1) {
1623 LexUnexpandedToken(Tok);
1624 switch (Tok.getKind()) {
1625 case tok::r_paren:
1626 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001627 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001628 // Otherwise we have #define FOO(A,)
1629 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1630 return true;
1631 case tok::ellipsis: // #define X(... -> C99 varargs
1632 // Warn if use of C99 feature in non-C99 mode.
1633 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1634
1635 // Lex the token after the identifier.
1636 LexUnexpandedToken(Tok);
1637 if (Tok.getKind() != tok::r_paren) {
1638 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1639 return true;
1640 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001641 // Add the __VA_ARGS__ identifier as an argument.
1642 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001643 MI->setIsC99Varargs();
1644 return false;
1645 case tok::eom: // #define X(
1646 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1647 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001648 default:
1649 // Handle keywords and identifiers here to accept things like
1650 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001651 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001652 if (II == 0) {
1653 // #define X(1
1654 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1655 return true;
1656 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001657
1658 // If this is already used as an argument, it is used multiple times (e.g.
1659 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001660 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001661 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1662 return true;
1663 }
1664
1665 // Add the argument to the macro info.
1666 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001667
1668 // Lex the token after the identifier.
1669 LexUnexpandedToken(Tok);
1670
1671 switch (Tok.getKind()) {
1672 default: // #define X(A B
1673 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1674 return true;
1675 case tok::r_paren: // #define X(A)
1676 return false;
1677 case tok::comma: // #define X(A,
1678 break;
1679 case tok::ellipsis: // #define X(A... -> GCC extension
1680 // Diagnose extension.
1681 Diag(Tok, diag::ext_named_variadic_macro);
1682
1683 // Lex the token after the identifier.
1684 LexUnexpandedToken(Tok);
1685 if (Tok.getKind() != tok::r_paren) {
1686 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1687 return true;
1688 }
1689
1690 MI->setIsGNUVarargs();
1691 return false;
1692 }
1693 }
1694 }
1695}
1696
Chris Lattner22eb9722006-06-18 05:43:12 +00001697/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001698/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1699/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001700///
Chris Lattner81278c62006-10-14 19:03:49 +00001701void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1702 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001703 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001704
Chris Lattner22eb9722006-06-18 05:43:12 +00001705 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001706 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001707
1708 // Error reading macro name? If so, diagnostic already issued.
1709 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001710 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001711
Chris Lattner457fc152006-07-29 06:30:25 +00001712 // If we are supposed to keep comments in #defines, reenable comment saving
1713 // mode.
1714 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1715
Chris Lattner063400e2006-10-14 19:54:15 +00001716 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001717 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001718 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001719
Chris Lattner063400e2006-10-14 19:54:15 +00001720 // If the identifier is an 'other target' macro, clear this bit.
1721 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1722
1723
Chris Lattner22eb9722006-06-18 05:43:12 +00001724 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001725 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001726
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001727 // If this is a function-like macro definition, parse the argument list,
1728 // marking each of the identifiers as being used as macro arguments. Also,
1729 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001730 if (Tok.getKind() == tok::eom) {
1731 // If there is no body to this macro, we have no special handling here.
1732 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001733 // This is a function-like macro definition. Read the argument list.
1734 MI->setIsFunctionLike();
1735 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001736 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001737 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001738 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001739 if (CurLexer->ParsingPreprocessorDirective)
1740 DiscardUntilEndOfDirective();
1741 return;
1742 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001743
Chris Lattner815a1f92006-07-08 20:48:04 +00001744 // Read the first token after the arg list for down below.
1745 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001746 } else if (!Tok.hasLeadingSpace()) {
1747 // C99 requires whitespace between the macro definition and the body. Emit
1748 // a diagnostic for something like "#define X+".
1749 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001750 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001751 } else {
1752 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1753 // one in some cases!
1754 }
1755 } else {
1756 // This is a normal token with leading space. Clear the leading space
1757 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001758 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001759 }
1760
Chris Lattner7e374832006-07-29 03:46:57 +00001761 // If this is a definition of a variadic C99 function-like macro, not using
1762 // the GNU named varargs extension, enabled __VA_ARGS__.
1763
1764 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1765 // This gets unpoisoned where it is allowed.
1766 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1767 if (MI->isC99Varargs())
1768 Ident__VA_ARGS__->setIsPoisoned(false);
1769
Chris Lattner22eb9722006-06-18 05:43:12 +00001770 // Read the rest of the macro body.
1771 while (Tok.getKind() != tok::eom) {
1772 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001773
1774 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001775 // parameters in function-like macro expansions.
1776 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001777 // Get the next token of the macro.
1778 LexUnexpandedToken(Tok);
1779 continue;
1780 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001781
Chris Lattner815a1f92006-07-08 20:48:04 +00001782 // Get the next token of the macro.
1783 LexUnexpandedToken(Tok);
1784
1785 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001786 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001787 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001788 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001789 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001790
1791 // Disable __VA_ARGS__ again.
1792 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001793 return;
1794 }
1795
1796 // Things look ok, add the param name token to the macro.
1797 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001798
Chris Lattner22eb9722006-06-18 05:43:12 +00001799 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001800 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001801 }
Chris Lattner7e374832006-07-29 03:46:57 +00001802
1803 // Disable __VA_ARGS__ again.
1804 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001805
Chris Lattnerbff18d52006-07-06 04:49:18 +00001806 // Check that there is no paste (##) operator at the begining or end of the
1807 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001808 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001809 if (NumTokens != 0) {
1810 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001811 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001812 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001813 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001814 }
1815 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001816 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001817 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001818 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001819 }
1820 }
1821
Chris Lattner13044d92006-07-03 05:16:44 +00001822 // If this is the primary source file, remember that this macro hasn't been
1823 // used yet.
1824 if (isInPrimaryFile())
1825 MI->setIsUsed(false);
1826
Chris Lattner22eb9722006-06-18 05:43:12 +00001827 // Finally, if this identifier already had a macro defined for it, verify that
1828 // the macro bodies are identical and free the old definition.
1829 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001830 if (!OtherMI->isUsed())
1831 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1832
Chris Lattner22eb9722006-06-18 05:43:12 +00001833 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001834 // must be the same. C99 6.10.3.2.
1835 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001836 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1837 MacroNameTok.getIdentifierInfo()->getName());
1838 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1839 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001840 delete OtherMI;
1841 }
1842
1843 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001844}
1845
Chris Lattner063400e2006-10-14 19:54:15 +00001846/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1847void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1848 LexerToken MacroNameTok;
1849 ReadMacroName(MacroNameTok, 1);
1850
1851 // Error reading macro name? If so, diagnostic already issued.
1852 if (MacroNameTok.getKind() == tok::eom)
1853 return;
1854
1855 // Check to see if this is the last token on the #undef line.
1856 CheckEndOfDirective("#define_other_target");
1857
1858 // If there is already a macro defined by this name, turn it into a
1859 // target-specific define.
1860 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1861 MI->setIsTargetSpecific(true);
1862 return;
1863 }
1864
1865 // Mark the identifier as being a macro on some other target.
1866 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1867}
1868
Chris Lattner22eb9722006-06-18 05:43:12 +00001869
1870/// HandleUndefDirective - Implements #undef.
1871///
Chris Lattnercb283342006-06-18 06:48:37 +00001872void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001873 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001874
Chris Lattner22eb9722006-06-18 05:43:12 +00001875 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001876 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001877
1878 // Error reading macro name? If so, diagnostic already issued.
1879 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001880 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001881
1882 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001883 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001884
1885 // Okay, we finally have a valid identifier to undef.
1886 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1887
Chris Lattner063400e2006-10-14 19:54:15 +00001888 // #undef untaints an identifier if it were marked by define_other_target.
1889 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1890
Chris Lattner22eb9722006-06-18 05:43:12 +00001891 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001892 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001893
Chris Lattner13044d92006-07-03 05:16:44 +00001894 if (!MI->isUsed())
1895 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001896
1897 // Free macro definition.
1898 delete MI;
1899 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001900}
1901
1902
Chris Lattnerb8761832006-06-24 21:31:03 +00001903//===----------------------------------------------------------------------===//
1904// Preprocessor Conditional Directive Handling.
1905//===----------------------------------------------------------------------===//
1906
Chris Lattner22eb9722006-06-18 05:43:12 +00001907/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001908/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1909/// if any tokens have been returned or pp-directives activated before this
1910/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001911///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001912void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1913 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001914 ++NumIf;
1915 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001916
Chris Lattner22eb9722006-06-18 05:43:12 +00001917 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001918 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001919
1920 // Error reading macro name? If so, diagnostic already issued.
1921 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001922 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001923
1924 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001925 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1926
1927 // If the start of a top-level #ifdef, inform MIOpt.
1928 if (!ReadAnyTokensBeforeDirective &&
1929 CurLexer->getConditionalStackDepth() == 0) {
1930 assert(isIfndef && "#ifdef shouldn't reach here");
1931 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1932 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001933
Chris Lattner063400e2006-10-14 19:54:15 +00001934 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1935 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001936
Chris Lattner81278c62006-10-14 19:03:49 +00001937 // If there is a macro, process it.
1938 if (MI) {
1939 // Mark it used.
1940 MI->setIsUsed(true);
1941
1942 // If this is the first use of a target-specific macro, warn about it.
1943 if (MI->isTargetSpecific()) {
1944 MI->setIsTargetSpecific(false); // Don't warn on second use.
1945 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1946 diag::port_target_macro_use);
1947 }
Chris Lattner063400e2006-10-14 19:54:15 +00001948 } else {
1949 // Use of a target-specific macro for some other target? If so, warn.
1950 if (MII->isOtherTargetMacro()) {
1951 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1952 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1953 diag::port_target_macro_use);
1954 }
Chris Lattner81278c62006-10-14 19:03:49 +00001955 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001956
Chris Lattner22eb9722006-06-18 05:43:12 +00001957 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001958 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001959 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001960 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001961 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001962 } else {
1963 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001964 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001965 /*Foundnonskip*/false,
1966 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001967 }
1968}
1969
1970/// HandleIfDirective - Implements the #if directive.
1971///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001972void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1973 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001974 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001975
Chris Lattner371ac8a2006-07-04 07:11:10 +00001976 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001977 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001978 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001979
1980 // Should we include the stuff contained by this directive?
1981 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001982 // If this condition is equivalent to #ifndef X, and if this is the first
1983 // directive seen, handle it for the multiple-include optimization.
1984 if (!ReadAnyTokensBeforeDirective &&
1985 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1986 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1987
Chris Lattner22eb9722006-06-18 05:43:12 +00001988 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001989 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001990 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001991 } else {
1992 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001993 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001994 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001995 }
1996}
1997
1998/// HandleEndifDirective - Implements the #endif directive.
1999///
Chris Lattnercb283342006-06-18 06:48:37 +00002000void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002001 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002002
Chris Lattner22eb9722006-06-18 05:43:12 +00002003 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002004 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002005
2006 PPConditionalInfo CondInfo;
2007 if (CurLexer->popConditionalLevel(CondInfo)) {
2008 // No conditionals on the stack: this is an #endif without an #if.
2009 return Diag(EndifToken, diag::err_pp_endif_without_if);
2010 }
2011
Chris Lattner371ac8a2006-07-04 07:11:10 +00002012 // If this the end of a top-level #endif, inform MIOpt.
2013 if (CurLexer->getConditionalStackDepth() == 0)
2014 CurLexer->MIOpt.ExitTopLevelConditional();
2015
Chris Lattner538d7f32006-07-20 04:31:52 +00002016 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002017 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002018}
2019
2020
Chris Lattnercb283342006-06-18 06:48:37 +00002021void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002022 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002023
Chris Lattner22eb9722006-06-18 05:43:12 +00002024 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002025 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002026
2027 PPConditionalInfo CI;
2028 if (CurLexer->popConditionalLevel(CI))
2029 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002030
2031 // If this is a top-level #else, inform the MIOpt.
2032 if (CurLexer->getConditionalStackDepth() == 0)
2033 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002034
2035 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002036 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002037
2038 // Finally, skip the rest of the contents of this block and return the first
2039 // token after it.
2040 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2041 /*FoundElse*/true);
2042}
2043
Chris Lattnercb283342006-06-18 06:48:37 +00002044void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002045 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002046
Chris Lattner22eb9722006-06-18 05:43:12 +00002047 // #elif directive in a non-skipping conditional... start skipping.
2048 // We don't care what the condition is, because we will always skip it (since
2049 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002050 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002051
2052 PPConditionalInfo CI;
2053 if (CurLexer->popConditionalLevel(CI))
2054 return Diag(ElifToken, diag::pp_err_elif_without_if);
2055
Chris Lattner371ac8a2006-07-04 07:11:10 +00002056 // If this is a top-level #elif, inform the MIOpt.
2057 if (CurLexer->getConditionalStackDepth() == 0)
2058 CurLexer->MIOpt.FoundTopLevelElse();
2059
Chris Lattner22eb9722006-06-18 05:43:12 +00002060 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002061 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002062
2063 // Finally, skip the rest of the contents of this block and return the first
2064 // token after it.
2065 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2066 /*FoundElse*/CI.FoundElse);
2067}
Chris Lattnerb8761832006-06-24 21:31:03 +00002068