blob: b122b0a2e167aa45ceb4b9872f6b51838cd4c8a1 [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,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000046 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000047 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000048 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
49 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000050 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000051 ScratchBuf = new ScratchBuffer(SourceMgr);
52
Chris Lattner22eb9722006-06-18 05:43:12 +000053 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000054 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000055 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000056 NumEnteredSourceFiles = 0;
57 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000058 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000059 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000061
Chris Lattner22eb9722006-06-18 05:43:12 +000062 // Macro expansion is enabled.
63 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000064 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000065
Chris Lattner8ff71992006-07-06 05:17:39 +000066 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
67 // This gets unpoisoned where it is allowed.
68 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
69
Chris Lattnerb8761832006-06-24 21:31:03 +000070 // Initialize the pragma handlers.
71 PragmaHandlers = new PragmaNamespace(0);
72 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000073
74 // Initialize builtin macros like __LINE__ and friends.
75 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000076}
77
78Preprocessor::~Preprocessor() {
79 // Free any active lexers.
80 delete CurLexer;
81
Chris Lattner69772b02006-07-02 20:34:39 +000082 while (!IncludeMacroStack.empty()) {
83 delete IncludeMacroStack.back().TheLexer;
84 delete IncludeMacroStack.back().TheMacroExpander;
85 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000086 }
Chris Lattnerb8761832006-06-24 21:31:03 +000087
88 // Release pragma information.
89 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000090
91 // Delete the scratch buffer info.
92 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000093}
94
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000095PPCallbacks::~PPCallbacks() {
96}
Chris Lattner87d3bec2006-10-17 03:44:32 +000097
Chris Lattner22eb9722006-06-18 05:43:12 +000098/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
99/// the specified LexerToken's location, translating the token's start
100/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000101void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000102 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000103 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000104}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000105
106void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
107 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
108 << getSpelling(Tok) << "'";
109
110 if (!DumpFlags) return;
111 std::cerr << "\t";
112 if (Tok.isAtStartOfLine())
113 std::cerr << " [StartOfLine]";
114 if (Tok.hasLeadingSpace())
115 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000116 if (Tok.isExpandDisabled())
117 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000118 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000119 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000120 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
121 << "']";
122 }
123}
124
125void Preprocessor::DumpMacro(const MacroInfo &MI) const {
126 std::cerr << "MACRO: ";
127 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
128 DumpToken(MI.getReplacementToken(i));
129 std::cerr << " ";
130 }
131 std::cerr << "\n";
132}
133
Chris Lattner22eb9722006-06-18 05:43:12 +0000134void Preprocessor::PrintStats() {
135 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000136 std::cerr << NumDirectives << " directives found:\n";
137 std::cerr << " " << NumDefined << " #define.\n";
138 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000139 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000140 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
141 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
142 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
143 std::cerr << " " << NumElse << " #else/#elif.\n";
144 std::cerr << " " << NumEndif << " #endif.\n";
145 std::cerr << " " << NumPragma << " #pragma.\n";
146 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
147
Chris Lattner78186052006-07-09 00:45:31 +0000148 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
149 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000150 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000151 std::cerr << (NumFastTokenPaste+NumTokenPaste)
152 << " token paste (##) operations performed, "
153 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000154}
155
156//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000157// Token Spelling
158//===----------------------------------------------------------------------===//
159
160
161/// getSpelling() - Return the 'spelling' of this token. The spelling of a
162/// token are the characters used to represent the token in the source file
163/// after trigraph expansion and escaped-newline folding. In particular, this
164/// wants to get the true, uncanonicalized, spelling of things like digraphs
165/// UCNs, etc.
166std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
167 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
168
169 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000170 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000171 if (!Tok.needsCleaning())
172 return std::string(TokStart, TokStart+Tok.getLength());
173
Chris Lattnerd01e2912006-06-18 16:22:51 +0000174 std::string Result;
175 Result.reserve(Tok.getLength());
176
Chris Lattneref9eae12006-07-04 22:33:12 +0000177 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000178 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
179 Ptr != End; ) {
180 unsigned CharSize;
181 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
182 Ptr += CharSize;
183 }
184 assert(Result.size() != unsigned(Tok.getLength()) &&
185 "NeedsCleaning flag set on something that didn't need cleaning!");
186 return Result;
187}
188
189/// getSpelling - This method is used to get the spelling of a token into a
190/// preallocated buffer, instead of as an std::string. The caller is required
191/// to allocate enough space for the token, which is guaranteed to be at least
192/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000193///
194/// Note that this method may do two possible things: it may either fill in
195/// the buffer specified with characters, or it may *change the input pointer*
196/// to point to a constant buffer with the data already in it (avoiding a
197/// copy). The caller is not allowed to modify the returned buffer pointer
198/// if an internal buffer is returned.
199unsigned Preprocessor::getSpelling(const LexerToken &Tok,
200 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000201 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
202
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000203 // If this token is an identifier, just return the string from the identifier
204 // table, which is very quick.
205 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
206 Buffer = II->getName();
207 return Tok.getLength();
208 }
209
210 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000211 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000212
213 // If this token contains nothing interesting, return it directly.
214 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000215 Buffer = TokStart;
216 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000217 }
218 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000219 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
221 Ptr != End; ) {
222 unsigned CharSize;
223 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
224 Ptr += CharSize;
225 }
226 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
227 "NeedsCleaning flag set on something that didn't need cleaning!");
228
229 return OutBuf-Buffer;
230}
231
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000232
233/// CreateString - Plop the specified string into a scratch buffer and return a
234/// location for it. If specified, the source location provides a source
235/// location for the token.
236SourceLocation Preprocessor::
237CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
238 if (SLoc.isValid())
239 return ScratchBuf->getToken(Buf, Len, SLoc);
240 return ScratchBuf->getToken(Buf, Len);
241}
242
243
Chris Lattnerd01e2912006-06-18 16:22:51 +0000244//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000245// Source File Location Methods.
246//===----------------------------------------------------------------------===//
247
Chris Lattner22eb9722006-06-18 05:43:12 +0000248/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
249/// return null on failure. isAngled indicates whether the file reference is
250/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000251const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
252 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000253 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000254 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000255 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000256 // If the header lookup mechanism may be relative to the current file, pass in
257 // info about where the current file is.
258 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000259 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000260 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000261 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000262 }
263
Chris Lattner63dd32b2006-10-20 04:42:40 +0000264 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000265 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000266 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000267 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
268 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000269 if (FE) return FE;
270
271 // Otherwise, see if this is a subframework header. If so, this is relative
272 // to one of the headers on the #include stack. Walk the list of the current
273 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000274 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000275 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000276 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
277 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000278 return FE;
279 }
280
281 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
282 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000283 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000284 CurFileEnt =
285 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000286 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
287 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000288 return FE;
289 }
290 }
291
292 // Otherwise, we really couldn't find the file.
293 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000294}
295
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000296/// isInPrimaryFile - Return true if we're in the top-level file, not in a
297/// #include.
298bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000299 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000300 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000301
Chris Lattner13044d92006-07-03 05:16:44 +0000302 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000303 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000304 if (IncludeMacroStack[i].TheLexer &&
305 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
306 return IncludeMacroStack[i].TheLexer->isMainFile();
307 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000308}
309
310/// getCurrentLexer - Return the current file lexer being lexed from. Note
311/// that this ignores any potentially active macro expansions and _Pragma
312/// expansions going on at the time.
313Lexer *Preprocessor::getCurrentFileLexer() const {
314 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
315
316 // Look for a stacked lexer.
317 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000318 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000319 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
320 return L;
321 }
322 return 0;
323}
324
325
Chris Lattner22eb9722006-06-18 05:43:12 +0000326/// EnterSourceFile - Add a source file to the top of the include stack and
327/// start lexing tokens from it instead of the current buffer. Return true
328/// on failure.
329void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000330 const DirectoryLookup *CurDir,
331 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000332 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000333 ++NumEnteredSourceFiles;
334
Chris Lattner69772b02006-07-02 20:34:39 +0000335 if (MaxIncludeStackDepth < IncludeMacroStack.size())
336 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000337
Chris Lattner22eb9722006-06-18 05:43:12 +0000338 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000339 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000340 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000341 EnterSourceFileWithLexer(TheLexer, CurDir);
342}
Chris Lattner22eb9722006-06-18 05:43:12 +0000343
Chris Lattner69772b02006-07-02 20:34:39 +0000344/// EnterSourceFile - Add a source file to the top of the include stack and
345/// start lexing tokens from it instead of the current buffer.
346void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
347 const DirectoryLookup *CurDir) {
348
349 // Add the current lexer to the include stack.
350 if (CurLexer || CurMacroExpander)
351 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
352 CurMacroExpander));
353
354 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000355 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000356 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000357
358 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000359 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000360 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
361
362 // Get the file entry for the current file.
363 if (const FileEntry *FE =
364 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000365 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000366
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000367 Callbacks->FileChanged(SourceLocation(CurLexer->getCurFileID(), 0),
368 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000369 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000370}
371
Chris Lattner69772b02006-07-02 20:34:39 +0000372
373
Chris Lattner22eb9722006-06-18 05:43:12 +0000374/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000375/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000376void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000377 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
378 CurMacroExpander));
379 CurLexer = 0;
380 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000381
Chris Lattneree8760b2006-07-15 07:42:55 +0000382 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000383}
384
Chris Lattner7667d0d2006-07-16 18:16:58 +0000385/// EnterTokenStream - Add a "macro" context to the top of the include stack,
386/// which will cause the lexer to start returning the specified tokens. Note
387/// that these tokens will be re-macro-expanded when/if expansion is enabled.
388/// This method assumes that the specified stream of tokens has a permanent
389/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000390void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000391 // Save our current state.
392 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
393 CurMacroExpander));
394 CurLexer = 0;
395 CurDirLookup = 0;
396
397 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000398 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000399}
400
401/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
402/// lexer stack. This should only be used in situations where the current
403/// state of the top-of-stack lexer is known.
404void Preprocessor::RemoveTopOfLexerStack() {
405 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
406 delete CurLexer;
407 delete CurMacroExpander;
408 CurLexer = IncludeMacroStack.back().TheLexer;
409 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
410 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
411 IncludeMacroStack.pop_back();
412}
413
Chris Lattner22eb9722006-06-18 05:43:12 +0000414//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000415// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000416//===----------------------------------------------------------------------===//
417
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000418/// RegisterBuiltinMacro - Register the specified identifier in the identifier
419/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000420IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000421 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000422 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000423
424 // Mark it as being a macro that is builtin.
425 MacroInfo *MI = new MacroInfo(SourceLocation());
426 MI->setIsBuiltinMacro();
427 Id->setMacroInfo(MI);
428 return Id;
429}
430
431
Chris Lattner677757a2006-06-28 05:26:32 +0000432/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
433/// identifier table.
434void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000435 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000436 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000437 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
438 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000439 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000440
441 // GCC Extensions.
442 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
443 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000444 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000445}
446
Chris Lattnerc2395832006-07-09 00:57:04 +0000447/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
448/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000449static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
450 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000451 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
452
453 // If the token isn't an identifier, it's always literally expanded.
454 if (II == 0) return true;
455
456 // If the identifier is a macro, and if that macro is enabled, it may be
457 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000458 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
459 // Fast expanding "#define X X" is ok, because X would be disabled.
460 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000461 return false;
462
463 // If this is an object-like macro invocation, it is safe to trivially expand
464 // it.
465 if (MI->isObjectLike()) return true;
466
467 // If this is a function-like macro invocation, it's safe to trivially expand
468 // as long as the identifier is not a macro argument.
469 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
470 I != E; ++I)
471 if (*I == II)
472 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000473
Chris Lattnerc2395832006-07-09 00:57:04 +0000474 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000475}
476
Chris Lattnerc2395832006-07-09 00:57:04 +0000477
Chris Lattnerafe603f2006-07-11 04:02:46 +0000478/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
479/// lexed is a '('. If so, consume the token and return true, if not, this
480/// method should have no observable side-effect on the lexed tokens.
481bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000482 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000483 unsigned Val;
484 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000485 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000486 else
487 Val = CurMacroExpander->isNextTokenLParen();
488
489 if (Val == 2) {
490 // If we ran off the end of the lexer or macro expander, walk the include
491 // stack, looking for whatever will return the next token.
492 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
493 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
494 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000495 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000496 else
497 Val = Entry.TheMacroExpander->isNextTokenLParen();
498 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000499 }
500
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000501 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
502 // have found something that isn't a '(' or we found the end of the
503 // translation unit. In either case, return false.
504 if (Val != 1)
505 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000506
507 LexerToken Tok;
508 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000509 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
510 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000511}
Chris Lattner677757a2006-06-28 05:26:32 +0000512
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000513/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
514/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000515bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000516 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000517
518 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
519 if (MI->isBuiltinMacro()) {
520 ExpandBuiltinMacro(Identifier);
521 return false;
522 }
523
Chris Lattner81278c62006-10-14 19:03:49 +0000524 // If this is the first use of a target-specific macro, warn about it.
525 if (MI->isTargetSpecific()) {
526 MI->setIsTargetSpecific(false); // Don't warn on second use.
527 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
528 diag::port_target_macro_use);
529 }
530
Chris Lattneree8760b2006-07-15 07:42:55 +0000531 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000532 /// for each macro argument, the list of tokens that were provided to the
533 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000534 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000535
536 // If this is a function-like macro, read the arguments.
537 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000538 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
539 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000540 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000541 return true;
542
Chris Lattner78186052006-07-09 00:45:31 +0000543 // Remember that we are now parsing the arguments to a macro invocation.
544 // Preprocessor directives used inside macro arguments are not portable, and
545 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000546 InMacroArgs = true;
547 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000548
549 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000550 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000551
552 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000553 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000554
555 ++NumFnMacroExpanded;
556 } else {
557 ++NumMacroExpanded;
558 }
Chris Lattner13044d92006-07-03 05:16:44 +0000559
560 // Notice that this macro has been used.
561 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000562
563 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000564
565 // If this macro expands to no tokens, don't bother to push it onto the
566 // expansion stack, only to take it right back off.
567 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000568 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000569 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000570
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000571 // Ignore this macro use, just return the next token in the current
572 // buffer.
573 bool HadLeadingSpace = Identifier.hasLeadingSpace();
574 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
575
576 Lex(Identifier);
577
578 // If the identifier isn't on some OTHER line, inherit the leading
579 // whitespace/first-on-a-line property of this token. This handles
580 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
581 // empty.
582 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000583 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
584 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000585 }
586 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000587 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000588
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000589 } else if (MI->getNumTokens() == 1 &&
590 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000591 // Otherwise, if this macro expands into a single trivially-expanded
592 // token: expand it now. This handles common cases like
593 // "#define VAL 42".
594
595 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
596 // identifier to the expanded token.
597 bool isAtStartOfLine = Identifier.isAtStartOfLine();
598 bool hasLeadingSpace = Identifier.hasLeadingSpace();
599
600 // Remember where the token is instantiated.
601 SourceLocation InstantiateLoc = Identifier.getLocation();
602
603 // Replace the result token.
604 Identifier = MI->getReplacementToken(0);
605
606 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000607 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
608 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000609
610 // Update the tokens location to include both its logical and physical
611 // locations.
612 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000613 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000614 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000615
Chris Lattner6e4bf522006-07-27 06:59:25 +0000616 // If this is #define X X, we must mark the result as unexpandible.
617 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
618 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000619 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000620
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000621 // Since this is not an identifier token, it can't be macro expanded, so
622 // we're done.
623 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000624 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000625 }
626
Chris Lattner78186052006-07-09 00:45:31 +0000627 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000628 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000629
630 // Now that the macro is at the top of the include stack, ask the
631 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000632 Lex(Identifier);
633 return false;
634}
635
Chris Lattneree8760b2006-07-15 07:42:55 +0000636/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000637/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000638/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000639MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
640 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000641 // The number of fixed arguments to parse.
642 unsigned NumFixedArgsLeft = MI->getNumArgs();
643 bool isVariadic = MI->isVariadic();
644
Chris Lattner78186052006-07-09 00:45:31 +0000645 // Outer loop, while there are more arguments, keep reading them.
646 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000647 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000648 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000649
650 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000651 // argument is separated by an EOF token. Use a SmallVector so we can avoid
652 // heap allocations in the common case.
653 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000654
655 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000656 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000657 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
658 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000659
Chris Lattner78186052006-07-09 00:45:31 +0000660 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000661 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
662 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000663 LexUnexpandedToken(Tok);
664
665 if (Tok.getKind() == tok::eof) {
666 Diag(MacroName, diag::err_unterm_macro_invoc);
667 // Do not lose the EOF. Return it to the client.
668 MacroName = Tok;
669 return 0;
670 } else if (Tok.getKind() == tok::r_paren) {
671 // If we found the ) token, the macro arg list is done.
672 if (NumParens-- == 0)
673 break;
674 } else if (Tok.getKind() == tok::l_paren) {
675 ++NumParens;
676 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
677 // Comma ends this argument if there are more fixed arguments expected.
678 if (NumFixedArgsLeft)
679 break;
680
Chris Lattner2ada5d32006-07-15 07:51:24 +0000681 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000682 if (!isVariadic) {
683 // Emit the diagnostic at the macro name in case there is a missing ).
684 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000685 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000686 return 0;
687 }
688 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000689 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
690 // If this is a comment token in the argument list and we're just in
691 // -C mode (not -CC mode), discard the comment.
692 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000693 }
694
695 ArgTokens.push_back(Tok);
696 }
697
Chris Lattnera12dd152006-07-11 04:09:02 +0000698 // Empty arguments are standard in C99 and supported as an extension in
699 // other modes.
700 if (ArgTokens.empty() && !Features.C99)
701 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000702
Chris Lattner36b6e812006-07-21 06:38:30 +0000703 // Add a marker EOF token to the end of the token list for this argument.
704 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000705 EOFTok.startToken();
706 EOFTok.setKind(tok::eof);
707 EOFTok.setLocation(Tok.getLocation());
708 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000709 ArgTokens.push_back(EOFTok);
710 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000711 --NumFixedArgsLeft;
712 };
713
714 // Okay, we either found the r_paren. Check to see if we parsed too few
715 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000716 unsigned MinArgsExpected = MI->getNumArgs();
717
Chris Lattner775d8322006-07-29 04:39:41 +0000718 // See MacroArgs instance var for description of this.
719 bool isVarargsElided = false;
720
Chris Lattner2ada5d32006-07-15 07:51:24 +0000721 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000722 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000723 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000724 // Varargs where the named vararg parameter is missing: ok as extension.
725 // #define A(x, ...)
726 // A("blah")
727 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000728
729 // Remember this occurred if this is a C99 macro invocation with at least
730 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000731 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000732 } else if (MI->getNumArgs() == 1) {
733 // #define A(x)
734 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000735 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000736
737 // Empty arguments are standard in C99 and supported as an extension in
738 // other modes.
739 if (ArgTokens.empty() && !Features.C99)
740 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000741 } else {
742 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000743 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000744 return 0;
745 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000746
747 // Add a marker EOF token to the end of the token list for this argument.
748 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000749 Tok.startToken();
750 Tok.setKind(tok::eof);
751 Tok.setLocation(EndLoc);
752 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000753 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000754 }
755
Chris Lattner775d8322006-07-29 04:39:41 +0000756 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000757}
758
Chris Lattnerc673f902006-06-30 06:10:41 +0000759/// ComputeDATE_TIME - Compute the current time, enter it into the specified
760/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
761/// the identifier tokens inserted.
762static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000763 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000764 time_t TT = time(0);
765 struct tm *TM = localtime(&TT);
766
767 static const char * const Months[] = {
768 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
769 };
770
771 char TmpBuffer[100];
772 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
773 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000774 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000775
776 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000777 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000778}
779
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000780/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
781/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000782void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000783 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000784 IdentifierInfo *II = Tok.getIdentifierInfo();
785 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000786
787 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
788 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000789 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000790 return Handle_Pragma(Tok);
791
Chris Lattner78186052006-07-09 00:45:31 +0000792 ++NumBuiltinMacroExpanded;
793
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000794 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000795
796 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000797 Tok.setIdentifierInfo(0);
798 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000799
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000800 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000801 // __LINE__ expands to a simple numeric value.
802 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
803 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000804 Tok.setKind(tok::numeric_constant);
805 Tok.setLength(Length);
806 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000807 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000808 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000809 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000810 Diag(Tok, diag::ext_pp_base_file);
811 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
812 while (NextLoc.getFileID() != 0) {
813 Loc = NextLoc;
814 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
815 }
816 }
817
Chris Lattner0766e592006-07-03 01:07:01 +0000818 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
819 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000820 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000821 Tok.setKind(tok::string_literal);
822 Tok.setLength(FN.size());
823 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000824 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000825 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000826 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000827 Tok.setKind(tok::string_literal);
828 Tok.setLength(strlen("\"Mmm dd yyyy\""));
829 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000830 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000831 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000832 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000833 Tok.setKind(tok::string_literal);
834 Tok.setLength(strlen("\"hh:mm:ss\""));
835 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000836 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000837 Diag(Tok, diag::ext_pp_include_level);
838
839 // Compute the include depth of this token.
840 unsigned Depth = 0;
841 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
842 for (; Loc.getFileID() != 0; ++Depth)
843 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
844
845 // __INCLUDE_LEVEL__ expands to a simple numeric value.
846 sprintf(TmpBuffer, "%u", Depth);
847 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000848 Tok.setKind(tok::numeric_constant);
849 Tok.setLength(Length);
850 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000851 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000852 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
853 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
854 Diag(Tok, diag::ext_pp_timestamp);
855
856 // Get the file that we are lexing out of. If we're currently lexing from
857 // a macro, dig into the include stack.
858 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000859 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000860
861 if (TheLexer)
862 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
863
864 // If this file is older than the file it depends on, emit a diagnostic.
865 const char *Result;
866 if (CurFile) {
867 time_t TT = CurFile->getModificationTime();
868 struct tm *TM = localtime(&TT);
869 Result = asctime(TM);
870 } else {
871 Result = "??? ??? ?? ??:??:?? ????\n";
872 }
873 TmpBuffer[0] = '"';
874 strcpy(TmpBuffer+1, Result);
875 unsigned Len = strlen(TmpBuffer);
876 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000877 Tok.setKind(tok::string_literal);
878 Tok.setLength(Len);
879 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000880 } else {
881 assert(0 && "Unknown identifier!");
882 }
883}
Chris Lattner677757a2006-06-28 05:26:32 +0000884
Chris Lattner13044d92006-07-03 05:16:44 +0000885namespace {
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000886struct UnusedIdentifierReporter : public CStringMapVisitor {
Chris Lattner13044d92006-07-03 05:16:44 +0000887 Preprocessor &PP;
888 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
889
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000890 void Visit(const char *Key, void *Value) const {
891 IdentifierInfo &II = *static_cast<IdentifierInfo*>(Value);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000892 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
893 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000894 }
895};
896}
897
Chris Lattner677757a2006-06-28 05:26:32 +0000898//===----------------------------------------------------------------------===//
899// Lexer Event Handling.
900//===----------------------------------------------------------------------===//
901
Chris Lattnercefc7682006-07-08 08:28:12 +0000902/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
903/// identifier information for the token and install it into the token.
904IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
905 const char *BufPtr) {
906 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
907 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
908
909 // Look up this token, see if it is a macro, or if it is a language keyword.
910 IdentifierInfo *II;
911 if (BufPtr && !Identifier.needsCleaning()) {
912 // No cleaning needed, just use the characters from the lexed buffer.
913 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
914 } else {
915 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
916 const char *TmpBuf = (char*)alloca(Identifier.getLength());
917 unsigned Size = getSpelling(Identifier, TmpBuf);
918 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
919 }
Chris Lattner8c204872006-10-14 05:19:21 +0000920 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000921 return II;
922}
923
924
Chris Lattner677757a2006-06-28 05:26:32 +0000925/// HandleIdentifier - This callback is invoked when the lexer reads an
926/// identifier. This callback looks up the identifier in the map and/or
927/// potentially macro expands it or turns it into a named token (like 'for').
928void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000929 assert(Identifier.getIdentifierInfo() &&
930 "Can't handle identifiers without identifier info!");
931
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000932 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000933
934 // If this identifier was poisoned, and if it was not produced from a macro
935 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000936 if (II.isPoisoned() && CurLexer) {
937 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
938 Diag(Identifier, diag::err_pp_used_poisoned_id);
939 else
940 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
941 }
Chris Lattner677757a2006-06-28 05:26:32 +0000942
Chris Lattner78186052006-07-09 00:45:31 +0000943 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000944 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000945 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
946 if (MI->isEnabled()) {
947 if (!HandleMacroExpandedIdentifier(Identifier, MI))
948 return;
949 } else {
950 // C99 6.10.3.4p2 says that a disabled macro may never again be
951 // expanded, even if it's in a context where it could be expanded in the
952 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000953 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000954 }
955 }
Chris Lattner063400e2006-10-14 19:54:15 +0000956 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
957 // If this identifier is a macro on some other target, emit a diagnostic.
958 // This diagnosic is only emitted when macro expansion is enabled, because
959 // the macro would not have been expanded for the other target either.
960 II.setIsOtherTargetMacro(false); // Don't warn on second use.
961 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
962 diag::port_target_macro_use);
963
964 }
Chris Lattner677757a2006-06-28 05:26:32 +0000965
966 // Change the kind of this identifier to the appropriate token kind, e.g.
967 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000968 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000969
970 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000971 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000972}
973
Chris Lattner22eb9722006-06-18 05:43:12 +0000974/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
975/// the current file. This either returns the EOF token or pops a level off
976/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000977bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000978 assert(!CurMacroExpander &&
979 "Ending a file when currently in a macro!");
980
Chris Lattner371ac8a2006-07-04 07:11:10 +0000981 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000982 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000983 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000984 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000985 // Okay, this has a controlling macro, remember in PerFileInfo.
986 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000987 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
988 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000989 }
990 }
991
Chris Lattner22eb9722006-06-18 05:43:12 +0000992 // If this is a #include'd file, pop it off the include stack and continue
993 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000994 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000995 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000996 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +0000997
998 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000999 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001000 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1001
1002 // Get the file entry for the current file.
1003 if (const FileEntry *FE =
1004 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001005 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001006
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001007 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1008 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001009 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001010
1011 // Client should lex another token.
1012 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001013 }
1014
Chris Lattner8c204872006-10-14 05:19:21 +00001015 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001016 CurLexer->BufferPtr = CurLexer->BufferEnd;
1017 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001018 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001019
1020 // We're done with the #included file.
1021 delete CurLexer;
1022 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001023
Chris Lattner03f83482006-07-10 06:16:26 +00001024 // This is the end of the top-level file. If the diag::pp_macro_not_used
1025 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1026 // have not been used.
1027 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1028 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001029
1030 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001031}
1032
1033/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001034/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001035bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001036 assert(CurMacroExpander && !CurLexer &&
1037 "Ending a macro when currently in a #include file!");
1038
Chris Lattner22eb9722006-06-18 05:43:12 +00001039 delete CurMacroExpander;
1040
Chris Lattner69772b02006-07-02 20:34:39 +00001041 // Handle this like a #include file being popped off the stack.
1042 CurMacroExpander = 0;
1043 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001044}
1045
1046
1047//===----------------------------------------------------------------------===//
1048// Utility Methods for Preprocessor Directive Handling.
1049//===----------------------------------------------------------------------===//
1050
1051/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1052/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001053void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001054 LexerToken Tmp;
1055 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001056 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001057 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001058}
1059
1060/// ReadMacroName - Lex and validate a macro name, which occurs after a
1061/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001062/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1063/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001064/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001065void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001066 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001067 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001068
1069 // Missing macro name?
1070 if (MacroNameTok.getKind() == tok::eom)
1071 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1072
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001073 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1074 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001075 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001076 // Fall through on error.
1077 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001078 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001079
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001080 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1081 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001082 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001083 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001084 } else if (isDefineUndef && II->getMacroInfo() &&
1085 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001086 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001087 if (isDefineUndef == 1)
1088 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1089 else
1090 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001091 } else {
1092 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001093 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001094 }
1095
Chris Lattner22eb9722006-06-18 05:43:12 +00001096 // Invalid macro name, read and discard the rest of the line. Then set the
1097 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001098 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001099 return DiscardUntilEndOfDirective();
1100}
1101
1102/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1103/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001104void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001105 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001106 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001107 // There should be no tokens after the directive, but we allow them as an
1108 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001109 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1110 Lex(Tmp);
1111
Chris Lattner22eb9722006-06-18 05:43:12 +00001112 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001113 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1114 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001115 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001116}
1117
1118
1119
1120/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1121/// decided that the subsequent tokens are in the #if'd out portion of the
1122/// file. Lex the rest of the file, until we see an #endif. If
1123/// FoundNonSkipPortion is true, then we have already emitted code for part of
1124/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1125/// is true, then #else directives are ok, if not, then we have already seen one
1126/// so a #else directive is a duplicate. When this returns, the caller can lex
1127/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001128void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001129 bool FoundNonSkipPortion,
1130 bool FoundElse) {
1131 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001132 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001133 "Lexing a macro, not a file?");
1134
1135 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1136 FoundNonSkipPortion, FoundElse);
1137
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001138 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1139 // disabling warnings, etc.
1140 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001141 LexerToken Tok;
1142 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001143 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001144
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001145 // If this is the end of the buffer, we have an error.
1146 if (Tok.getKind() == tok::eof) {
1147 // Emit errors for each unterminated conditional on the stack, including
1148 // the current one.
1149 while (!CurLexer->ConditionalStack.empty()) {
1150 Diag(CurLexer->ConditionalStack.back().IfLoc,
1151 diag::err_pp_unterminated_conditional);
1152 CurLexer->ConditionalStack.pop_back();
1153 }
1154
1155 // Just return and let the caller lex after this #include.
1156 break;
1157 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001158
1159 // If this token is not a preprocessor directive, just skip it.
1160 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1161 continue;
1162
1163 // We just parsed a # character at the start of a line, so we're in
1164 // directive mode. Tell the lexer this so any newlines we see will be
1165 // converted into an EOM token (this terminates the macro).
1166 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001167 CurLexer->KeepCommentMode = false;
1168
Chris Lattner22eb9722006-06-18 05:43:12 +00001169
1170 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001171 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001172
1173 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1174 // something bogus), skip it.
1175 if (Tok.getKind() != tok::identifier) {
1176 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001177 // Restore comment saving mode.
1178 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001179 continue;
1180 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001181
Chris Lattner22eb9722006-06-18 05:43:12 +00001182 // If the first letter isn't i or e, it isn't intesting to us. We know that
1183 // this is safe in the face of spelling differences, because there is no way
1184 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001185 // allows us to avoid looking up the identifier info for #define/#undef and
1186 // other common directives.
1187 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1188 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001189 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1190 FirstChar != 'i' && FirstChar != 'e') {
1191 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001192 // Restore comment saving mode.
1193 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001194 continue;
1195 }
1196
Chris Lattnere60165f2006-06-22 06:36:29 +00001197 // Get the identifier name without trigraphs or embedded newlines. Note
1198 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1199 // when skipping.
1200 // TODO: could do this with zero copies in the no-clean case by using
1201 // strncmp below.
1202 char Directive[20];
1203 unsigned IdLen;
1204 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1205 IdLen = Tok.getLength();
1206 memcpy(Directive, RawCharData, IdLen);
1207 Directive[IdLen] = 0;
1208 } else {
1209 std::string DirectiveStr = getSpelling(Tok);
1210 IdLen = DirectiveStr.size();
1211 if (IdLen >= 20) {
1212 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001213 // Restore comment saving mode.
1214 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001215 continue;
1216 }
1217 memcpy(Directive, &DirectiveStr[0], IdLen);
1218 Directive[IdLen] = 0;
1219 }
1220
Chris Lattner22eb9722006-06-18 05:43:12 +00001221 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001222 if ((IdLen == 2) || // "if"
1223 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1224 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001225 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1226 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001227 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001228 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001229 /*foundnonskip*/false,
1230 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001231 }
1232 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001233 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001234 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001235 PPConditionalInfo CondInfo;
1236 CondInfo.WasSkipping = true; // Silence bogus warning.
1237 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001238 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001239 assert(!InCond && "Can't be skipping if not in a conditional!");
1240
1241 // If we popped the outermost skipping block, we're done skipping!
1242 if (!CondInfo.WasSkipping)
1243 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001244 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001245 // #else directive in a skipping conditional. If not in some other
1246 // skipping conditional, and if #else hasn't already been seen, enter it
1247 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001248 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001249 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1250
1251 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001252 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001253
1254 // Note that we've seen a #else in this conditional.
1255 CondInfo.FoundElse = true;
1256
1257 // If the conditional is at the top level, and the #if block wasn't
1258 // entered, enter the #else block now.
1259 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1260 CondInfo.FoundNonSkip = true;
1261 break;
1262 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001263 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001264 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1265
1266 bool ShouldEnter;
1267 // If this is in a skipping block or if we're already handled this #if
1268 // block, don't bother parsing the condition.
1269 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001270 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001271 ShouldEnter = false;
1272 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001273 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001274 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001275 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1276 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001277 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001278 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001279 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001280 }
1281
1282 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001283 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001284
1285 // If this condition is true, enter it!
1286 if (ShouldEnter) {
1287 CondInfo.FoundNonSkip = true;
1288 break;
1289 }
1290 }
1291 }
1292
1293 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001294 // Restore comment saving mode.
1295 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 }
1297
1298 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1299 // of the file, just stop skipping and return to lexing whatever came after
1300 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001301 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001302}
1303
1304//===----------------------------------------------------------------------===//
1305// Preprocessor Directive Handling.
1306//===----------------------------------------------------------------------===//
1307
1308/// HandleDirective - This callback is invoked when the lexer sees a # token
1309/// at the start of a line. This consumes the directive, modifies the
1310/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1311/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001312void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001313 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001314
1315 // We just parsed a # character at the start of a line, so we're in directive
1316 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001317 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001318 CurLexer->ParsingPreprocessorDirective = true;
1319
1320 ++NumDirectives;
1321
Chris Lattner371ac8a2006-07-04 07:11:10 +00001322 // We are about to read a token. For the multiple-include optimization FA to
1323 // work, we have to remember if we had read any tokens *before* this
1324 // pp-directive.
1325 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1326
Chris Lattner78186052006-07-09 00:45:31 +00001327 // Read the next token, the directive flavor. This isn't expanded due to
1328 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001329 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001330
Chris Lattner78186052006-07-09 00:45:31 +00001331 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1332 // #define A(x) #x
1333 // A(abc
1334 // #warning blah
1335 // def)
1336 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001337 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001338 Diag(Result, diag::ext_embedded_directive);
1339
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001340TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001341 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001342 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001343 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001344 case tok::comment:
1345 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1346 LexUnexpandedToken(Result);
1347 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001348
Chris Lattner22eb9722006-06-18 05:43:12 +00001349 case tok::numeric_constant:
1350 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001351 DiscardUntilEndOfDirective();
1352 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001353 default:
1354 IdentifierInfo *II = Result.getIdentifierInfo();
1355 if (II == 0) break; // Not an identifier.
1356
1357 // Ask what the preprocessor keyword ID is.
1358 switch (II->getPPKeywordID()) {
1359 default: break;
1360 // C99 6.10.1 - Conditional Inclusion.
1361 case tok::pp_if:
1362 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1363 case tok::pp_ifdef:
1364 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1365 case tok::pp_ifndef:
1366 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1367 case tok::pp_elif:
1368 return HandleElifDirective(Result);
1369 case tok::pp_else:
1370 return HandleElseDirective(Result);
1371 case tok::pp_endif:
1372 return HandleEndifDirective(Result);
1373
1374 // C99 6.10.2 - Source File Inclusion.
1375 case tok::pp_include:
1376 return HandleIncludeDirective(Result); // Handle #include.
1377
1378 // C99 6.10.3 - Macro Replacement.
1379 case tok::pp_define:
1380 return HandleDefineDirective(Result, false);
1381 case tok::pp_undef:
1382 return HandleUndefDirective(Result);
1383
1384 // C99 6.10.4 - Line Control.
1385 case tok::pp_line:
1386 // FIXME: implement #line
1387 DiscardUntilEndOfDirective();
1388 return;
1389
1390 // C99 6.10.5 - Error Directive.
1391 case tok::pp_error:
1392 return HandleUserDiagnosticDirective(Result, false);
1393
1394 // C99 6.10.6 - Pragma Directive.
1395 case tok::pp_pragma:
1396 return HandlePragmaDirective();
1397
1398 // GNU Extensions.
1399 case tok::pp_import:
1400 return HandleImportDirective(Result);
1401 case tok::pp_include_next:
1402 return HandleIncludeNextDirective(Result);
1403
1404 case tok::pp_warning:
1405 Diag(Result, diag::ext_pp_warning_directive);
1406 return HandleUserDiagnosticDirective(Result, true);
1407 case tok::pp_ident:
1408 return HandleIdentSCCSDirective(Result);
1409 case tok::pp_sccs:
1410 return HandleIdentSCCSDirective(Result);
1411 case tok::pp_assert:
1412 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001413 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001414 case tok::pp_unassert:
1415 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001416 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001417
1418 // clang extensions.
1419 case tok::pp_define_target:
1420 return HandleDefineDirective(Result, true);
1421 case tok::pp_define_other_target:
1422 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001423 }
1424 break;
1425 }
1426
1427 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001428 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001429
1430 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001431 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001432
1433 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001434}
1435
Chris Lattner01d66cc2006-07-03 22:16:27 +00001436void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001437 bool isWarning) {
1438 // Read the rest of the line raw. We do this because we don't want macros
1439 // to be expanded and we don't require that the tokens be valid preprocessing
1440 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1441 // collapse multiple consequtive white space between tokens, but this isn't
1442 // specified by the standard.
1443 std::string Message = CurLexer->ReadToEndOfLine();
1444
1445 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001446 return Diag(Tok, DiagID, Message);
1447}
1448
1449/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1450///
1451void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001452 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001453 Diag(Tok, diag::ext_pp_ident_directive);
1454
Chris Lattner371ac8a2006-07-04 07:11:10 +00001455 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001456 LexerToken StrTok;
1457 Lex(StrTok);
1458
1459 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001460 if (StrTok.getKind() != tok::string_literal &&
1461 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001462 return Diag(StrTok, diag::err_pp_malformed_ident);
1463
1464 // Verify that there is nothing after the string, other than EOM.
1465 CheckEndOfDirective("#ident");
1466
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001467 if (Callbacks)
1468 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001469}
1470
Chris Lattnerb8761832006-06-24 21:31:03 +00001471//===----------------------------------------------------------------------===//
1472// Preprocessor Include Directive Handling.
1473//===----------------------------------------------------------------------===//
1474
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001475/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1476/// checked and spelled filename, e.g. as an operand of #include. This returns
1477/// true if the input filename was in <>'s or false if it were in ""'s. The
1478/// caller is expected to provide a buffer that is large enough to hold the
1479/// spelling of the filename, but is also expected to handle the case when
1480/// this method decides to use a different buffer.
1481bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1482 const char *&BufStart,
1483 const char *&BufEnd) {
1484 // Get the text form of the filename.
1485 unsigned Len = getSpelling(FilenameTok, BufStart);
1486 BufEnd = BufStart+Len;
1487 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1488
1489 // Make sure the filename is <x> or "x".
1490 bool isAngled;
1491 if (BufStart[0] == '<') {
1492 if (BufEnd[-1] != '>') {
1493 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1494 BufStart = 0;
1495 return true;
1496 }
1497 isAngled = true;
1498 } else if (BufStart[0] == '"') {
1499 if (BufEnd[-1] != '"') {
1500 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1501 BufStart = 0;
1502 return true;
1503 }
1504 isAngled = false;
1505 } else {
1506 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1507 BufStart = 0;
1508 return true;
1509 }
1510
1511 // Diagnose #include "" as invalid.
1512 if (BufEnd-BufStart <= 2) {
1513 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1514 BufStart = 0;
1515 return "";
1516 }
1517
1518 // Skip the brackets.
1519 ++BufStart;
1520 --BufEnd;
1521 return isAngled;
1522}
1523
Chris Lattner22eb9722006-06-18 05:43:12 +00001524/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1525/// file to be included from the lexer, then include it! This is a common
1526/// routine with functionality shared between #include, #include_next and
1527/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001528void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001529 const DirectoryLookup *LookupFrom,
1530 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001531
Chris Lattner22eb9722006-06-18 05:43:12 +00001532 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001533 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001534
1535 // If the token kind is EOM, the error has already been diagnosed.
1536 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001537 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001538
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001539 // Reserve a buffer to get the spelling.
1540 SmallVector<char, 128> FilenameBuffer;
1541 FilenameBuffer.resize(FilenameTok.getLength());
1542
1543 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1544 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1545 FilenameStart, FilenameEnd);
1546 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1547 // error.
1548 if (FilenameStart == 0)
1549 return;
1550
Chris Lattner269c2322006-06-25 06:23:00 +00001551 // Verify that there is nothing after the filename, other than EOM. Use the
1552 // preprocessor to lex this in case lexing the filename entered a macro.
1553 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001554
1555 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001556 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001557 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1558
Chris Lattner22eb9722006-06-18 05:43:12 +00001559 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001560 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001561 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001562 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001563 if (File == 0)
1564 return Diag(FilenameTok, diag::err_pp_file_not_found);
1565
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001566 // Ask HeaderInfo if we should enter this #include file.
1567 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1568 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001569 return;
1570 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001571
1572 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001573 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001574 if (FileID == 0)
1575 return Diag(FilenameTok, diag::err_pp_file_not_found);
1576
1577 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001578 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001579}
1580
1581/// HandleIncludeNextDirective - Implements #include_next.
1582///
Chris Lattnercb283342006-06-18 06:48:37 +00001583void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1584 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001585
1586 // #include_next is like #include, except that we start searching after
1587 // the current found directory. If we can't do this, issue a
1588 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001589 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001590 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001591 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001592 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001593 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001594 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001595 } else {
1596 // Start looking up in the next directory.
1597 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001598 }
1599
1600 return HandleIncludeDirective(IncludeNextTok, Lookup);
1601}
1602
1603/// HandleImportDirective - Implements #import.
1604///
Chris Lattnercb283342006-06-18 06:48:37 +00001605void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1606 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001607
1608 return HandleIncludeDirective(ImportTok, 0, true);
1609}
1610
Chris Lattnerb8761832006-06-24 21:31:03 +00001611//===----------------------------------------------------------------------===//
1612// Preprocessor Macro Directive Handling.
1613//===----------------------------------------------------------------------===//
1614
Chris Lattnercefc7682006-07-08 08:28:12 +00001615/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1616/// definition has just been read. Lex the rest of the arguments and the
1617/// closing ), updating MI with what we learn. Return true if an error occurs
1618/// parsing the arg list.
1619bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1620 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001621 while (1) {
1622 LexUnexpandedToken(Tok);
1623 switch (Tok.getKind()) {
1624 case tok::r_paren:
1625 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001626 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001627 // Otherwise we have #define FOO(A,)
1628 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1629 return true;
1630 case tok::ellipsis: // #define X(... -> C99 varargs
1631 // Warn if use of C99 feature in non-C99 mode.
1632 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1633
1634 // Lex the token after the identifier.
1635 LexUnexpandedToken(Tok);
1636 if (Tok.getKind() != tok::r_paren) {
1637 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1638 return true;
1639 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001640 // Add the __VA_ARGS__ identifier as an argument.
1641 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001642 MI->setIsC99Varargs();
1643 return false;
1644 case tok::eom: // #define X(
1645 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1646 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001647 default:
1648 // Handle keywords and identifiers here to accept things like
1649 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001650 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001651 if (II == 0) {
1652 // #define X(1
1653 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1654 return true;
1655 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001656
1657 // If this is already used as an argument, it is used multiple times (e.g.
1658 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001659 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001660 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1661 return true;
1662 }
1663
1664 // Add the argument to the macro info.
1665 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001666
1667 // Lex the token after the identifier.
1668 LexUnexpandedToken(Tok);
1669
1670 switch (Tok.getKind()) {
1671 default: // #define X(A B
1672 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1673 return true;
1674 case tok::r_paren: // #define X(A)
1675 return false;
1676 case tok::comma: // #define X(A,
1677 break;
1678 case tok::ellipsis: // #define X(A... -> GCC extension
1679 // Diagnose extension.
1680 Diag(Tok, diag::ext_named_variadic_macro);
1681
1682 // Lex the token after the identifier.
1683 LexUnexpandedToken(Tok);
1684 if (Tok.getKind() != tok::r_paren) {
1685 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1686 return true;
1687 }
1688
1689 MI->setIsGNUVarargs();
1690 return false;
1691 }
1692 }
1693 }
1694}
1695
Chris Lattner22eb9722006-06-18 05:43:12 +00001696/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001697/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1698/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001699///
Chris Lattner81278c62006-10-14 19:03:49 +00001700void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1701 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001702 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001703
Chris Lattner22eb9722006-06-18 05:43:12 +00001704 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001705 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001706
1707 // Error reading macro name? If so, diagnostic already issued.
1708 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001709 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001710
Chris Lattner457fc152006-07-29 06:30:25 +00001711 // If we are supposed to keep comments in #defines, reenable comment saving
1712 // mode.
1713 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1714
Chris Lattner063400e2006-10-14 19:54:15 +00001715 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001716 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001717 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001718
Chris Lattner063400e2006-10-14 19:54:15 +00001719 // If the identifier is an 'other target' macro, clear this bit.
1720 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1721
1722
Chris Lattner22eb9722006-06-18 05:43:12 +00001723 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001724 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001725
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001726 // If this is a function-like macro definition, parse the argument list,
1727 // marking each of the identifiers as being used as macro arguments. Also,
1728 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001729 if (Tok.getKind() == tok::eom) {
1730 // If there is no body to this macro, we have no special handling here.
1731 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001732 // This is a function-like macro definition. Read the argument list.
1733 MI->setIsFunctionLike();
1734 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001735 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001736 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001737 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001738 if (CurLexer->ParsingPreprocessorDirective)
1739 DiscardUntilEndOfDirective();
1740 return;
1741 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001742
Chris Lattner815a1f92006-07-08 20:48:04 +00001743 // Read the first token after the arg list for down below.
1744 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001745 } else if (!Tok.hasLeadingSpace()) {
1746 // C99 requires whitespace between the macro definition and the body. Emit
1747 // a diagnostic for something like "#define X+".
1748 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001749 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001750 } else {
1751 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1752 // one in some cases!
1753 }
1754 } else {
1755 // This is a normal token with leading space. Clear the leading space
1756 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001757 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001758 }
1759
Chris Lattner7e374832006-07-29 03:46:57 +00001760 // If this is a definition of a variadic C99 function-like macro, not using
1761 // the GNU named varargs extension, enabled __VA_ARGS__.
1762
1763 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1764 // This gets unpoisoned where it is allowed.
1765 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1766 if (MI->isC99Varargs())
1767 Ident__VA_ARGS__->setIsPoisoned(false);
1768
Chris Lattner22eb9722006-06-18 05:43:12 +00001769 // Read the rest of the macro body.
1770 while (Tok.getKind() != tok::eom) {
1771 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001772
1773 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001774 // parameters in function-like macro expansions.
1775 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001776 // Get the next token of the macro.
1777 LexUnexpandedToken(Tok);
1778 continue;
1779 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001780
Chris Lattner815a1f92006-07-08 20:48:04 +00001781 // Get the next token of the macro.
1782 LexUnexpandedToken(Tok);
1783
1784 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001785 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001786 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001787 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001788 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001789
1790 // Disable __VA_ARGS__ again.
1791 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001792 return;
1793 }
1794
1795 // Things look ok, add the param name token to the macro.
1796 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001797
Chris Lattner22eb9722006-06-18 05:43:12 +00001798 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001799 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001800 }
Chris Lattner7e374832006-07-29 03:46:57 +00001801
1802 // Disable __VA_ARGS__ again.
1803 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001804
Chris Lattnerbff18d52006-07-06 04:49:18 +00001805 // Check that there is no paste (##) operator at the begining or end of the
1806 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001807 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001808 if (NumTokens != 0) {
1809 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001810 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001811 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001812 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001813 }
1814 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001815 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001816 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001817 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001818 }
1819 }
1820
Chris Lattner13044d92006-07-03 05:16:44 +00001821 // If this is the primary source file, remember that this macro hasn't been
1822 // used yet.
1823 if (isInPrimaryFile())
1824 MI->setIsUsed(false);
1825
Chris Lattner22eb9722006-06-18 05:43:12 +00001826 // Finally, if this identifier already had a macro defined for it, verify that
1827 // the macro bodies are identical and free the old definition.
1828 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001829 if (!OtherMI->isUsed())
1830 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1831
Chris Lattner22eb9722006-06-18 05:43:12 +00001832 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001833 // must be the same. C99 6.10.3.2.
1834 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001835 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1836 MacroNameTok.getIdentifierInfo()->getName());
1837 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1838 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001839 delete OtherMI;
1840 }
1841
1842 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001843}
1844
Chris Lattner063400e2006-10-14 19:54:15 +00001845/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1846void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1847 LexerToken MacroNameTok;
1848 ReadMacroName(MacroNameTok, 1);
1849
1850 // Error reading macro name? If so, diagnostic already issued.
1851 if (MacroNameTok.getKind() == tok::eom)
1852 return;
1853
1854 // Check to see if this is the last token on the #undef line.
1855 CheckEndOfDirective("#define_other_target");
1856
1857 // If there is already a macro defined by this name, turn it into a
1858 // target-specific define.
1859 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1860 MI->setIsTargetSpecific(true);
1861 return;
1862 }
1863
1864 // Mark the identifier as being a macro on some other target.
1865 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1866}
1867
Chris Lattner22eb9722006-06-18 05:43:12 +00001868
1869/// HandleUndefDirective - Implements #undef.
1870///
Chris Lattnercb283342006-06-18 06:48:37 +00001871void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001872 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001873
Chris Lattner22eb9722006-06-18 05:43:12 +00001874 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001875 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001876
1877 // Error reading macro name? If so, diagnostic already issued.
1878 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001879 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001880
1881 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001882 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001883
1884 // Okay, we finally have a valid identifier to undef.
1885 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1886
Chris Lattner063400e2006-10-14 19:54:15 +00001887 // #undef untaints an identifier if it were marked by define_other_target.
1888 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1889
Chris Lattner22eb9722006-06-18 05:43:12 +00001890 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001891 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001892
Chris Lattner13044d92006-07-03 05:16:44 +00001893 if (!MI->isUsed())
1894 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001895
1896 // Free macro definition.
1897 delete MI;
1898 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001899}
1900
1901
Chris Lattnerb8761832006-06-24 21:31:03 +00001902//===----------------------------------------------------------------------===//
1903// Preprocessor Conditional Directive Handling.
1904//===----------------------------------------------------------------------===//
1905
Chris Lattner22eb9722006-06-18 05:43:12 +00001906/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001907/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1908/// if any tokens have been returned or pp-directives activated before this
1909/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001910///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001911void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1912 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001913 ++NumIf;
1914 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001915
Chris Lattner22eb9722006-06-18 05:43:12 +00001916 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001917 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001918
1919 // Error reading macro name? If so, diagnostic already issued.
1920 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001921 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001922
1923 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001924 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1925
1926 // If the start of a top-level #ifdef, inform MIOpt.
1927 if (!ReadAnyTokensBeforeDirective &&
1928 CurLexer->getConditionalStackDepth() == 0) {
1929 assert(isIfndef && "#ifdef shouldn't reach here");
1930 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1931 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001932
Chris Lattner063400e2006-10-14 19:54:15 +00001933 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1934 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001935
Chris Lattner81278c62006-10-14 19:03:49 +00001936 // If there is a macro, process it.
1937 if (MI) {
1938 // Mark it used.
1939 MI->setIsUsed(true);
1940
1941 // If this is the first use of a target-specific macro, warn about it.
1942 if (MI->isTargetSpecific()) {
1943 MI->setIsTargetSpecific(false); // Don't warn on second use.
1944 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1945 diag::port_target_macro_use);
1946 }
Chris Lattner063400e2006-10-14 19:54:15 +00001947 } else {
1948 // Use of a target-specific macro for some other target? If so, warn.
1949 if (MII->isOtherTargetMacro()) {
1950 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1951 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1952 diag::port_target_macro_use);
1953 }
Chris Lattner81278c62006-10-14 19:03:49 +00001954 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001955
Chris Lattner22eb9722006-06-18 05:43:12 +00001956 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001957 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001958 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001959 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001960 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001961 } else {
1962 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001963 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001964 /*Foundnonskip*/false,
1965 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001966 }
1967}
1968
1969/// HandleIfDirective - Implements the #if directive.
1970///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001971void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1972 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001973 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001974
Chris Lattner371ac8a2006-07-04 07:11:10 +00001975 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001976 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001977 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001978
1979 // Should we include the stuff contained by this directive?
1980 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001981 // If this condition is equivalent to #ifndef X, and if this is the first
1982 // directive seen, handle it for the multiple-include optimization.
1983 if (!ReadAnyTokensBeforeDirective &&
1984 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1985 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1986
Chris Lattner22eb9722006-06-18 05:43:12 +00001987 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001988 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001989 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001990 } else {
1991 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001992 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001993 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001994 }
1995}
1996
1997/// HandleEndifDirective - Implements the #endif directive.
1998///
Chris Lattnercb283342006-06-18 06:48:37 +00001999void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002000 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002001
Chris Lattner22eb9722006-06-18 05:43:12 +00002002 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002003 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002004
2005 PPConditionalInfo CondInfo;
2006 if (CurLexer->popConditionalLevel(CondInfo)) {
2007 // No conditionals on the stack: this is an #endif without an #if.
2008 return Diag(EndifToken, diag::err_pp_endif_without_if);
2009 }
2010
Chris Lattner371ac8a2006-07-04 07:11:10 +00002011 // If this the end of a top-level #endif, inform MIOpt.
2012 if (CurLexer->getConditionalStackDepth() == 0)
2013 CurLexer->MIOpt.ExitTopLevelConditional();
2014
Chris Lattner538d7f32006-07-20 04:31:52 +00002015 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002016 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002017}
2018
2019
Chris Lattnercb283342006-06-18 06:48:37 +00002020void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002021 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002022
Chris Lattner22eb9722006-06-18 05:43:12 +00002023 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002024 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002025
2026 PPConditionalInfo CI;
2027 if (CurLexer->popConditionalLevel(CI))
2028 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002029
2030 // If this is a top-level #else, inform the MIOpt.
2031 if (CurLexer->getConditionalStackDepth() == 0)
2032 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002033
2034 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002035 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002036
2037 // Finally, skip the rest of the contents of this block and return the first
2038 // token after it.
2039 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2040 /*FoundElse*/true);
2041}
2042
Chris Lattnercb283342006-06-18 06:48:37 +00002043void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002044 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002045
Chris Lattner22eb9722006-06-18 05:43:12 +00002046 // #elif directive in a non-skipping conditional... start skipping.
2047 // We don't care what the condition is, because we will always skip it (since
2048 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002049 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002050
2051 PPConditionalInfo CI;
2052 if (CurLexer->popConditionalLevel(CI))
2053 return Diag(ElifToken, diag::pp_err_elif_without_if);
2054
Chris Lattner371ac8a2006-07-04 07:11:10 +00002055 // If this is a top-level #elif, inform the MIOpt.
2056 if (CurLexer->getConditionalStackDepth() == 0)
2057 CurLexer->MIOpt.FoundTopLevelElse();
2058
Chris Lattner22eb9722006-06-18 05:43:12 +00002059 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002060 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002061
2062 // Finally, skip the rest of the contents of this block and return the first
2063 // token after it.
2064 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2065 /*FoundElse*/CI.FoundElse);
2066}
Chris Lattnerb8761832006-06-24 21:31:03 +00002067