blob: 7ff3f225c2b2a4531cb09bdc7016836c5999243e [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 Lattnerb8761832006-06-24 21:31:03 +000031#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000032#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000033#include "clang/Basic/Diagnostic.h"
34#include "clang/Basic/FileManager.h"
35#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000036#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000037#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000038#include <iostream>
39using namespace llvm;
40using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
Chris Lattner02dffbd2006-10-14 07:50:21 +000044Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
45 TargetInfo &target,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000046 FileManager &FM, SourceManager &SM,
47 HeaderSearch &Headers)
Chris Lattner02dffbd2006-10-14 07:50:21 +000048 : Diags(diags), Features(opts), Target(target), FileMgr(FM), SourceMgr(SM),
Chris Lattner25e0d542006-10-18 06:07:05 +000049 HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerc8997182006-06-22 05:52:16 +000050 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000051 ScratchBuf = new ScratchBuffer(SourceMgr);
52
Chris Lattner22eb9722006-06-18 05:43:12 +000053 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000054 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000055 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000056 NumEnteredSourceFiles = 0;
57 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000058 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000059 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000061
Chris Lattner22eb9722006-06-18 05:43:12 +000062 // Macro expansion is enabled.
63 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000064 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000065
66 // There is no file-change handler yet.
67 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000068 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +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 Lattner87d3bec2006-10-17 03:44:32 +000099
100
Chris Lattner22eb9722006-06-18 05:43:12 +0000101/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
102/// the specified LexerToken's location, translating the token's start
103/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000104void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000105 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000106 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000107}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000108
109void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
110 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
111 << getSpelling(Tok) << "'";
112
113 if (!DumpFlags) return;
114 std::cerr << "\t";
115 if (Tok.isAtStartOfLine())
116 std::cerr << " [StartOfLine]";
117 if (Tok.hasLeadingSpace())
118 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000119 if (Tok.isExpandDisabled())
120 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000121 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000122 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000123 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
124 << "']";
125 }
126}
127
128void Preprocessor::DumpMacro(const MacroInfo &MI) const {
129 std::cerr << "MACRO: ";
130 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
131 DumpToken(MI.getReplacementToken(i));
132 std::cerr << " ";
133 }
134 std::cerr << "\n";
135}
136
Chris Lattner22eb9722006-06-18 05:43:12 +0000137void Preprocessor::PrintStats() {
138 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000139 std::cerr << NumDirectives << " directives found:\n";
140 std::cerr << " " << NumDefined << " #define.\n";
141 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000142 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000143 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
144 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
145 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
146 std::cerr << " " << NumElse << " #else/#elif.\n";
147 std::cerr << " " << NumEndif << " #endif.\n";
148 std::cerr << " " << NumPragma << " #pragma.\n";
149 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
150
Chris Lattner78186052006-07-09 00:45:31 +0000151 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
152 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000153 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000154 std::cerr << (NumFastTokenPaste+NumTokenPaste)
155 << " token paste (##) operations performed, "
156 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000157}
158
159//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000160// Token Spelling
161//===----------------------------------------------------------------------===//
162
163
164/// getSpelling() - Return the 'spelling' of this token. The spelling of a
165/// token are the characters used to represent the token in the source file
166/// after trigraph expansion and escaped-newline folding. In particular, this
167/// wants to get the true, uncanonicalized, spelling of things like digraphs
168/// UCNs, etc.
169std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
170 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
171
172 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000173 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000174 if (!Tok.needsCleaning())
175 return std::string(TokStart, TokStart+Tok.getLength());
176
Chris Lattnerd01e2912006-06-18 16:22:51 +0000177 std::string Result;
178 Result.reserve(Tok.getLength());
179
Chris Lattneref9eae12006-07-04 22:33:12 +0000180 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000181 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
182 Ptr != End; ) {
183 unsigned CharSize;
184 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
185 Ptr += CharSize;
186 }
187 assert(Result.size() != unsigned(Tok.getLength()) &&
188 "NeedsCleaning flag set on something that didn't need cleaning!");
189 return Result;
190}
191
192/// getSpelling - This method is used to get the spelling of a token into a
193/// preallocated buffer, instead of as an std::string. The caller is required
194/// to allocate enough space for the token, which is guaranteed to be at least
195/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000196///
197/// Note that this method may do two possible things: it may either fill in
198/// the buffer specified with characters, or it may *change the input pointer*
199/// to point to a constant buffer with the data already in it (avoiding a
200/// copy). The caller is not allowed to modify the returned buffer pointer
201/// if an internal buffer is returned.
202unsigned Preprocessor::getSpelling(const LexerToken &Tok,
203 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000204 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
205
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000206 // If this token is an identifier, just return the string from the identifier
207 // table, which is very quick.
208 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
209 Buffer = II->getName();
210 return Tok.getLength();
211 }
212
213 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000214 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000215
216 // If this token contains nothing interesting, return it directly.
217 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000218 Buffer = TokStart;
219 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220 }
221 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000222 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000223 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
224 Ptr != End; ) {
225 unsigned CharSize;
226 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
227 Ptr += CharSize;
228 }
229 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
230 "NeedsCleaning flag set on something that didn't need cleaning!");
231
232 return OutBuf-Buffer;
233}
234
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000235
236/// CreateString - Plop the specified string into a scratch buffer and return a
237/// location for it. If specified, the source location provides a source
238/// location for the token.
239SourceLocation Preprocessor::
240CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
241 if (SLoc.isValid())
242 return ScratchBuf->getToken(Buf, Len, SLoc);
243 return ScratchBuf->getToken(Buf, Len);
244}
245
246
Chris Lattnerd01e2912006-06-18 16:22:51 +0000247//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000248// Source File Location Methods.
249//===----------------------------------------------------------------------===//
250
Chris Lattner22eb9722006-06-18 05:43:12 +0000251/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
252/// return null on failure. isAngled indicates whether the file reference is
253/// for system #include's or not (i.e. using <> instead of "").
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000254const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000255 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000256 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000257 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000258 // If the header lookup mechanism may be relative to the current file, pass in
259 // info about where the current file is.
260 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000261 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000262 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000263 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000264 }
265
Chris Lattner63dd32b2006-10-20 04:42:40 +0000266 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000267 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000268 const FileEntry *FE =
269 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
270 if (FE) return FE;
271
272 // Otherwise, see if this is a subframework header. If so, this is relative
273 // to one of the headers on the #include stack. Walk the list of the current
274 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000275 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000276 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
277 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
278 return FE;
279 }
280
281 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
282 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000283 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000284 CurFileEnt =
285 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
286 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
287 return FE;
288 }
289 }
290
291 // Otherwise, we really couldn't find the file.
292 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000293}
294
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000295/// isInPrimaryFile - Return true if we're in the top-level file, not in a
296/// #include.
297bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000298 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000299 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000300
Chris Lattner13044d92006-07-03 05:16:44 +0000301 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000302 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000303 if (IncludeMacroStack[i].TheLexer &&
304 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
305 return IncludeMacroStack[i].TheLexer->isMainFile();
306 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000307}
308
309/// getCurrentLexer - Return the current file lexer being lexed from. Note
310/// that this ignores any potentially active macro expansions and _Pragma
311/// expansions going on at the time.
312Lexer *Preprocessor::getCurrentFileLexer() const {
313 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
314
315 // Look for a stacked lexer.
316 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000317 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000318 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
319 return L;
320 }
321 return 0;
322}
323
324
Chris Lattner22eb9722006-06-18 05:43:12 +0000325/// EnterSourceFile - Add a source file to the top of the include stack and
326/// start lexing tokens from it instead of the current buffer. Return true
327/// on failure.
328void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000329 const DirectoryLookup *CurDir,
330 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000331 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000332 ++NumEnteredSourceFiles;
333
Chris Lattner69772b02006-07-02 20:34:39 +0000334 if (MaxIncludeStackDepth < IncludeMacroStack.size())
335 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000336
Chris Lattner22eb9722006-06-18 05:43:12 +0000337 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000338 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000339 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000340 EnterSourceFileWithLexer(TheLexer, CurDir);
341}
Chris Lattner22eb9722006-06-18 05:43:12 +0000342
Chris Lattner69772b02006-07-02 20:34:39 +0000343/// EnterSourceFile - Add a source file to the top of the include stack and
344/// start lexing tokens from it instead of the current buffer.
345void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
346 const DirectoryLookup *CurDir) {
347
348 // Add the current lexer to the include stack.
349 if (CurLexer || CurMacroExpander)
350 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
351 CurMacroExpander));
352
353 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000354 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000355 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000356
357 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000358 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000359 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
360
361 // Get the file entry for the current file.
362 if (const FileEntry *FE =
363 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000364 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000365
Chris Lattner1840e492006-07-02 22:30:01 +0000366 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000367 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000368 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000369}
370
Chris Lattner69772b02006-07-02 20:34:39 +0000371
372
Chris Lattner22eb9722006-06-18 05:43:12 +0000373/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000374/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000375void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000376 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
377 CurMacroExpander));
378 CurLexer = 0;
379 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000380
Chris Lattneree8760b2006-07-15 07:42:55 +0000381 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000382}
383
Chris Lattner7667d0d2006-07-16 18:16:58 +0000384/// EnterTokenStream - Add a "macro" context to the top of the include stack,
385/// which will cause the lexer to start returning the specified tokens. Note
386/// that these tokens will be re-macro-expanded when/if expansion is enabled.
387/// This method assumes that the specified stream of tokens has a permanent
388/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000389void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000390 // Save our current state.
391 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
392 CurMacroExpander));
393 CurLexer = 0;
394 CurDirLookup = 0;
395
396 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000397 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000398}
399
400/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
401/// lexer stack. This should only be used in situations where the current
402/// state of the top-of-stack lexer is known.
403void Preprocessor::RemoveTopOfLexerStack() {
404 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
405 delete CurLexer;
406 delete CurMacroExpander;
407 CurLexer = IncludeMacroStack.back().TheLexer;
408 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
409 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
410 IncludeMacroStack.pop_back();
411}
412
Chris Lattner22eb9722006-06-18 05:43:12 +0000413//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000414// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000415//===----------------------------------------------------------------------===//
416
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000417/// RegisterBuiltinMacro - Register the specified identifier in the identifier
418/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000419IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000420 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000421 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000422
423 // Mark it as being a macro that is builtin.
424 MacroInfo *MI = new MacroInfo(SourceLocation());
425 MI->setIsBuiltinMacro();
426 Id->setMacroInfo(MI);
427 return Id;
428}
429
430
Chris Lattner677757a2006-06-28 05:26:32 +0000431/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
432/// identifier table.
433void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000434 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000435 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000436 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
437 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000438 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000439
440 // GCC Extensions.
441 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
442 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000443 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000444}
445
Chris Lattnerc2395832006-07-09 00:57:04 +0000446/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
447/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000448static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
449 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000450 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
451
452 // If the token isn't an identifier, it's always literally expanded.
453 if (II == 0) return true;
454
455 // If the identifier is a macro, and if that macro is enabled, it may be
456 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000457 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
458 // Fast expanding "#define X X" is ok, because X would be disabled.
459 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000460 return false;
461
462 // If this is an object-like macro invocation, it is safe to trivially expand
463 // it.
464 if (MI->isObjectLike()) return true;
465
466 // If this is a function-like macro invocation, it's safe to trivially expand
467 // as long as the identifier is not a macro argument.
468 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
469 I != E; ++I)
470 if (*I == II)
471 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000472
Chris Lattnerc2395832006-07-09 00:57:04 +0000473 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000474}
475
Chris Lattnerc2395832006-07-09 00:57:04 +0000476
Chris Lattnerafe603f2006-07-11 04:02:46 +0000477/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
478/// lexed is a '('. If so, consume the token and return true, if not, this
479/// method should have no observable side-effect on the lexed tokens.
480bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000481 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000482 unsigned Val;
483 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000484 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000485 else
486 Val = CurMacroExpander->isNextTokenLParen();
487
488 if (Val == 2) {
489 // If we ran off the end of the lexer or macro expander, walk the include
490 // stack, looking for whatever will return the next token.
491 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
492 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
493 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000494 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000495 else
496 Val = Entry.TheMacroExpander->isNextTokenLParen();
497 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000498 }
499
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000500 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
501 // have found something that isn't a '(' or we found the end of the
502 // translation unit. In either case, return false.
503 if (Val != 1)
504 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000505
506 LexerToken Tok;
507 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000508 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
509 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000510}
Chris Lattner677757a2006-06-28 05:26:32 +0000511
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000512/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
513/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000514bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000515 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000516
517 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
518 if (MI->isBuiltinMacro()) {
519 ExpandBuiltinMacro(Identifier);
520 return false;
521 }
522
Chris Lattner81278c62006-10-14 19:03:49 +0000523 // If this is the first use of a target-specific macro, warn about it.
524 if (MI->isTargetSpecific()) {
525 MI->setIsTargetSpecific(false); // Don't warn on second use.
526 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
527 diag::port_target_macro_use);
528 }
529
Chris Lattneree8760b2006-07-15 07:42:55 +0000530 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000531 /// for each macro argument, the list of tokens that were provided to the
532 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000533 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000534
535 // If this is a function-like macro, read the arguments.
536 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000537 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
538 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000539 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000540 return true;
541
Chris Lattner78186052006-07-09 00:45:31 +0000542 // Remember that we are now parsing the arguments to a macro invocation.
543 // Preprocessor directives used inside macro arguments are not portable, and
544 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000545 InMacroArgs = true;
546 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000547
548 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000549 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000550
551 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000552 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000553
554 ++NumFnMacroExpanded;
555 } else {
556 ++NumMacroExpanded;
557 }
Chris Lattner13044d92006-07-03 05:16:44 +0000558
559 // Notice that this macro has been used.
560 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000561
562 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000563
564 // If this macro expands to no tokens, don't bother to push it onto the
565 // expansion stack, only to take it right back off.
566 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000567 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000568 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000569
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000570 // Ignore this macro use, just return the next token in the current
571 // buffer.
572 bool HadLeadingSpace = Identifier.hasLeadingSpace();
573 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
574
575 Lex(Identifier);
576
577 // If the identifier isn't on some OTHER line, inherit the leading
578 // whitespace/first-on-a-line property of this token. This handles
579 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
580 // empty.
581 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000582 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
583 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000584 }
585 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000586 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000587
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000588 } else if (MI->getNumTokens() == 1 &&
589 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000590 // Otherwise, if this macro expands into a single trivially-expanded
591 // token: expand it now. This handles common cases like
592 // "#define VAL 42".
593
594 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
595 // identifier to the expanded token.
596 bool isAtStartOfLine = Identifier.isAtStartOfLine();
597 bool hasLeadingSpace = Identifier.hasLeadingSpace();
598
599 // Remember where the token is instantiated.
600 SourceLocation InstantiateLoc = Identifier.getLocation();
601
602 // Replace the result token.
603 Identifier = MI->getReplacementToken(0);
604
605 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000606 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
607 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000608
609 // Update the tokens location to include both its logical and physical
610 // locations.
611 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000612 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000613 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000614
Chris Lattner6e4bf522006-07-27 06:59:25 +0000615 // If this is #define X X, we must mark the result as unexpandible.
616 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
617 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000618 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000619
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000620 // Since this is not an identifier token, it can't be macro expanded, so
621 // we're done.
622 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000623 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000624 }
625
Chris Lattner78186052006-07-09 00:45:31 +0000626 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000627 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000628
629 // Now that the macro is at the top of the include stack, ask the
630 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000631 Lex(Identifier);
632 return false;
633}
634
Chris Lattneree8760b2006-07-15 07:42:55 +0000635/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000636/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000637/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000638MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
639 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000640 // The number of fixed arguments to parse.
641 unsigned NumFixedArgsLeft = MI->getNumArgs();
642 bool isVariadic = MI->isVariadic();
643
Chris Lattner78186052006-07-09 00:45:31 +0000644 // Outer loop, while there are more arguments, keep reading them.
645 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000646 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000647 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000648
649 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000650 // argument is separated by an EOF token. Use a SmallVector so we can avoid
651 // heap allocations in the common case.
652 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000653
654 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000655 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000656 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
657 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000658
Chris Lattner78186052006-07-09 00:45:31 +0000659 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000660 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
661 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000662 LexUnexpandedToken(Tok);
663
664 if (Tok.getKind() == tok::eof) {
665 Diag(MacroName, diag::err_unterm_macro_invoc);
666 // Do not lose the EOF. Return it to the client.
667 MacroName = Tok;
668 return 0;
669 } else if (Tok.getKind() == tok::r_paren) {
670 // If we found the ) token, the macro arg list is done.
671 if (NumParens-- == 0)
672 break;
673 } else if (Tok.getKind() == tok::l_paren) {
674 ++NumParens;
675 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
676 // Comma ends this argument if there are more fixed arguments expected.
677 if (NumFixedArgsLeft)
678 break;
679
Chris Lattner2ada5d32006-07-15 07:51:24 +0000680 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000681 if (!isVariadic) {
682 // Emit the diagnostic at the macro name in case there is a missing ).
683 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000684 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000685 return 0;
686 }
687 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000688 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
689 // If this is a comment token in the argument list and we're just in
690 // -C mode (not -CC mode), discard the comment.
691 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000692 }
693
694 ArgTokens.push_back(Tok);
695 }
696
Chris Lattnera12dd152006-07-11 04:09:02 +0000697 // Empty arguments are standard in C99 and supported as an extension in
698 // other modes.
699 if (ArgTokens.empty() && !Features.C99)
700 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000701
Chris Lattner36b6e812006-07-21 06:38:30 +0000702 // Add a marker EOF token to the end of the token list for this argument.
703 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000704 EOFTok.startToken();
705 EOFTok.setKind(tok::eof);
706 EOFTok.setLocation(Tok.getLocation());
707 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000708 ArgTokens.push_back(EOFTok);
709 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000710 --NumFixedArgsLeft;
711 };
712
713 // Okay, we either found the r_paren. Check to see if we parsed too few
714 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000715 unsigned MinArgsExpected = MI->getNumArgs();
716
Chris Lattner775d8322006-07-29 04:39:41 +0000717 // See MacroArgs instance var for description of this.
718 bool isVarargsElided = false;
719
Chris Lattner2ada5d32006-07-15 07:51:24 +0000720 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000721 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000722 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000723 // Varargs where the named vararg parameter is missing: ok as extension.
724 // #define A(x, ...)
725 // A("blah")
726 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000727
728 // Remember this occurred if this is a C99 macro invocation with at least
729 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000730 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000731 } else if (MI->getNumArgs() == 1) {
732 // #define A(x)
733 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000734 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000735
736 // Empty arguments are standard in C99 and supported as an extension in
737 // other modes.
738 if (ArgTokens.empty() && !Features.C99)
739 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000740 } else {
741 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000742 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000743 return 0;
744 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000745
746 // Add a marker EOF token to the end of the token list for this argument.
747 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000748 Tok.startToken();
749 Tok.setKind(tok::eof);
750 Tok.setLocation(EndLoc);
751 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000752 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000753 }
754
Chris Lattner775d8322006-07-29 04:39:41 +0000755 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000756}
757
Chris Lattnerc673f902006-06-30 06:10:41 +0000758/// ComputeDATE_TIME - Compute the current time, enter it into the specified
759/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
760/// the identifier tokens inserted.
761static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000762 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000763 time_t TT = time(0);
764 struct tm *TM = localtime(&TT);
765
766 static const char * const Months[] = {
767 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
768 };
769
770 char TmpBuffer[100];
771 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
772 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000773 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000774
775 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000776 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000777}
778
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000779/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
780/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000781void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000782 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000783 IdentifierInfo *II = Tok.getIdentifierInfo();
784 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000785
786 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
787 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000788 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000789 return Handle_Pragma(Tok);
790
Chris Lattner78186052006-07-09 00:45:31 +0000791 ++NumBuiltinMacroExpanded;
792
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000793 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000794
795 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000796 Tok.setIdentifierInfo(0);
797 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000798
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000799 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000800 // __LINE__ expands to a simple numeric value.
801 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
802 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000803 Tok.setKind(tok::numeric_constant);
804 Tok.setLength(Length);
805 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000806 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000807 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000808 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000809 Diag(Tok, diag::ext_pp_base_file);
810 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
811 while (NextLoc.getFileID() != 0) {
812 Loc = NextLoc;
813 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
814 }
815 }
816
Chris Lattner0766e592006-07-03 01:07:01 +0000817 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
818 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000819 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000820 Tok.setKind(tok::string_literal);
821 Tok.setLength(FN.size());
822 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000823 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000824 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000825 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000826 Tok.setKind(tok::string_literal);
827 Tok.setLength(strlen("\"Mmm dd yyyy\""));
828 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000829 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000830 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000831 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000832 Tok.setKind(tok::string_literal);
833 Tok.setLength(strlen("\"hh:mm:ss\""));
834 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000835 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000836 Diag(Tok, diag::ext_pp_include_level);
837
838 // Compute the include depth of this token.
839 unsigned Depth = 0;
840 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
841 for (; Loc.getFileID() != 0; ++Depth)
842 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
843
844 // __INCLUDE_LEVEL__ expands to a simple numeric value.
845 sprintf(TmpBuffer, "%u", Depth);
846 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000847 Tok.setKind(tok::numeric_constant);
848 Tok.setLength(Length);
849 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000850 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000851 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
852 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
853 Diag(Tok, diag::ext_pp_timestamp);
854
855 // Get the file that we are lexing out of. If we're currently lexing from
856 // a macro, dig into the include stack.
857 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000858 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000859
860 if (TheLexer)
861 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
862
863 // If this file is older than the file it depends on, emit a diagnostic.
864 const char *Result;
865 if (CurFile) {
866 time_t TT = CurFile->getModificationTime();
867 struct tm *TM = localtime(&TT);
868 Result = asctime(TM);
869 } else {
870 Result = "??? ??? ?? ??:??:?? ????\n";
871 }
872 TmpBuffer[0] = '"';
873 strcpy(TmpBuffer+1, Result);
874 unsigned Len = strlen(TmpBuffer);
875 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000876 Tok.setKind(tok::string_literal);
877 Tok.setLength(Len);
878 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000879 } else {
880 assert(0 && "Unknown identifier!");
881 }
882}
Chris Lattner677757a2006-06-28 05:26:32 +0000883
Chris Lattner13044d92006-07-03 05:16:44 +0000884namespace {
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000885struct UnusedIdentifierReporter : public CStringMapVisitor {
Chris Lattner13044d92006-07-03 05:16:44 +0000886 Preprocessor &PP;
887 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
888
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000889 void Visit(const char *Key, void *Value) const {
890 IdentifierInfo &II = *static_cast<IdentifierInfo*>(Value);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000891 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
892 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000893 }
894};
895}
896
Chris Lattner677757a2006-06-28 05:26:32 +0000897//===----------------------------------------------------------------------===//
898// Lexer Event Handling.
899//===----------------------------------------------------------------------===//
900
Chris Lattnercefc7682006-07-08 08:28:12 +0000901/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
902/// identifier information for the token and install it into the token.
903IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
904 const char *BufPtr) {
905 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
906 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
907
908 // Look up this token, see if it is a macro, or if it is a language keyword.
909 IdentifierInfo *II;
910 if (BufPtr && !Identifier.needsCleaning()) {
911 // No cleaning needed, just use the characters from the lexed buffer.
912 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
913 } else {
914 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
915 const char *TmpBuf = (char*)alloca(Identifier.getLength());
916 unsigned Size = getSpelling(Identifier, TmpBuf);
917 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
918 }
Chris Lattner8c204872006-10-14 05:19:21 +0000919 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000920 return II;
921}
922
923
Chris Lattner677757a2006-06-28 05:26:32 +0000924/// HandleIdentifier - This callback is invoked when the lexer reads an
925/// identifier. This callback looks up the identifier in the map and/or
926/// potentially macro expands it or turns it into a named token (like 'for').
927void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000928 assert(Identifier.getIdentifierInfo() &&
929 "Can't handle identifiers without identifier info!");
930
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000931 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000932
933 // If this identifier was poisoned, and if it was not produced from a macro
934 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000935 if (II.isPoisoned() && CurLexer) {
936 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
937 Diag(Identifier, diag::err_pp_used_poisoned_id);
938 else
939 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
940 }
Chris Lattner677757a2006-06-28 05:26:32 +0000941
Chris Lattner78186052006-07-09 00:45:31 +0000942 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000943 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000944 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
945 if (MI->isEnabled()) {
946 if (!HandleMacroExpandedIdentifier(Identifier, MI))
947 return;
948 } else {
949 // C99 6.10.3.4p2 says that a disabled macro may never again be
950 // expanded, even if it's in a context where it could be expanded in the
951 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000952 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000953 }
954 }
Chris Lattner063400e2006-10-14 19:54:15 +0000955 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
956 // If this identifier is a macro on some other target, emit a diagnostic.
957 // This diagnosic is only emitted when macro expansion is enabled, because
958 // the macro would not have been expanded for the other target either.
959 II.setIsOtherTargetMacro(false); // Don't warn on second use.
960 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
961 diag::port_target_macro_use);
962
963 }
Chris Lattner677757a2006-06-28 05:26:32 +0000964
965 // Change the kind of this identifier to the appropriate token kind, e.g.
966 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000967 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000968
969 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000970 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000971}
972
Chris Lattner22eb9722006-06-18 05:43:12 +0000973/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
974/// the current file. This either returns the EOF token or pops a level off
975/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000976bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000977 assert(!CurMacroExpander &&
978 "Ending a file when currently in a macro!");
979
Chris Lattner371ac8a2006-07-04 07:11:10 +0000980 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000981 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000982 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000983 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000984 // Okay, this has a controlling macro, remember in PerFileInfo.
985 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000986 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
987 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000988 }
989 }
990
Chris Lattner22eb9722006-06-18 05:43:12 +0000991 // If this is a #include'd file, pop it off the include stack and continue
992 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000993 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000994 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000995 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +0000996
997 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000998 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000999 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1000
1001 // Get the file entry for the current file.
1002 if (const FileEntry *FE =
1003 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001004 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001005
Chris Lattner0c885f52006-06-21 06:50:18 +00001006 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001007 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001008 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001009
1010 // Client should lex another token.
1011 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001012 }
1013
Chris Lattner8c204872006-10-14 05:19:21 +00001014 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001015 CurLexer->BufferPtr = CurLexer->BufferEnd;
1016 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001017 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001018
1019 // We're done with the #included file.
1020 delete CurLexer;
1021 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001022
Chris Lattner03f83482006-07-10 06:16:26 +00001023 // This is the end of the top-level file. If the diag::pp_macro_not_used
1024 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1025 // have not been used.
1026 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1027 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001028
1029 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001030}
1031
1032/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001033/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001034bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001035 assert(CurMacroExpander && !CurLexer &&
1036 "Ending a macro when currently in a #include file!");
1037
Chris Lattner22eb9722006-06-18 05:43:12 +00001038 delete CurMacroExpander;
1039
Chris Lattner69772b02006-07-02 20:34:39 +00001040 // Handle this like a #include file being popped off the stack.
1041 CurMacroExpander = 0;
1042 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001043}
1044
1045
1046//===----------------------------------------------------------------------===//
1047// Utility Methods for Preprocessor Directive Handling.
1048//===----------------------------------------------------------------------===//
1049
1050/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1051/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001052void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001053 LexerToken Tmp;
1054 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001055 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001056 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001057}
1058
1059/// ReadMacroName - Lex and validate a macro name, which occurs after a
1060/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001061/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1062/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001063/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001064void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001065 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001066 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001067
1068 // Missing macro name?
1069 if (MacroNameTok.getKind() == tok::eom)
1070 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1071
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001072 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1073 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001074 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001075 // Fall through on error.
1076 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001077 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001078
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001079 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1080 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001081 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001082 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001083 } else if (isDefineUndef && II->getMacroInfo() &&
1084 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001085 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001086 if (isDefineUndef == 1)
1087 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1088 else
1089 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001090 } else {
1091 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001092 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001093 }
1094
Chris Lattner22eb9722006-06-18 05:43:12 +00001095 // Invalid macro name, read and discard the rest of the line. Then set the
1096 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001097 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001098 return DiscardUntilEndOfDirective();
1099}
1100
1101/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1102/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001103void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001104 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001105 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001106 // There should be no tokens after the directive, but we allow them as an
1107 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001108 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1109 Lex(Tmp);
1110
Chris Lattner22eb9722006-06-18 05:43:12 +00001111 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001112 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1113 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001114 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001115}
1116
1117
1118
1119/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1120/// decided that the subsequent tokens are in the #if'd out portion of the
1121/// file. Lex the rest of the file, until we see an #endif. If
1122/// FoundNonSkipPortion is true, then we have already emitted code for part of
1123/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1124/// is true, then #else directives are ok, if not, then we have already seen one
1125/// so a #else directive is a duplicate. When this returns, the caller can lex
1126/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001127void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001128 bool FoundNonSkipPortion,
1129 bool FoundElse) {
1130 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001131 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001132 "Lexing a macro, not a file?");
1133
1134 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1135 FoundNonSkipPortion, FoundElse);
1136
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001137 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1138 // disabling warnings, etc.
1139 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001140 LexerToken Tok;
1141 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001142 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001143
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001144 // If this is the end of the buffer, we have an error.
1145 if (Tok.getKind() == tok::eof) {
1146 // Emit errors for each unterminated conditional on the stack, including
1147 // the current one.
1148 while (!CurLexer->ConditionalStack.empty()) {
1149 Diag(CurLexer->ConditionalStack.back().IfLoc,
1150 diag::err_pp_unterminated_conditional);
1151 CurLexer->ConditionalStack.pop_back();
1152 }
1153
1154 // Just return and let the caller lex after this #include.
1155 break;
1156 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001157
1158 // If this token is not a preprocessor directive, just skip it.
1159 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1160 continue;
1161
1162 // We just parsed a # character at the start of a line, so we're in
1163 // directive mode. Tell the lexer this so any newlines we see will be
1164 // converted into an EOM token (this terminates the macro).
1165 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001166 CurLexer->KeepCommentMode = false;
1167
Chris Lattner22eb9722006-06-18 05:43:12 +00001168
1169 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001170 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001171
1172 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1173 // something bogus), skip it.
1174 if (Tok.getKind() != tok::identifier) {
1175 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001176 // Restore comment saving mode.
1177 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001178 continue;
1179 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001180
Chris Lattner22eb9722006-06-18 05:43:12 +00001181 // If the first letter isn't i or e, it isn't intesting to us. We know that
1182 // this is safe in the face of spelling differences, because there is no way
1183 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001184 // allows us to avoid looking up the identifier info for #define/#undef and
1185 // other common directives.
1186 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1187 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001188 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1189 FirstChar != 'i' && FirstChar != 'e') {
1190 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001191 // Restore comment saving mode.
1192 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001193 continue;
1194 }
1195
Chris Lattnere60165f2006-06-22 06:36:29 +00001196 // Get the identifier name without trigraphs or embedded newlines. Note
1197 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1198 // when skipping.
1199 // TODO: could do this with zero copies in the no-clean case by using
1200 // strncmp below.
1201 char Directive[20];
1202 unsigned IdLen;
1203 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1204 IdLen = Tok.getLength();
1205 memcpy(Directive, RawCharData, IdLen);
1206 Directive[IdLen] = 0;
1207 } else {
1208 std::string DirectiveStr = getSpelling(Tok);
1209 IdLen = DirectiveStr.size();
1210 if (IdLen >= 20) {
1211 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001212 // Restore comment saving mode.
1213 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001214 continue;
1215 }
1216 memcpy(Directive, &DirectiveStr[0], IdLen);
1217 Directive[IdLen] = 0;
1218 }
1219
Chris Lattner22eb9722006-06-18 05:43:12 +00001220 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001221 if ((IdLen == 2) || // "if"
1222 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1223 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001224 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1225 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001226 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001227 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001228 /*foundnonskip*/false,
1229 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001230 }
1231 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001232 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001233 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001234 PPConditionalInfo CondInfo;
1235 CondInfo.WasSkipping = true; // Silence bogus warning.
1236 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1237 assert(!InCond && "Can't be skipping if not in a conditional!");
1238
1239 // If we popped the outermost skipping block, we're done skipping!
1240 if (!CondInfo.WasSkipping)
1241 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001242 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001243 // #else directive in a skipping conditional. If not in some other
1244 // skipping conditional, and if #else hasn't already been seen, enter it
1245 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001246 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001247 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1248
1249 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001250 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001251
1252 // Note that we've seen a #else in this conditional.
1253 CondInfo.FoundElse = true;
1254
1255 // If the conditional is at the top level, and the #if block wasn't
1256 // entered, enter the #else block now.
1257 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1258 CondInfo.FoundNonSkip = true;
1259 break;
1260 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001261 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001262 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1263
1264 bool ShouldEnter;
1265 // If this is in a skipping block or if we're already handled this #if
1266 // block, don't bother parsing the condition.
1267 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001268 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001269 ShouldEnter = false;
1270 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001271 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001272 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001273 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1274 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001275 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001276 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001277 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001278 }
1279
1280 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001281 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001282
1283 // If this condition is true, enter it!
1284 if (ShouldEnter) {
1285 CondInfo.FoundNonSkip = true;
1286 break;
1287 }
1288 }
1289 }
1290
1291 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001292 // Restore comment saving mode.
1293 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001294 }
1295
1296 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1297 // of the file, just stop skipping and return to lexing whatever came after
1298 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001299 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001300}
1301
1302//===----------------------------------------------------------------------===//
1303// Preprocessor Directive Handling.
1304//===----------------------------------------------------------------------===//
1305
1306/// HandleDirective - This callback is invoked when the lexer sees a # token
1307/// at the start of a line. This consumes the directive, modifies the
1308/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1309/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001310void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001311 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001312
1313 // We just parsed a # character at the start of a line, so we're in directive
1314 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001315 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001316 CurLexer->ParsingPreprocessorDirective = true;
1317
1318 ++NumDirectives;
1319
Chris Lattner371ac8a2006-07-04 07:11:10 +00001320 // We are about to read a token. For the multiple-include optimization FA to
1321 // work, we have to remember if we had read any tokens *before* this
1322 // pp-directive.
1323 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1324
Chris Lattner78186052006-07-09 00:45:31 +00001325 // Read the next token, the directive flavor. This isn't expanded due to
1326 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001327 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001328
Chris Lattner78186052006-07-09 00:45:31 +00001329 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1330 // #define A(x) #x
1331 // A(abc
1332 // #warning blah
1333 // def)
1334 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001335 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001336 Diag(Result, diag::ext_embedded_directive);
1337
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001338TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001339 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001340 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001341 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001342 case tok::comment:
1343 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1344 LexUnexpandedToken(Result);
1345 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001346
Chris Lattner22eb9722006-06-18 05:43:12 +00001347 case tok::numeric_constant:
1348 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001349 DiscardUntilEndOfDirective();
1350 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001351 default:
1352 IdentifierInfo *II = Result.getIdentifierInfo();
1353 if (II == 0) break; // Not an identifier.
1354
1355 // Ask what the preprocessor keyword ID is.
1356 switch (II->getPPKeywordID()) {
1357 default: break;
1358 // C99 6.10.1 - Conditional Inclusion.
1359 case tok::pp_if:
1360 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1361 case tok::pp_ifdef:
1362 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1363 case tok::pp_ifndef:
1364 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1365 case tok::pp_elif:
1366 return HandleElifDirective(Result);
1367 case tok::pp_else:
1368 return HandleElseDirective(Result);
1369 case tok::pp_endif:
1370 return HandleEndifDirective(Result);
1371
1372 // C99 6.10.2 - Source File Inclusion.
1373 case tok::pp_include:
1374 return HandleIncludeDirective(Result); // Handle #include.
1375
1376 // C99 6.10.3 - Macro Replacement.
1377 case tok::pp_define:
1378 return HandleDefineDirective(Result, false);
1379 case tok::pp_undef:
1380 return HandleUndefDirective(Result);
1381
1382 // C99 6.10.4 - Line Control.
1383 case tok::pp_line:
1384 // FIXME: implement #line
1385 DiscardUntilEndOfDirective();
1386 return;
1387
1388 // C99 6.10.5 - Error Directive.
1389 case tok::pp_error:
1390 return HandleUserDiagnosticDirective(Result, false);
1391
1392 // C99 6.10.6 - Pragma Directive.
1393 case tok::pp_pragma:
1394 return HandlePragmaDirective();
1395
1396 // GNU Extensions.
1397 case tok::pp_import:
1398 return HandleImportDirective(Result);
1399 case tok::pp_include_next:
1400 return HandleIncludeNextDirective(Result);
1401
1402 case tok::pp_warning:
1403 Diag(Result, diag::ext_pp_warning_directive);
1404 return HandleUserDiagnosticDirective(Result, true);
1405 case tok::pp_ident:
1406 return HandleIdentSCCSDirective(Result);
1407 case tok::pp_sccs:
1408 return HandleIdentSCCSDirective(Result);
1409 case tok::pp_assert:
1410 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001411 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001412 case tok::pp_unassert:
1413 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001414 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001415
1416 // clang extensions.
1417 case tok::pp_define_target:
1418 return HandleDefineDirective(Result, true);
1419 case tok::pp_define_other_target:
1420 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001421 }
1422 break;
1423 }
1424
1425 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001426 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001427
1428 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001429 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001430
1431 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001432}
1433
Chris Lattner01d66cc2006-07-03 22:16:27 +00001434void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001435 bool isWarning) {
1436 // Read the rest of the line raw. We do this because we don't want macros
1437 // to be expanded and we don't require that the tokens be valid preprocessing
1438 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1439 // collapse multiple consequtive white space between tokens, but this isn't
1440 // specified by the standard.
1441 std::string Message = CurLexer->ReadToEndOfLine();
1442
1443 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001444 return Diag(Tok, DiagID, Message);
1445}
1446
1447/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1448///
1449void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001450 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001451 Diag(Tok, diag::ext_pp_ident_directive);
1452
Chris Lattner371ac8a2006-07-04 07:11:10 +00001453 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001454 LexerToken StrTok;
1455 Lex(StrTok);
1456
1457 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001458 if (StrTok.getKind() != tok::string_literal &&
1459 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001460 return Diag(StrTok, diag::err_pp_malformed_ident);
1461
1462 // Verify that there is nothing after the string, other than EOM.
1463 CheckEndOfDirective("#ident");
1464
1465 if (IdentHandler)
1466 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001467}
1468
Chris Lattnerb8761832006-06-24 21:31:03 +00001469//===----------------------------------------------------------------------===//
1470// Preprocessor Include Directive Handling.
1471//===----------------------------------------------------------------------===//
1472
Chris Lattner22eb9722006-06-18 05:43:12 +00001473/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1474/// file to be included from the lexer, then include it! This is a common
1475/// routine with functionality shared between #include, #include_next and
1476/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001477void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001478 const DirectoryLookup *LookupFrom,
1479 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001480
Chris Lattner22eb9722006-06-18 05:43:12 +00001481 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001482 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001483
1484 // If the token kind is EOM, the error has already been diagnosed.
1485 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001486 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001487
1488 // Verify that there is nothing after the filename, other than EOM. Use the
1489 // preprocessor to lex this in case lexing the filename entered a macro.
1490 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001491
1492 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001493 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001494 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1495
Chris Lattner269c2322006-06-25 06:23:00 +00001496 // Find out whether the filename is <x> or "x".
1497 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001498
1499 // Remove the quotes.
1500 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1501
Chris Lattner22eb9722006-06-18 05:43:12 +00001502 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001503 const DirectoryLookup *CurDir;
1504 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001505 if (File == 0)
1506 return Diag(FilenameTok, diag::err_pp_file_not_found);
1507
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001508 // Ask HeaderInfo if we should enter this #include file.
1509 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1510 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001511 return;
1512 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001513
1514 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001515 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001516 if (FileID == 0)
1517 return Diag(FilenameTok, diag::err_pp_file_not_found);
1518
1519 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001520 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001521}
1522
1523/// HandleIncludeNextDirective - Implements #include_next.
1524///
Chris Lattnercb283342006-06-18 06:48:37 +00001525void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1526 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001527
1528 // #include_next is like #include, except that we start searching after
1529 // the current found directory. If we can't do this, issue a
1530 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001531 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001532 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001533 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001534 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001535 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001536 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001537 } else {
1538 // Start looking up in the next directory.
1539 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001540 }
1541
1542 return HandleIncludeDirective(IncludeNextTok, Lookup);
1543}
1544
1545/// HandleImportDirective - Implements #import.
1546///
Chris Lattnercb283342006-06-18 06:48:37 +00001547void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1548 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001549
1550 return HandleIncludeDirective(ImportTok, 0, true);
1551}
1552
Chris Lattnerb8761832006-06-24 21:31:03 +00001553//===----------------------------------------------------------------------===//
1554// Preprocessor Macro Directive Handling.
1555//===----------------------------------------------------------------------===//
1556
Chris Lattnercefc7682006-07-08 08:28:12 +00001557/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1558/// definition has just been read. Lex the rest of the arguments and the
1559/// closing ), updating MI with what we learn. Return true if an error occurs
1560/// parsing the arg list.
1561bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1562 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001563 while (1) {
1564 LexUnexpandedToken(Tok);
1565 switch (Tok.getKind()) {
1566 case tok::r_paren:
1567 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001568 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001569 // Otherwise we have #define FOO(A,)
1570 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1571 return true;
1572 case tok::ellipsis: // #define X(... -> C99 varargs
1573 // Warn if use of C99 feature in non-C99 mode.
1574 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1575
1576 // Lex the token after the identifier.
1577 LexUnexpandedToken(Tok);
1578 if (Tok.getKind() != tok::r_paren) {
1579 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1580 return true;
1581 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001582 // Add the __VA_ARGS__ identifier as an argument.
1583 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001584 MI->setIsC99Varargs();
1585 return false;
1586 case tok::eom: // #define X(
1587 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1588 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001589 default:
1590 // Handle keywords and identifiers here to accept things like
1591 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001592 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001593 if (II == 0) {
1594 // #define X(1
1595 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1596 return true;
1597 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001598
1599 // If this is already used as an argument, it is used multiple times (e.g.
1600 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001601 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001602 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1603 return true;
1604 }
1605
1606 // Add the argument to the macro info.
1607 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001608
1609 // Lex the token after the identifier.
1610 LexUnexpandedToken(Tok);
1611
1612 switch (Tok.getKind()) {
1613 default: // #define X(A B
1614 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1615 return true;
1616 case tok::r_paren: // #define X(A)
1617 return false;
1618 case tok::comma: // #define X(A,
1619 break;
1620 case tok::ellipsis: // #define X(A... -> GCC extension
1621 // Diagnose extension.
1622 Diag(Tok, diag::ext_named_variadic_macro);
1623
1624 // Lex the token after the identifier.
1625 LexUnexpandedToken(Tok);
1626 if (Tok.getKind() != tok::r_paren) {
1627 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1628 return true;
1629 }
1630
1631 MI->setIsGNUVarargs();
1632 return false;
1633 }
1634 }
1635 }
1636}
1637
Chris Lattner22eb9722006-06-18 05:43:12 +00001638/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001639/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1640/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001641///
Chris Lattner81278c62006-10-14 19:03:49 +00001642void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1643 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001644 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001645
Chris Lattner22eb9722006-06-18 05:43:12 +00001646 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001647 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001648
1649 // Error reading macro name? If so, diagnostic already issued.
1650 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001651 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001652
Chris Lattner457fc152006-07-29 06:30:25 +00001653 // If we are supposed to keep comments in #defines, reenable comment saving
1654 // mode.
1655 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1656
Chris Lattner063400e2006-10-14 19:54:15 +00001657 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001658 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001659 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001660
Chris Lattner063400e2006-10-14 19:54:15 +00001661 // If the identifier is an 'other target' macro, clear this bit.
1662 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1663
1664
Chris Lattner22eb9722006-06-18 05:43:12 +00001665 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001666 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001667
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001668 // If this is a function-like macro definition, parse the argument list,
1669 // marking each of the identifiers as being used as macro arguments. Also,
1670 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001671 if (Tok.getKind() == tok::eom) {
1672 // If there is no body to this macro, we have no special handling here.
1673 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001674 // This is a function-like macro definition. Read the argument list.
1675 MI->setIsFunctionLike();
1676 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001677 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001678 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001679 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001680 if (CurLexer->ParsingPreprocessorDirective)
1681 DiscardUntilEndOfDirective();
1682 return;
1683 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001684
Chris Lattner815a1f92006-07-08 20:48:04 +00001685 // Read the first token after the arg list for down below.
1686 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001687 } else if (!Tok.hasLeadingSpace()) {
1688 // C99 requires whitespace between the macro definition and the body. Emit
1689 // a diagnostic for something like "#define X+".
1690 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001691 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001692 } else {
1693 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1694 // one in some cases!
1695 }
1696 } else {
1697 // This is a normal token with leading space. Clear the leading space
1698 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001699 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001700 }
1701
Chris Lattner7e374832006-07-29 03:46:57 +00001702 // If this is a definition of a variadic C99 function-like macro, not using
1703 // the GNU named varargs extension, enabled __VA_ARGS__.
1704
1705 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1706 // This gets unpoisoned where it is allowed.
1707 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1708 if (MI->isC99Varargs())
1709 Ident__VA_ARGS__->setIsPoisoned(false);
1710
Chris Lattner22eb9722006-06-18 05:43:12 +00001711 // Read the rest of the macro body.
1712 while (Tok.getKind() != tok::eom) {
1713 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001714
1715 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001716 // parameters in function-like macro expansions.
1717 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001718 // Get the next token of the macro.
1719 LexUnexpandedToken(Tok);
1720 continue;
1721 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001722
Chris Lattner815a1f92006-07-08 20:48:04 +00001723 // Get the next token of the macro.
1724 LexUnexpandedToken(Tok);
1725
1726 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001727 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001728 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001729 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001730 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001731
1732 // Disable __VA_ARGS__ again.
1733 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001734 return;
1735 }
1736
1737 // Things look ok, add the param name token to the macro.
1738 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001739
Chris Lattner22eb9722006-06-18 05:43:12 +00001740 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001741 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001742 }
Chris Lattner7e374832006-07-29 03:46:57 +00001743
1744 // Disable __VA_ARGS__ again.
1745 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001746
Chris Lattnerbff18d52006-07-06 04:49:18 +00001747 // Check that there is no paste (##) operator at the begining or end of the
1748 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001749 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001750 if (NumTokens != 0) {
1751 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001752 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001753 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001754 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001755 }
1756 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001757 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001758 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001759 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001760 }
1761 }
1762
Chris Lattner13044d92006-07-03 05:16:44 +00001763 // If this is the primary source file, remember that this macro hasn't been
1764 // used yet.
1765 if (isInPrimaryFile())
1766 MI->setIsUsed(false);
1767
Chris Lattner22eb9722006-06-18 05:43:12 +00001768 // Finally, if this identifier already had a macro defined for it, verify that
1769 // the macro bodies are identical and free the old definition.
1770 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001771 if (!OtherMI->isUsed())
1772 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1773
Chris Lattner22eb9722006-06-18 05:43:12 +00001774 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001775 // must be the same. C99 6.10.3.2.
1776 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001777 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1778 MacroNameTok.getIdentifierInfo()->getName());
1779 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1780 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001781 delete OtherMI;
1782 }
1783
1784 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001785}
1786
Chris Lattner063400e2006-10-14 19:54:15 +00001787/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1788void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1789 LexerToken MacroNameTok;
1790 ReadMacroName(MacroNameTok, 1);
1791
1792 // Error reading macro name? If so, diagnostic already issued.
1793 if (MacroNameTok.getKind() == tok::eom)
1794 return;
1795
1796 // Check to see if this is the last token on the #undef line.
1797 CheckEndOfDirective("#define_other_target");
1798
1799 // If there is already a macro defined by this name, turn it into a
1800 // target-specific define.
1801 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1802 MI->setIsTargetSpecific(true);
1803 return;
1804 }
1805
1806 // Mark the identifier as being a macro on some other target.
1807 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1808}
1809
Chris Lattner22eb9722006-06-18 05:43:12 +00001810
1811/// HandleUndefDirective - Implements #undef.
1812///
Chris Lattnercb283342006-06-18 06:48:37 +00001813void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001814 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001815
Chris Lattner22eb9722006-06-18 05:43:12 +00001816 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001817 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001818
1819 // Error reading macro name? If so, diagnostic already issued.
1820 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001821 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001822
1823 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001824 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001825
1826 // Okay, we finally have a valid identifier to undef.
1827 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1828
Chris Lattner063400e2006-10-14 19:54:15 +00001829 // #undef untaints an identifier if it were marked by define_other_target.
1830 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1831
Chris Lattner22eb9722006-06-18 05:43:12 +00001832 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001833 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001834
Chris Lattner13044d92006-07-03 05:16:44 +00001835 if (!MI->isUsed())
1836 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001837
1838 // Free macro definition.
1839 delete MI;
1840 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001841}
1842
1843
Chris Lattnerb8761832006-06-24 21:31:03 +00001844//===----------------------------------------------------------------------===//
1845// Preprocessor Conditional Directive Handling.
1846//===----------------------------------------------------------------------===//
1847
Chris Lattner22eb9722006-06-18 05:43:12 +00001848/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001849/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1850/// if any tokens have been returned or pp-directives activated before this
1851/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001852///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001853void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1854 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001855 ++NumIf;
1856 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001857
Chris Lattner22eb9722006-06-18 05:43:12 +00001858 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001859 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001860
1861 // Error reading macro name? If so, diagnostic already issued.
1862 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001863 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001864
1865 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001866 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1867
1868 // If the start of a top-level #ifdef, inform MIOpt.
1869 if (!ReadAnyTokensBeforeDirective &&
1870 CurLexer->getConditionalStackDepth() == 0) {
1871 assert(isIfndef && "#ifdef shouldn't reach here");
1872 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1873 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001874
Chris Lattner063400e2006-10-14 19:54:15 +00001875 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1876 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001877
Chris Lattner81278c62006-10-14 19:03:49 +00001878 // If there is a macro, process it.
1879 if (MI) {
1880 // Mark it used.
1881 MI->setIsUsed(true);
1882
1883 // If this is the first use of a target-specific macro, warn about it.
1884 if (MI->isTargetSpecific()) {
1885 MI->setIsTargetSpecific(false); // Don't warn on second use.
1886 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1887 diag::port_target_macro_use);
1888 }
Chris Lattner063400e2006-10-14 19:54:15 +00001889 } else {
1890 // Use of a target-specific macro for some other target? If so, warn.
1891 if (MII->isOtherTargetMacro()) {
1892 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1893 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1894 diag::port_target_macro_use);
1895 }
Chris Lattner81278c62006-10-14 19:03:49 +00001896 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001897
Chris Lattner22eb9722006-06-18 05:43:12 +00001898 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001899 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001900 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001901 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001902 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001903 } else {
1904 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001905 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001906 /*Foundnonskip*/false,
1907 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001908 }
1909}
1910
1911/// HandleIfDirective - Implements the #if directive.
1912///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001913void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1914 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001915 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001916
Chris Lattner371ac8a2006-07-04 07:11:10 +00001917 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001918 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001919 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001920
1921 // Should we include the stuff contained by this directive?
1922 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001923 // If this condition is equivalent to #ifndef X, and if this is the first
1924 // directive seen, handle it for the multiple-include optimization.
1925 if (!ReadAnyTokensBeforeDirective &&
1926 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1927 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1928
Chris Lattner22eb9722006-06-18 05:43:12 +00001929 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001930 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001931 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001932 } else {
1933 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001934 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001935 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001936 }
1937}
1938
1939/// HandleEndifDirective - Implements the #endif directive.
1940///
Chris Lattnercb283342006-06-18 06:48:37 +00001941void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001942 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001943
Chris Lattner22eb9722006-06-18 05:43:12 +00001944 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001945 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001946
1947 PPConditionalInfo CondInfo;
1948 if (CurLexer->popConditionalLevel(CondInfo)) {
1949 // No conditionals on the stack: this is an #endif without an #if.
1950 return Diag(EndifToken, diag::err_pp_endif_without_if);
1951 }
1952
Chris Lattner371ac8a2006-07-04 07:11:10 +00001953 // If this the end of a top-level #endif, inform MIOpt.
1954 if (CurLexer->getConditionalStackDepth() == 0)
1955 CurLexer->MIOpt.ExitTopLevelConditional();
1956
Chris Lattner538d7f32006-07-20 04:31:52 +00001957 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001958 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001959}
1960
1961
Chris Lattnercb283342006-06-18 06:48:37 +00001962void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001963 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001964
Chris Lattner22eb9722006-06-18 05:43:12 +00001965 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001966 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001967
1968 PPConditionalInfo CI;
1969 if (CurLexer->popConditionalLevel(CI))
1970 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001971
1972 // If this is a top-level #else, inform the MIOpt.
1973 if (CurLexer->getConditionalStackDepth() == 0)
1974 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001975
1976 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001977 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001978
1979 // Finally, skip the rest of the contents of this block and return the first
1980 // token after it.
1981 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1982 /*FoundElse*/true);
1983}
1984
Chris Lattnercb283342006-06-18 06:48:37 +00001985void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001986 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001987
Chris Lattner22eb9722006-06-18 05:43:12 +00001988 // #elif directive in a non-skipping conditional... start skipping.
1989 // We don't care what the condition is, because we will always skip it (since
1990 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001991 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001992
1993 PPConditionalInfo CI;
1994 if (CurLexer->popConditionalLevel(CI))
1995 return Diag(ElifToken, diag::pp_err_elif_without_if);
1996
Chris Lattner371ac8a2006-07-04 07:11:10 +00001997 // If this is a top-level #elif, inform the MIOpt.
1998 if (CurLexer->getConditionalStackDepth() == 0)
1999 CurLexer->MIOpt.FoundTopLevelElse();
2000
Chris Lattner22eb9722006-06-18 05:43:12 +00002001 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002002 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002003
2004 // Finally, skip the rest of the contents of this block and return the first
2005 // token after it.
2006 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2007 /*FoundElse*/CI.FoundElse);
2008}
Chris Lattnerb8761832006-06-24 21:31:03 +00002009