blob: 636ed63fe3a1a1dc11fb5e9a53e70c9f958e9195 [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 Lattnerb352e3e2006-11-21 06:17:10 +000061
62 // Default to discarding comments.
63 KeepComments = false;
64 KeepMacroComments = false;
65
Chris Lattner22eb9722006-06-18 05:43:12 +000066 // Macro expansion is enabled.
67 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000068 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000069
Chris Lattner8ff71992006-07-06 05:17:39 +000070 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
71 // This gets unpoisoned where it is allowed.
72 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
73
Chris Lattnerb8761832006-06-24 21:31:03 +000074 // Initialize the pragma handlers.
75 PragmaHandlers = new PragmaNamespace(0);
76 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000077
78 // Initialize builtin macros like __LINE__ and friends.
79 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000080}
81
82Preprocessor::~Preprocessor() {
83 // Free any active lexers.
84 delete CurLexer;
85
Chris Lattner69772b02006-07-02 20:34:39 +000086 while (!IncludeMacroStack.empty()) {
87 delete IncludeMacroStack.back().TheLexer;
88 delete IncludeMacroStack.back().TheMacroExpander;
89 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000090 }
Chris Lattnerb8761832006-06-24 21:31:03 +000091
92 // Release pragma information.
93 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000094
95 // Delete the scratch buffer info.
96 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000097}
98
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000099PPCallbacks::~PPCallbacks() {
100}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000101
Chris Lattner22eb9722006-06-18 05:43:12 +0000102/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
103/// the specified LexerToken's location, translating the token's start
104/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattner36982e42007-05-16 17:49:37 +0000105void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
106 Diags.Report(Loc, DiagID);
107}
108
Chris Lattnercb283342006-06-18 06:48:37 +0000109void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000110 const std::string &Msg) {
Chris Lattner36982e42007-05-16 17:49:37 +0000111 Diags.Report(Loc, DiagID, &Msg, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000112}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000113
114void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
115 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
116 << getSpelling(Tok) << "'";
117
118 if (!DumpFlags) return;
119 std::cerr << "\t";
120 if (Tok.isAtStartOfLine())
121 std::cerr << " [StartOfLine]";
122 if (Tok.hasLeadingSpace())
123 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000124 if (Tok.isExpandDisabled())
125 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000126 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000127 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000128 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
129 << "']";
130 }
131}
132
133void Preprocessor::DumpMacro(const MacroInfo &MI) const {
134 std::cerr << "MACRO: ";
135 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
136 DumpToken(MI.getReplacementToken(i));
137 std::cerr << " ";
138 }
139 std::cerr << "\n";
140}
141
Chris Lattner22eb9722006-06-18 05:43:12 +0000142void Preprocessor::PrintStats() {
143 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000144 std::cerr << NumDirectives << " directives found:\n";
145 std::cerr << " " << NumDefined << " #define.\n";
146 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000147 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000148 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
149 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
150 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
151 std::cerr << " " << NumElse << " #else/#elif.\n";
152 std::cerr << " " << NumEndif << " #endif.\n";
153 std::cerr << " " << NumPragma << " #pragma.\n";
154 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
155
Chris Lattner78186052006-07-09 00:45:31 +0000156 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
157 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000158 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000159 std::cerr << (NumFastTokenPaste+NumTokenPaste)
160 << " token paste (##) operations performed, "
161 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000162}
163
164//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000165// Token Spelling
166//===----------------------------------------------------------------------===//
167
168
169/// getSpelling() - Return the 'spelling' of this token. The spelling of a
170/// token are the characters used to represent the token in the source file
171/// after trigraph expansion and escaped-newline folding. In particular, this
172/// wants to get the true, uncanonicalized, spelling of things like digraphs
173/// UCNs, etc.
174std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
175 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
176
177 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000178 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000179 if (!Tok.needsCleaning())
180 return std::string(TokStart, TokStart+Tok.getLength());
181
Chris Lattnerd01e2912006-06-18 16:22:51 +0000182 std::string Result;
183 Result.reserve(Tok.getLength());
184
Chris Lattneref9eae12006-07-04 22:33:12 +0000185 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000186 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
187 Ptr != End; ) {
188 unsigned CharSize;
189 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
190 Ptr += CharSize;
191 }
192 assert(Result.size() != unsigned(Tok.getLength()) &&
193 "NeedsCleaning flag set on something that didn't need cleaning!");
194 return Result;
195}
196
197/// getSpelling - This method is used to get the spelling of a token into a
198/// preallocated buffer, instead of as an std::string. The caller is required
199/// to allocate enough space for the token, which is guaranteed to be at least
200/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000201///
202/// Note that this method may do two possible things: it may either fill in
203/// the buffer specified with characters, or it may *change the input pointer*
204/// to point to a constant buffer with the data already in it (avoiding a
205/// copy). The caller is not allowed to modify the returned buffer pointer
206/// if an internal buffer is returned.
207unsigned Preprocessor::getSpelling(const LexerToken &Tok,
208 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000209 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
210
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000211 // If this token is an identifier, just return the string from the identifier
212 // table, which is very quick.
213 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
214 Buffer = II->getName();
215 return Tok.getLength();
216 }
217
218 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000219 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220
221 // If this token contains nothing interesting, return it directly.
222 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000223 Buffer = TokStart;
224 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225 }
226 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000227 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000228 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
229 Ptr != End; ) {
230 unsigned CharSize;
231 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
232 Ptr += CharSize;
233 }
234 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
235 "NeedsCleaning flag set on something that didn't need cleaning!");
236
237 return OutBuf-Buffer;
238}
239
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000240
241/// CreateString - Plop the specified string into a scratch buffer and return a
242/// location for it. If specified, the source location provides a source
243/// location for the token.
244SourceLocation Preprocessor::
245CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
246 if (SLoc.isValid())
247 return ScratchBuf->getToken(Buf, Len, SLoc);
248 return ScratchBuf->getToken(Buf, Len);
249}
250
251
Chris Lattnerd01e2912006-06-18 16:22:51 +0000252//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000253// Source File Location Methods.
254//===----------------------------------------------------------------------===//
255
Chris Lattner22eb9722006-06-18 05:43:12 +0000256/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
257/// return null on failure. isAngled indicates whether the file reference is
258/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000259const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
260 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000261 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000262 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000263 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000264 // If the header lookup mechanism may be relative to the current file, pass in
265 // info about where the current file is.
266 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000267 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000268 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000269 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000270 }
271
Chris Lattner63dd32b2006-10-20 04:42:40 +0000272 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000273 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000274 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000275 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
276 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000277 if (FE) return FE;
278
279 // Otherwise, see if this is a subframework header. If so, this is relative
280 // to one of the headers on the #include stack. Walk the list of the current
281 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000282 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000283 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000284 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
285 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000286 return FE;
287 }
288
289 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
290 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000291 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000292 CurFileEnt =
293 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000294 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
295 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000296 return FE;
297 }
298 }
299
300 // Otherwise, we really couldn't find the file.
301 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000302}
303
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000304/// isInPrimaryFile - Return true if we're in the top-level file, not in a
305/// #include.
306bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000307 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000308 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000309
Chris Lattner13044d92006-07-03 05:16:44 +0000310 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000311 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000312 if (IncludeMacroStack[i].TheLexer &&
313 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
314 return IncludeMacroStack[i].TheLexer->isMainFile();
315 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000316}
317
318/// getCurrentLexer - Return the current file lexer being lexed from. Note
319/// that this ignores any potentially active macro expansions and _Pragma
320/// expansions going on at the time.
321Lexer *Preprocessor::getCurrentFileLexer() const {
322 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
323
324 // Look for a stacked lexer.
325 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000326 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000327 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
328 return L;
329 }
330 return 0;
331}
332
333
Chris Lattner22eb9722006-06-18 05:43:12 +0000334/// EnterSourceFile - Add a source file to the top of the include stack and
335/// start lexing tokens from it instead of the current buffer. Return true
336/// on failure.
337void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000338 const DirectoryLookup *CurDir,
339 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000340 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000341 ++NumEnteredSourceFiles;
342
Chris Lattner69772b02006-07-02 20:34:39 +0000343 if (MaxIncludeStackDepth < IncludeMacroStack.size())
344 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000345
Chris Lattner739e7392007-04-29 07:12:06 +0000346 const MemoryBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000347 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000348 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000349 EnterSourceFileWithLexer(TheLexer, CurDir);
350}
Chris Lattner22eb9722006-06-18 05:43:12 +0000351
Chris Lattner69772b02006-07-02 20:34:39 +0000352/// EnterSourceFile - Add a source file to the top of the include stack and
353/// start lexing tokens from it instead of the current buffer.
354void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
355 const DirectoryLookup *CurDir) {
356
357 // Add the current lexer to the include stack.
358 if (CurLexer || CurMacroExpander)
359 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
360 CurMacroExpander));
361
362 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000363 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000364 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000365
366 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000367 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000368 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
369
370 // Get the file entry for the current file.
371 if (const FileEntry *FE =
372 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000373 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000374
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000375 Callbacks->FileChanged(SourceLocation(CurLexer->getCurFileID(), 0),
376 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000377 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000378}
379
Chris Lattner69772b02006-07-02 20:34:39 +0000380
381
Chris Lattner22eb9722006-06-18 05:43:12 +0000382/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000383/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000384void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000385 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
386 CurMacroExpander));
387 CurLexer = 0;
388 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000389
Chris Lattneree8760b2006-07-15 07:42:55 +0000390 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000391}
392
Chris Lattner7667d0d2006-07-16 18:16:58 +0000393/// EnterTokenStream - Add a "macro" context to the top of the include stack,
394/// which will cause the lexer to start returning the specified tokens. Note
395/// that these tokens will be re-macro-expanded when/if expansion is enabled.
396/// This method assumes that the specified stream of tokens has a permanent
397/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000398void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000399 // Save our current state.
400 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
401 CurMacroExpander));
402 CurLexer = 0;
403 CurDirLookup = 0;
404
405 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000406 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000407}
408
409/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
410/// lexer stack. This should only be used in situations where the current
411/// state of the top-of-stack lexer is known.
412void Preprocessor::RemoveTopOfLexerStack() {
413 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
414 delete CurLexer;
415 delete CurMacroExpander;
416 CurLexer = IncludeMacroStack.back().TheLexer;
417 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
418 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
419 IncludeMacroStack.pop_back();
420}
421
Chris Lattner22eb9722006-06-18 05:43:12 +0000422//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000423// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000424//===----------------------------------------------------------------------===//
425
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000426/// RegisterBuiltinMacro - Register the specified identifier in the identifier
427/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000428IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000429 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000430 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000431
432 // Mark it as being a macro that is builtin.
433 MacroInfo *MI = new MacroInfo(SourceLocation());
434 MI->setIsBuiltinMacro();
435 Id->setMacroInfo(MI);
436 return Id;
437}
438
439
Chris Lattner677757a2006-06-28 05:26:32 +0000440/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
441/// identifier table.
442void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000443 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000444 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000445 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
446 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000447 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000448
449 // GCC Extensions.
450 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
451 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000452 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000453}
454
Chris Lattnerc2395832006-07-09 00:57:04 +0000455/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
456/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000457static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
458 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000459 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
460
461 // If the token isn't an identifier, it's always literally expanded.
462 if (II == 0) return true;
463
464 // If the identifier is a macro, and if that macro is enabled, it may be
465 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000466 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
467 // Fast expanding "#define X X" is ok, because X would be disabled.
468 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000469 return false;
470
471 // If this is an object-like macro invocation, it is safe to trivially expand
472 // it.
473 if (MI->isObjectLike()) return true;
474
475 // If this is a function-like macro invocation, it's safe to trivially expand
476 // as long as the identifier is not a macro argument.
477 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
478 I != E; ++I)
479 if (*I == II)
480 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000481
Chris Lattnerc2395832006-07-09 00:57:04 +0000482 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000483}
484
Chris Lattnerc2395832006-07-09 00:57:04 +0000485
Chris Lattnerafe603f2006-07-11 04:02:46 +0000486/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
487/// lexed is a '('. If so, consume the token and return true, if not, this
488/// method should have no observable side-effect on the lexed tokens.
489bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000490 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000491 unsigned Val;
492 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000493 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000494 else
495 Val = CurMacroExpander->isNextTokenLParen();
496
497 if (Val == 2) {
498 // If we ran off the end of the lexer or macro expander, walk the include
499 // stack, looking for whatever will return the next token.
500 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
501 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
502 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000503 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000504 else
505 Val = Entry.TheMacroExpander->isNextTokenLParen();
506 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000507 }
508
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000509 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
510 // have found something that isn't a '(' or we found the end of the
511 // translation unit. In either case, return false.
512 if (Val != 1)
513 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000514
515 LexerToken Tok;
516 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000517 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
518 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000519}
Chris Lattner677757a2006-06-28 05:26:32 +0000520
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000521/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
522/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000523bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000524 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000525
526 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
527 if (MI->isBuiltinMacro()) {
528 ExpandBuiltinMacro(Identifier);
529 return false;
530 }
531
Chris Lattner81278c62006-10-14 19:03:49 +0000532 // If this is the first use of a target-specific macro, warn about it.
533 if (MI->isTargetSpecific()) {
534 MI->setIsTargetSpecific(false); // Don't warn on second use.
535 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
536 diag::port_target_macro_use);
537 }
538
Chris Lattneree8760b2006-07-15 07:42:55 +0000539 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000540 /// for each macro argument, the list of tokens that were provided to the
541 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000542 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000543
544 // If this is a function-like macro, read the arguments.
545 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000546 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
547 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000548 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000549 return true;
550
Chris Lattner78186052006-07-09 00:45:31 +0000551 // Remember that we are now parsing the arguments to a macro invocation.
552 // Preprocessor directives used inside macro arguments are not portable, and
553 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000554 InMacroArgs = true;
555 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000556
557 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000558 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000559
560 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000561 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000562
563 ++NumFnMacroExpanded;
564 } else {
565 ++NumMacroExpanded;
566 }
Chris Lattner13044d92006-07-03 05:16:44 +0000567
568 // Notice that this macro has been used.
569 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000570
571 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000572
573 // If this macro expands to no tokens, don't bother to push it onto the
574 // expansion stack, only to take it right back off.
575 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000576 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000577 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000578
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000579 // Ignore this macro use, just return the next token in the current
580 // buffer.
581 bool HadLeadingSpace = Identifier.hasLeadingSpace();
582 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
583
584 Lex(Identifier);
585
586 // If the identifier isn't on some OTHER line, inherit the leading
587 // whitespace/first-on-a-line property of this token. This handles
588 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
589 // empty.
590 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000591 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
592 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000593 }
594 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000595 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000596
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000597 } else if (MI->getNumTokens() == 1 &&
598 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000599 // Otherwise, if this macro expands into a single trivially-expanded
600 // token: expand it now. This handles common cases like
601 // "#define VAL 42".
602
603 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
604 // identifier to the expanded token.
605 bool isAtStartOfLine = Identifier.isAtStartOfLine();
606 bool hasLeadingSpace = Identifier.hasLeadingSpace();
607
608 // Remember where the token is instantiated.
609 SourceLocation InstantiateLoc = Identifier.getLocation();
610
611 // Replace the result token.
612 Identifier = MI->getReplacementToken(0);
613
614 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000615 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
616 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000617
618 // Update the tokens location to include both its logical and physical
619 // locations.
620 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000621 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000622 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000623
Chris Lattner6e4bf522006-07-27 06:59:25 +0000624 // If this is #define X X, we must mark the result as unexpandible.
625 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
626 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000627 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000628
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000629 // Since this is not an identifier token, it can't be macro expanded, so
630 // we're done.
631 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000632 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000633 }
634
Chris Lattner78186052006-07-09 00:45:31 +0000635 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000636 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000637
638 // Now that the macro is at the top of the include stack, ask the
639 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000640 Lex(Identifier);
641 return false;
642}
643
Chris Lattneree8760b2006-07-15 07:42:55 +0000644/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000645/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000646/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000647MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
648 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000649 // The number of fixed arguments to parse.
650 unsigned NumFixedArgsLeft = MI->getNumArgs();
651 bool isVariadic = MI->isVariadic();
652
Chris Lattner78186052006-07-09 00:45:31 +0000653 // Outer loop, while there are more arguments, keep reading them.
654 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000655 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000656 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000657
658 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000659 // argument is separated by an EOF token. Use a SmallVector so we can avoid
660 // heap allocations in the common case.
661 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000662
663 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000664 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000665 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
666 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000667
Chris Lattner78186052006-07-09 00:45:31 +0000668 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000669 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
670 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000671 LexUnexpandedToken(Tok);
672
673 if (Tok.getKind() == tok::eof) {
674 Diag(MacroName, diag::err_unterm_macro_invoc);
675 // Do not lose the EOF. Return it to the client.
676 MacroName = Tok;
677 return 0;
678 } else if (Tok.getKind() == tok::r_paren) {
679 // If we found the ) token, the macro arg list is done.
680 if (NumParens-- == 0)
681 break;
682 } else if (Tok.getKind() == tok::l_paren) {
683 ++NumParens;
684 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
685 // Comma ends this argument if there are more fixed arguments expected.
686 if (NumFixedArgsLeft)
687 break;
688
Chris Lattner2ada5d32006-07-15 07:51:24 +0000689 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000690 if (!isVariadic) {
691 // Emit the diagnostic at the macro name in case there is a missing ).
692 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000693 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000694 return 0;
695 }
696 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000697 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000698 // If this is a comment token in the argument list and we're just in
699 // -C mode (not -CC mode), discard the comment.
700 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000701 }
702
703 ArgTokens.push_back(Tok);
704 }
705
Chris Lattnera12dd152006-07-11 04:09:02 +0000706 // Empty arguments are standard in C99 and supported as an extension in
707 // other modes.
708 if (ArgTokens.empty() && !Features.C99)
709 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000710
Chris Lattner36b6e812006-07-21 06:38:30 +0000711 // Add a marker EOF token to the end of the token list for this argument.
712 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000713 EOFTok.startToken();
714 EOFTok.setKind(tok::eof);
715 EOFTok.setLocation(Tok.getLocation());
716 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000717 ArgTokens.push_back(EOFTok);
718 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000719 --NumFixedArgsLeft;
720 };
721
722 // Okay, we either found the r_paren. Check to see if we parsed too few
723 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000724 unsigned MinArgsExpected = MI->getNumArgs();
725
Chris Lattner775d8322006-07-29 04:39:41 +0000726 // See MacroArgs instance var for description of this.
727 bool isVarargsElided = false;
728
Chris Lattner2ada5d32006-07-15 07:51:24 +0000729 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000730 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000731 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000732 // Varargs where the named vararg parameter is missing: ok as extension.
733 // #define A(x, ...)
734 // A("blah")
735 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000736
737 // Remember this occurred if this is a C99 macro invocation with at least
738 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000739 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000740 } else if (MI->getNumArgs() == 1) {
741 // #define A(x)
742 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000743 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000744
745 // Empty arguments are standard in C99 and supported as an extension in
746 // other modes.
747 if (ArgTokens.empty() && !Features.C99)
748 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000749 } else {
750 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000751 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000752 return 0;
753 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000754
755 // Add a marker EOF token to the end of the token list for this argument.
756 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000757 Tok.startToken();
758 Tok.setKind(tok::eof);
759 Tok.setLocation(EndLoc);
760 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000761 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000762 }
763
Chris Lattner775d8322006-07-29 04:39:41 +0000764 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000765}
766
Chris Lattnerc673f902006-06-30 06:10:41 +0000767/// ComputeDATE_TIME - Compute the current time, enter it into the specified
768/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
769/// the identifier tokens inserted.
770static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000771 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000772 time_t TT = time(0);
773 struct tm *TM = localtime(&TT);
774
775 static const char * const Months[] = {
776 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
777 };
778
779 char TmpBuffer[100];
780 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
781 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000782 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000783
784 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000785 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000786}
787
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000788/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
789/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000790void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000791 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000792 IdentifierInfo *II = Tok.getIdentifierInfo();
793 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000794
795 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
796 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000797 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000798 return Handle_Pragma(Tok);
799
Chris Lattner78186052006-07-09 00:45:31 +0000800 ++NumBuiltinMacroExpanded;
801
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000802 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000803
804 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000805 Tok.setIdentifierInfo(0);
806 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000807
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000808 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000809 // __LINE__ expands to a simple numeric value.
810 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
811 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000812 Tok.setKind(tok::numeric_constant);
813 Tok.setLength(Length);
814 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000815 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000816 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000817 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000818 Diag(Tok, diag::ext_pp_base_file);
819 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
820 while (NextLoc.getFileID() != 0) {
821 Loc = NextLoc;
822 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
823 }
824 }
825
Chris Lattner0766e592006-07-03 01:07:01 +0000826 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
827 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000828 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000829 Tok.setKind(tok::string_literal);
830 Tok.setLength(FN.size());
831 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000832 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000833 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000834 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000835 Tok.setKind(tok::string_literal);
836 Tok.setLength(strlen("\"Mmm dd yyyy\""));
837 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000838 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000839 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000840 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000841 Tok.setKind(tok::string_literal);
842 Tok.setLength(strlen("\"hh:mm:ss\""));
843 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000844 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000845 Diag(Tok, diag::ext_pp_include_level);
846
847 // Compute the include depth of this token.
848 unsigned Depth = 0;
849 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
850 for (; Loc.getFileID() != 0; ++Depth)
851 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
852
853 // __INCLUDE_LEVEL__ expands to a simple numeric value.
854 sprintf(TmpBuffer, "%u", Depth);
855 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000856 Tok.setKind(tok::numeric_constant);
857 Tok.setLength(Length);
858 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000859 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000860 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
861 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
862 Diag(Tok, diag::ext_pp_timestamp);
863
864 // Get the file that we are lexing out of. If we're currently lexing from
865 // a macro, dig into the include stack.
866 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000867 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000868
869 if (TheLexer)
870 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
871
872 // If this file is older than the file it depends on, emit a diagnostic.
873 const char *Result;
874 if (CurFile) {
875 time_t TT = CurFile->getModificationTime();
876 struct tm *TM = localtime(&TT);
877 Result = asctime(TM);
878 } else {
879 Result = "??? ??? ?? ??:??:?? ????\n";
880 }
881 TmpBuffer[0] = '"';
882 strcpy(TmpBuffer+1, Result);
883 unsigned Len = strlen(TmpBuffer);
884 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000885 Tok.setKind(tok::string_literal);
886 Tok.setLength(Len);
887 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000888 } else {
889 assert(0 && "Unknown identifier!");
890 }
891}
Chris Lattner677757a2006-06-28 05:26:32 +0000892
893//===----------------------------------------------------------------------===//
894// Lexer Event Handling.
895//===----------------------------------------------------------------------===//
896
Chris Lattnercefc7682006-07-08 08:28:12 +0000897/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
898/// identifier information for the token and install it into the token.
899IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
900 const char *BufPtr) {
901 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
902 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
903
904 // Look up this token, see if it is a macro, or if it is a language keyword.
905 IdentifierInfo *II;
906 if (BufPtr && !Identifier.needsCleaning()) {
907 // No cleaning needed, just use the characters from the lexed buffer.
908 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
909 } else {
910 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
911 const char *TmpBuf = (char*)alloca(Identifier.getLength());
912 unsigned Size = getSpelling(Identifier, TmpBuf);
913 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
914 }
Chris Lattner8c204872006-10-14 05:19:21 +0000915 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000916 return II;
917}
918
919
Chris Lattner677757a2006-06-28 05:26:32 +0000920/// HandleIdentifier - This callback is invoked when the lexer reads an
921/// identifier. This callback looks up the identifier in the map and/or
922/// potentially macro expands it or turns it into a named token (like 'for').
923void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000924 assert(Identifier.getIdentifierInfo() &&
925 "Can't handle identifiers without identifier info!");
926
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000927 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000928
929 // If this identifier was poisoned, and if it was not produced from a macro
930 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000931 if (II.isPoisoned() && CurLexer) {
932 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
933 Diag(Identifier, diag::err_pp_used_poisoned_id);
934 else
935 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
936 }
Chris Lattner677757a2006-06-28 05:26:32 +0000937
Chris Lattner78186052006-07-09 00:45:31 +0000938 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000939 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000940 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
941 if (MI->isEnabled()) {
942 if (!HandleMacroExpandedIdentifier(Identifier, MI))
943 return;
944 } else {
945 // C99 6.10.3.4p2 says that a disabled macro may never again be
946 // expanded, even if it's in a context where it could be expanded in the
947 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000948 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000949 }
950 }
Chris Lattner063400e2006-10-14 19:54:15 +0000951 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
952 // If this identifier is a macro on some other target, emit a diagnostic.
953 // This diagnosic is only emitted when macro expansion is enabled, because
954 // the macro would not have been expanded for the other target either.
955 II.setIsOtherTargetMacro(false); // Don't warn on second use.
956 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
957 diag::port_target_macro_use);
958
959 }
Chris Lattner677757a2006-06-28 05:26:32 +0000960
Chris Lattner5b9f4892006-11-21 17:23:33 +0000961 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
962 // then we act as if it is the actual operator and not the textual
963 // representation of it.
964 if (II.isCPlusPlusOperatorKeyword())
965 Identifier.setIdentifierInfo(0);
966
Chris Lattner677757a2006-06-28 05:26:32 +0000967 // Change the kind of this identifier to the appropriate token kind, e.g.
968 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000969 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000970
971 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000972 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000973}
974
Chris Lattner22eb9722006-06-18 05:43:12 +0000975/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
976/// the current file. This either returns the EOF token or pops a level off
977/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000978bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000979 assert(!CurMacroExpander &&
980 "Ending a file when currently in a macro!");
981
Chris Lattner371ac8a2006-07-04 07:11:10 +0000982 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000983 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000984 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000985 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000986 // Okay, this has a controlling macro, remember in PerFileInfo.
987 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000988 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
989 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000990 }
991 }
992
Chris Lattner22eb9722006-06-18 05:43:12 +0000993 // If this is a #include'd file, pop it off the include stack and continue
994 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000995 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000996 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000997 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +0000998
999 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001000 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001001 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1002
1003 // Get the file entry for the current file.
1004 if (const FileEntry *FE =
1005 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001006 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001007
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001008 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1009 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001010 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001011
1012 // Client should lex another token.
1013 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001014 }
1015
Chris Lattner8c204872006-10-14 05:19:21 +00001016 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001017 CurLexer->BufferPtr = CurLexer->BufferEnd;
1018 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001019 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001020
1021 // We're done with the #included file.
1022 delete CurLexer;
1023 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001024
Chris Lattner03f83482006-07-10 06:16:26 +00001025 // This is the end of the top-level file. If the diag::pp_macro_not_used
1026 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1027 // have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001028 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1029 for (IdentifierTable::iterator I = Identifiers.begin(),
1030 E = Identifiers.end(); I != E; ++I) {
1031 const IdentifierInfo &II = I->getValue();
1032 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1033 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1034 }
1035 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001036
1037 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001038}
1039
1040/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001041/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001042bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001043 assert(CurMacroExpander && !CurLexer &&
1044 "Ending a macro when currently in a #include file!");
1045
Chris Lattner22eb9722006-06-18 05:43:12 +00001046 delete CurMacroExpander;
1047
Chris Lattner69772b02006-07-02 20:34:39 +00001048 // Handle this like a #include file being popped off the stack.
1049 CurMacroExpander = 0;
1050 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001051}
1052
1053
1054//===----------------------------------------------------------------------===//
1055// Utility Methods for Preprocessor Directive Handling.
1056//===----------------------------------------------------------------------===//
1057
1058/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1059/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001060void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001061 LexerToken Tmp;
1062 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001063 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001064 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001065}
1066
Chris Lattner652c1692006-11-21 23:47:30 +00001067/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1068static bool isCXXNamedOperator(const std::string &Spelling) {
1069 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1070 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1071 Spelling == "or" || Spelling == "xor";
1072}
1073
Chris Lattner22eb9722006-06-18 05:43:12 +00001074/// ReadMacroName - Lex and validate a macro name, which occurs after a
1075/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001076/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1077/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001078/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001079void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001080 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001081 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001082
1083 // Missing macro name?
1084 if (MacroNameTok.getKind() == tok::eom)
1085 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1086
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001087 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1088 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001089 std::string Spelling = getSpelling(MacroNameTok);
1090 if (isCXXNamedOperator(Spelling))
1091 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1092 // except for their spellings.
1093 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1094 else
1095 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001096 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001097 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001098 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001099 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001100 } else if (isDefineUndef && II->getMacroInfo() &&
1101 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001102 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001103 if (isDefineUndef == 1)
1104 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1105 else
1106 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001107 } else {
1108 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001109 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001110 }
1111
Chris Lattner22eb9722006-06-18 05:43:12 +00001112 // Invalid macro name, read and discard the rest of the line. Then set the
1113 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001114 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001115 return DiscardUntilEndOfDirective();
1116}
1117
1118/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1119/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001120void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001121 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001122 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001123 // There should be no tokens after the directive, but we allow them as an
1124 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001125 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1126 Lex(Tmp);
1127
Chris Lattner22eb9722006-06-18 05:43:12 +00001128 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001129 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1130 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001131 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001132}
1133
1134
1135
1136/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1137/// decided that the subsequent tokens are in the #if'd out portion of the
1138/// file. Lex the rest of the file, until we see an #endif. If
1139/// FoundNonSkipPortion is true, then we have already emitted code for part of
1140/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1141/// is true, then #else directives are ok, if not, then we have already seen one
1142/// so a #else directive is a duplicate. When this returns, the caller can lex
1143/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001144void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001145 bool FoundNonSkipPortion,
1146 bool FoundElse) {
1147 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001148 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001149 "Lexing a macro, not a file?");
1150
1151 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1152 FoundNonSkipPortion, FoundElse);
1153
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001154 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1155 // disabling warnings, etc.
1156 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001157 LexerToken Tok;
1158 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001159 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001160
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001161 // If this is the end of the buffer, we have an error.
1162 if (Tok.getKind() == tok::eof) {
1163 // Emit errors for each unterminated conditional on the stack, including
1164 // the current one.
1165 while (!CurLexer->ConditionalStack.empty()) {
1166 Diag(CurLexer->ConditionalStack.back().IfLoc,
1167 diag::err_pp_unterminated_conditional);
1168 CurLexer->ConditionalStack.pop_back();
1169 }
1170
1171 // Just return and let the caller lex after this #include.
1172 break;
1173 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001174
1175 // If this token is not a preprocessor directive, just skip it.
1176 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1177 continue;
1178
1179 // We just parsed a # character at the start of a line, so we're in
1180 // directive mode. Tell the lexer this so any newlines we see will be
1181 // converted into an EOM token (this terminates the macro).
1182 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001183 CurLexer->KeepCommentMode = false;
1184
Chris Lattner22eb9722006-06-18 05:43:12 +00001185
1186 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001187 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001188
1189 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1190 // something bogus), skip it.
1191 if (Tok.getKind() != tok::identifier) {
1192 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001193 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001194 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001195 continue;
1196 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001197
Chris Lattner22eb9722006-06-18 05:43:12 +00001198 // If the first letter isn't i or e, it isn't intesting to us. We know that
1199 // this is safe in the face of spelling differences, because there is no way
1200 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001201 // allows us to avoid looking up the identifier info for #define/#undef and
1202 // other common directives.
1203 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1204 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001205 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1206 FirstChar != 'i' && FirstChar != 'e') {
1207 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001208 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001209 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001210 continue;
1211 }
1212
Chris Lattnere60165f2006-06-22 06:36:29 +00001213 // Get the identifier name without trigraphs or embedded newlines. Note
1214 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1215 // when skipping.
1216 // TODO: could do this with zero copies in the no-clean case by using
1217 // strncmp below.
1218 char Directive[20];
1219 unsigned IdLen;
1220 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1221 IdLen = Tok.getLength();
1222 memcpy(Directive, RawCharData, IdLen);
1223 Directive[IdLen] = 0;
1224 } else {
1225 std::string DirectiveStr = getSpelling(Tok);
1226 IdLen = DirectiveStr.size();
1227 if (IdLen >= 20) {
1228 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001229 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001230 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001231 continue;
1232 }
1233 memcpy(Directive, &DirectiveStr[0], IdLen);
1234 Directive[IdLen] = 0;
1235 }
1236
Chris Lattner22eb9722006-06-18 05:43:12 +00001237 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001238 if ((IdLen == 2) || // "if"
1239 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1240 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001241 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1242 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001243 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001244 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001245 /*foundnonskip*/false,
1246 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001247 }
1248 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001249 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001250 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001251 PPConditionalInfo CondInfo;
1252 CondInfo.WasSkipping = true; // Silence bogus warning.
1253 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001254 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001255 assert(!InCond && "Can't be skipping if not in a conditional!");
1256
1257 // If we popped the outermost skipping block, we're done skipping!
1258 if (!CondInfo.WasSkipping)
1259 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001260 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001261 // #else directive in a skipping conditional. If not in some other
1262 // skipping conditional, and if #else hasn't already been seen, enter it
1263 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001264 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001265 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1266
1267 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001268 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001269
1270 // Note that we've seen a #else in this conditional.
1271 CondInfo.FoundElse = true;
1272
1273 // If the conditional is at the top level, and the #if block wasn't
1274 // entered, enter the #else block now.
1275 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1276 CondInfo.FoundNonSkip = true;
1277 break;
1278 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001279 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001280 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1281
1282 bool ShouldEnter;
1283 // If this is in a skipping block or if we're already handled this #if
1284 // block, don't bother parsing the condition.
1285 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001286 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001287 ShouldEnter = false;
1288 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001289 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001290 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001291 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1292 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001293 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001294 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001295 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 }
1297
1298 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001299 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001300
1301 // If this condition is true, enter it!
1302 if (ShouldEnter) {
1303 CondInfo.FoundNonSkip = true;
1304 break;
1305 }
1306 }
1307 }
1308
1309 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001310 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001311 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001312 }
1313
1314 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1315 // of the file, just stop skipping and return to lexing whatever came after
1316 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001317 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001318}
1319
1320//===----------------------------------------------------------------------===//
1321// Preprocessor Directive Handling.
1322//===----------------------------------------------------------------------===//
1323
1324/// HandleDirective - This callback is invoked when the lexer sees a # token
1325/// at the start of a line. This consumes the directive, modifies the
1326/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1327/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001328void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001329 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001330
1331 // We just parsed a # character at the start of a line, so we're in directive
1332 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001333 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001334 CurLexer->ParsingPreprocessorDirective = true;
1335
1336 ++NumDirectives;
1337
Chris Lattner371ac8a2006-07-04 07:11:10 +00001338 // We are about to read a token. For the multiple-include optimization FA to
1339 // work, we have to remember if we had read any tokens *before* this
1340 // pp-directive.
1341 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1342
Chris Lattner78186052006-07-09 00:45:31 +00001343 // Read the next token, the directive flavor. This isn't expanded due to
1344 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001345 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001346
Chris Lattner78186052006-07-09 00:45:31 +00001347 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1348 // #define A(x) #x
1349 // A(abc
1350 // #warning blah
1351 // def)
1352 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001353 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001354 Diag(Result, diag::ext_embedded_directive);
1355
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001356TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001357 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001358 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001359 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001360 case tok::comment:
1361 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1362 LexUnexpandedToken(Result);
1363 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001364
Chris Lattner22eb9722006-06-18 05:43:12 +00001365 case tok::numeric_constant:
1366 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001367 DiscardUntilEndOfDirective();
1368 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001369 default:
1370 IdentifierInfo *II = Result.getIdentifierInfo();
1371 if (II == 0) break; // Not an identifier.
1372
1373 // Ask what the preprocessor keyword ID is.
1374 switch (II->getPPKeywordID()) {
1375 default: break;
1376 // C99 6.10.1 - Conditional Inclusion.
1377 case tok::pp_if:
1378 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1379 case tok::pp_ifdef:
1380 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1381 case tok::pp_ifndef:
1382 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1383 case tok::pp_elif:
1384 return HandleElifDirective(Result);
1385 case tok::pp_else:
1386 return HandleElseDirective(Result);
1387 case tok::pp_endif:
1388 return HandleEndifDirective(Result);
1389
1390 // C99 6.10.2 - Source File Inclusion.
1391 case tok::pp_include:
1392 return HandleIncludeDirective(Result); // Handle #include.
1393
1394 // C99 6.10.3 - Macro Replacement.
1395 case tok::pp_define:
1396 return HandleDefineDirective(Result, false);
1397 case tok::pp_undef:
1398 return HandleUndefDirective(Result);
1399
1400 // C99 6.10.4 - Line Control.
1401 case tok::pp_line:
1402 // FIXME: implement #line
1403 DiscardUntilEndOfDirective();
1404 return;
1405
1406 // C99 6.10.5 - Error Directive.
1407 case tok::pp_error:
1408 return HandleUserDiagnosticDirective(Result, false);
1409
1410 // C99 6.10.6 - Pragma Directive.
1411 case tok::pp_pragma:
1412 return HandlePragmaDirective();
1413
1414 // GNU Extensions.
1415 case tok::pp_import:
1416 return HandleImportDirective(Result);
1417 case tok::pp_include_next:
1418 return HandleIncludeNextDirective(Result);
1419
1420 case tok::pp_warning:
1421 Diag(Result, diag::ext_pp_warning_directive);
1422 return HandleUserDiagnosticDirective(Result, true);
1423 case tok::pp_ident:
1424 return HandleIdentSCCSDirective(Result);
1425 case tok::pp_sccs:
1426 return HandleIdentSCCSDirective(Result);
1427 case tok::pp_assert:
1428 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001429 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001430 case tok::pp_unassert:
1431 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001432 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001433
1434 // clang extensions.
1435 case tok::pp_define_target:
1436 return HandleDefineDirective(Result, true);
1437 case tok::pp_define_other_target:
1438 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001439 }
1440 break;
1441 }
1442
1443 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001444 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001445
1446 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001447 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001448
1449 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001450}
1451
Chris Lattner01d66cc2006-07-03 22:16:27 +00001452void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001453 bool isWarning) {
1454 // Read the rest of the line raw. We do this because we don't want macros
1455 // to be expanded and we don't require that the tokens be valid preprocessing
1456 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1457 // collapse multiple consequtive white space between tokens, but this isn't
1458 // specified by the standard.
1459 std::string Message = CurLexer->ReadToEndOfLine();
1460
1461 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001462 return Diag(Tok, DiagID, Message);
1463}
1464
1465/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1466///
1467void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001468 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001469 Diag(Tok, diag::ext_pp_ident_directive);
1470
Chris Lattner371ac8a2006-07-04 07:11:10 +00001471 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001472 LexerToken StrTok;
1473 Lex(StrTok);
1474
1475 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001476 if (StrTok.getKind() != tok::string_literal &&
1477 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001478 return Diag(StrTok, diag::err_pp_malformed_ident);
1479
1480 // Verify that there is nothing after the string, other than EOM.
1481 CheckEndOfDirective("#ident");
1482
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001483 if (Callbacks)
1484 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001485}
1486
Chris Lattnerb8761832006-06-24 21:31:03 +00001487//===----------------------------------------------------------------------===//
1488// Preprocessor Include Directive Handling.
1489//===----------------------------------------------------------------------===//
1490
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001491/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1492/// checked and spelled filename, e.g. as an operand of #include. This returns
1493/// true if the input filename was in <>'s or false if it were in ""'s. The
1494/// caller is expected to provide a buffer that is large enough to hold the
1495/// spelling of the filename, but is also expected to handle the case when
1496/// this method decides to use a different buffer.
1497bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1498 const char *&BufStart,
1499 const char *&BufEnd) {
1500 // Get the text form of the filename.
1501 unsigned Len = getSpelling(FilenameTok, BufStart);
1502 BufEnd = BufStart+Len;
1503 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1504
1505 // Make sure the filename is <x> or "x".
1506 bool isAngled;
1507 if (BufStart[0] == '<') {
1508 if (BufEnd[-1] != '>') {
1509 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1510 BufStart = 0;
1511 return true;
1512 }
1513 isAngled = true;
1514 } else if (BufStart[0] == '"') {
1515 if (BufEnd[-1] != '"') {
1516 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1517 BufStart = 0;
1518 return true;
1519 }
1520 isAngled = false;
1521 } else {
1522 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1523 BufStart = 0;
1524 return true;
1525 }
1526
1527 // Diagnose #include "" as invalid.
1528 if (BufEnd-BufStart <= 2) {
1529 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1530 BufStart = 0;
1531 return "";
1532 }
1533
1534 // Skip the brackets.
1535 ++BufStart;
1536 --BufEnd;
1537 return isAngled;
1538}
1539
Chris Lattner22eb9722006-06-18 05:43:12 +00001540/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1541/// file to be included from the lexer, then include it! This is a common
1542/// routine with functionality shared between #include, #include_next and
1543/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001544void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001545 const DirectoryLookup *LookupFrom,
1546 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001547
Chris Lattner22eb9722006-06-18 05:43:12 +00001548 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001549 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001550
1551 // If the token kind is EOM, the error has already been diagnosed.
1552 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001553 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001554
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001555 // Reserve a buffer to get the spelling.
1556 SmallVector<char, 128> FilenameBuffer;
1557 FilenameBuffer.resize(FilenameTok.getLength());
1558
1559 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1560 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1561 FilenameStart, FilenameEnd);
1562 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1563 // error.
1564 if (FilenameStart == 0)
1565 return;
1566
Chris Lattner269c2322006-06-25 06:23:00 +00001567 // Verify that there is nothing after the filename, other than EOM. Use the
1568 // preprocessor to lex this in case lexing the filename entered a macro.
1569 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001570
1571 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001572 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001573 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1574
Chris Lattner22eb9722006-06-18 05:43:12 +00001575 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001576 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001577 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001578 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001579 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001580 return Diag(FilenameTok, diag::err_pp_file_not_found,
1581 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001582
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001583 // Ask HeaderInfo if we should enter this #include file.
1584 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1585 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001586 return;
1587 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001588
1589 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001590 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001591 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001592 return Diag(FilenameTok, diag::err_pp_file_not_found,
1593 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001594
1595 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001596 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001597}
1598
1599/// HandleIncludeNextDirective - Implements #include_next.
1600///
Chris Lattnercb283342006-06-18 06:48:37 +00001601void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1602 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001603
1604 // #include_next is like #include, except that we start searching after
1605 // the current found directory. If we can't do this, issue a
1606 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001607 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001608 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001609 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001610 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001611 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001612 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001613 } else {
1614 // Start looking up in the next directory.
1615 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001616 }
1617
1618 return HandleIncludeDirective(IncludeNextTok, Lookup);
1619}
1620
1621/// HandleImportDirective - Implements #import.
1622///
Chris Lattnercb283342006-06-18 06:48:37 +00001623void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1624 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001625
1626 return HandleIncludeDirective(ImportTok, 0, true);
1627}
1628
Chris Lattnerb8761832006-06-24 21:31:03 +00001629//===----------------------------------------------------------------------===//
1630// Preprocessor Macro Directive Handling.
1631//===----------------------------------------------------------------------===//
1632
Chris Lattnercefc7682006-07-08 08:28:12 +00001633/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1634/// definition has just been read. Lex the rest of the arguments and the
1635/// closing ), updating MI with what we learn. Return true if an error occurs
1636/// parsing the arg list.
1637bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1638 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001639 while (1) {
1640 LexUnexpandedToken(Tok);
1641 switch (Tok.getKind()) {
1642 case tok::r_paren:
1643 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001644 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001645 // Otherwise we have #define FOO(A,)
1646 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1647 return true;
1648 case tok::ellipsis: // #define X(... -> C99 varargs
1649 // Warn if use of C99 feature in non-C99 mode.
1650 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1651
1652 // Lex the token after the identifier.
1653 LexUnexpandedToken(Tok);
1654 if (Tok.getKind() != tok::r_paren) {
1655 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1656 return true;
1657 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001658 // Add the __VA_ARGS__ identifier as an argument.
1659 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001660 MI->setIsC99Varargs();
1661 return false;
1662 case tok::eom: // #define X(
1663 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1664 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001665 default:
1666 // Handle keywords and identifiers here to accept things like
1667 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001668 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001669 if (II == 0) {
1670 // #define X(1
1671 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1672 return true;
1673 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001674
1675 // If this is already used as an argument, it is used multiple times (e.g.
1676 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001677 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001678 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1679 return true;
1680 }
1681
1682 // Add the argument to the macro info.
1683 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001684
1685 // Lex the token after the identifier.
1686 LexUnexpandedToken(Tok);
1687
1688 switch (Tok.getKind()) {
1689 default: // #define X(A B
1690 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1691 return true;
1692 case tok::r_paren: // #define X(A)
1693 return false;
1694 case tok::comma: // #define X(A,
1695 break;
1696 case tok::ellipsis: // #define X(A... -> GCC extension
1697 // Diagnose extension.
1698 Diag(Tok, diag::ext_named_variadic_macro);
1699
1700 // Lex the token after the identifier.
1701 LexUnexpandedToken(Tok);
1702 if (Tok.getKind() != tok::r_paren) {
1703 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1704 return true;
1705 }
1706
1707 MI->setIsGNUVarargs();
1708 return false;
1709 }
1710 }
1711 }
1712}
1713
Chris Lattner22eb9722006-06-18 05:43:12 +00001714/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001715/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1716/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001717///
Chris Lattner81278c62006-10-14 19:03:49 +00001718void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1719 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001720 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001721
Chris Lattner22eb9722006-06-18 05:43:12 +00001722 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001723 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001724
1725 // Error reading macro name? If so, diagnostic already issued.
1726 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001727 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001728
Chris Lattner457fc152006-07-29 06:30:25 +00001729 // If we are supposed to keep comments in #defines, reenable comment saving
1730 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001731 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001732
Chris Lattner063400e2006-10-14 19:54:15 +00001733 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001734 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001735 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001736
Chris Lattner063400e2006-10-14 19:54:15 +00001737 // If the identifier is an 'other target' macro, clear this bit.
1738 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1739
1740
Chris Lattner22eb9722006-06-18 05:43:12 +00001741 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001742 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001743
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001744 // If this is a function-like macro definition, parse the argument list,
1745 // marking each of the identifiers as being used as macro arguments. Also,
1746 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001747 if (Tok.getKind() == tok::eom) {
1748 // If there is no body to this macro, we have no special handling here.
1749 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001750 // This is a function-like macro definition. Read the argument list.
1751 MI->setIsFunctionLike();
1752 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001753 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001754 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001755 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001756 if (CurLexer->ParsingPreprocessorDirective)
1757 DiscardUntilEndOfDirective();
1758 return;
1759 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001760
Chris Lattner815a1f92006-07-08 20:48:04 +00001761 // Read the first token after the arg list for down below.
1762 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001763 } else if (!Tok.hasLeadingSpace()) {
1764 // C99 requires whitespace between the macro definition and the body. Emit
1765 // a diagnostic for something like "#define X+".
1766 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001767 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001768 } else {
1769 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1770 // one in some cases!
1771 }
1772 } else {
1773 // This is a normal token with leading space. Clear the leading space
1774 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001775 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001776 }
1777
Chris Lattner7e374832006-07-29 03:46:57 +00001778 // If this is a definition of a variadic C99 function-like macro, not using
1779 // the GNU named varargs extension, enabled __VA_ARGS__.
1780
1781 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1782 // This gets unpoisoned where it is allowed.
1783 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1784 if (MI->isC99Varargs())
1785 Ident__VA_ARGS__->setIsPoisoned(false);
1786
Chris Lattner22eb9722006-06-18 05:43:12 +00001787 // Read the rest of the macro body.
1788 while (Tok.getKind() != tok::eom) {
1789 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001790
1791 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001792 // parameters in function-like macro expansions.
1793 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001794 // Get the next token of the macro.
1795 LexUnexpandedToken(Tok);
1796 continue;
1797 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001798
Chris Lattner815a1f92006-07-08 20:48:04 +00001799 // Get the next token of the macro.
1800 LexUnexpandedToken(Tok);
1801
1802 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001803 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001804 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001805 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001806 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001807
1808 // Disable __VA_ARGS__ again.
1809 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001810 return;
1811 }
1812
1813 // Things look ok, add the param name token to the macro.
1814 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001815
Chris Lattner22eb9722006-06-18 05:43:12 +00001816 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001817 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001818 }
Chris Lattner7e374832006-07-29 03:46:57 +00001819
1820 // Disable __VA_ARGS__ again.
1821 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001822
Chris Lattnerbff18d52006-07-06 04:49:18 +00001823 // Check that there is no paste (##) operator at the begining or end of the
1824 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001825 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001826 if (NumTokens != 0) {
1827 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001828 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001829 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001830 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001831 }
1832 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001833 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001834 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001835 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001836 }
1837 }
1838
Chris Lattner13044d92006-07-03 05:16:44 +00001839 // If this is the primary source file, remember that this macro hasn't been
1840 // used yet.
1841 if (isInPrimaryFile())
1842 MI->setIsUsed(false);
1843
Chris Lattner22eb9722006-06-18 05:43:12 +00001844 // Finally, if this identifier already had a macro defined for it, verify that
1845 // the macro bodies are identical and free the old definition.
1846 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001847 if (!OtherMI->isUsed())
1848 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1849
Chris Lattner22eb9722006-06-18 05:43:12 +00001850 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001851 // must be the same. C99 6.10.3.2.
1852 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001853 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1854 MacroNameTok.getIdentifierInfo()->getName());
1855 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1856 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001857 delete OtherMI;
1858 }
1859
1860 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001861}
1862
Chris Lattner063400e2006-10-14 19:54:15 +00001863/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1864void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1865 LexerToken MacroNameTok;
1866 ReadMacroName(MacroNameTok, 1);
1867
1868 // Error reading macro name? If so, diagnostic already issued.
1869 if (MacroNameTok.getKind() == tok::eom)
1870 return;
1871
1872 // Check to see if this is the last token on the #undef line.
1873 CheckEndOfDirective("#define_other_target");
1874
1875 // If there is already a macro defined by this name, turn it into a
1876 // target-specific define.
1877 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1878 MI->setIsTargetSpecific(true);
1879 return;
1880 }
1881
1882 // Mark the identifier as being a macro on some other target.
1883 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1884}
1885
Chris Lattner22eb9722006-06-18 05:43:12 +00001886
1887/// HandleUndefDirective - Implements #undef.
1888///
Chris Lattnercb283342006-06-18 06:48:37 +00001889void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001890 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001891
Chris Lattner22eb9722006-06-18 05:43:12 +00001892 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001893 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001894
1895 // Error reading macro name? If so, diagnostic already issued.
1896 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001897 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001898
1899 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001900 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001901
1902 // Okay, we finally have a valid identifier to undef.
1903 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1904
Chris Lattner063400e2006-10-14 19:54:15 +00001905 // #undef untaints an identifier if it were marked by define_other_target.
1906 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1907
Chris Lattner22eb9722006-06-18 05:43:12 +00001908 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001909 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001910
Chris Lattner13044d92006-07-03 05:16:44 +00001911 if (!MI->isUsed())
1912 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001913
1914 // Free macro definition.
1915 delete MI;
1916 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001917}
1918
1919
Chris Lattnerb8761832006-06-24 21:31:03 +00001920//===----------------------------------------------------------------------===//
1921// Preprocessor Conditional Directive Handling.
1922//===----------------------------------------------------------------------===//
1923
Chris Lattner22eb9722006-06-18 05:43:12 +00001924/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001925/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1926/// if any tokens have been returned or pp-directives activated before this
1927/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001928///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001929void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1930 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001931 ++NumIf;
1932 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001933
Chris Lattner22eb9722006-06-18 05:43:12 +00001934 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001935 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001936
1937 // Error reading macro name? If so, diagnostic already issued.
1938 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001939 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001940
1941 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001942 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1943
1944 // If the start of a top-level #ifdef, inform MIOpt.
1945 if (!ReadAnyTokensBeforeDirective &&
1946 CurLexer->getConditionalStackDepth() == 0) {
1947 assert(isIfndef && "#ifdef shouldn't reach here");
1948 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1949 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001950
Chris Lattner063400e2006-10-14 19:54:15 +00001951 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1952 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001953
Chris Lattner81278c62006-10-14 19:03:49 +00001954 // If there is a macro, process it.
1955 if (MI) {
1956 // Mark it used.
1957 MI->setIsUsed(true);
1958
1959 // If this is the first use of a target-specific macro, warn about it.
1960 if (MI->isTargetSpecific()) {
1961 MI->setIsTargetSpecific(false); // Don't warn on second use.
1962 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1963 diag::port_target_macro_use);
1964 }
Chris Lattner063400e2006-10-14 19:54:15 +00001965 } else {
1966 // Use of a target-specific macro for some other target? If so, warn.
1967 if (MII->isOtherTargetMacro()) {
1968 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1969 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1970 diag::port_target_macro_use);
1971 }
Chris Lattner81278c62006-10-14 19:03:49 +00001972 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001973
Chris Lattner22eb9722006-06-18 05:43:12 +00001974 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001975 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001976 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001977 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001978 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001979 } else {
1980 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001981 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001982 /*Foundnonskip*/false,
1983 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001984 }
1985}
1986
1987/// HandleIfDirective - Implements the #if directive.
1988///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001989void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1990 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001991 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001992
Chris Lattner371ac8a2006-07-04 07:11:10 +00001993 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001994 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001995 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001996
1997 // Should we include the stuff contained by this directive?
1998 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001999 // If this condition is equivalent to #ifndef X, and if this is the first
2000 // directive seen, handle it for the multiple-include optimization.
2001 if (!ReadAnyTokensBeforeDirective &&
2002 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2003 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2004
Chris Lattner22eb9722006-06-18 05:43:12 +00002005 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002006 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002007 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002008 } else {
2009 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002010 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002011 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002012 }
2013}
2014
2015/// HandleEndifDirective - Implements the #endif directive.
2016///
Chris Lattnercb283342006-06-18 06:48:37 +00002017void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002018 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002019
Chris Lattner22eb9722006-06-18 05:43:12 +00002020 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002021 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002022
2023 PPConditionalInfo CondInfo;
2024 if (CurLexer->popConditionalLevel(CondInfo)) {
2025 // No conditionals on the stack: this is an #endif without an #if.
2026 return Diag(EndifToken, diag::err_pp_endif_without_if);
2027 }
2028
Chris Lattner371ac8a2006-07-04 07:11:10 +00002029 // If this the end of a top-level #endif, inform MIOpt.
2030 if (CurLexer->getConditionalStackDepth() == 0)
2031 CurLexer->MIOpt.ExitTopLevelConditional();
2032
Chris Lattner538d7f32006-07-20 04:31:52 +00002033 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002034 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002035}
2036
2037
Chris Lattnercb283342006-06-18 06:48:37 +00002038void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002039 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002040
Chris Lattner22eb9722006-06-18 05:43:12 +00002041 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002042 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002043
2044 PPConditionalInfo CI;
2045 if (CurLexer->popConditionalLevel(CI))
2046 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002047
2048 // If this is a top-level #else, inform the MIOpt.
2049 if (CurLexer->getConditionalStackDepth() == 0)
2050 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002051
2052 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002053 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002054
2055 // Finally, skip the rest of the contents of this block and return the first
2056 // token after it.
2057 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2058 /*FoundElse*/true);
2059}
2060
Chris Lattnercb283342006-06-18 06:48:37 +00002061void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002062 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002063
Chris Lattner22eb9722006-06-18 05:43:12 +00002064 // #elif directive in a non-skipping conditional... start skipping.
2065 // We don't care what the condition is, because we will always skip it (since
2066 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002067 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002068
2069 PPConditionalInfo CI;
2070 if (CurLexer->popConditionalLevel(CI))
2071 return Diag(ElifToken, diag::pp_err_elif_without_if);
2072
Chris Lattner371ac8a2006-07-04 07:11:10 +00002073 // If this is a top-level #elif, inform the MIOpt.
2074 if (CurLexer->getConditionalStackDepth() == 0)
2075 CurLexer->MIOpt.FoundTopLevelElse();
2076
Chris Lattner22eb9722006-06-18 05:43:12 +00002077 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002078 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002079
2080 // Finally, skip the rest of the contents of this block and return the first
2081 // token after it.
2082 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2083 /*FoundElse*/CI.FoundElse);
2084}
Chris Lattnerb8761832006-06-24 21:31:03 +00002085