blob: 1a87119609808e110cb28bc7c19cc2c2c134d240 [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"
29#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000030#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000031#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000032#include "clang/Basic/Diagnostic.h"
33#include "clang/Basic/FileManager.h"
34#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000035#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000036#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000037#include <iostream>
38using namespace llvm;
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42
Chris Lattner02dffbd2006-10-14 07:50:21 +000043Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
44 TargetInfo &target,
Chris Lattner22eb9722006-06-18 05:43:12 +000045 FileManager &FM, SourceManager &SM)
Chris Lattner02dffbd2006-10-14 07:50:21 +000046 : Diags(diags), Features(opts), Target(target), FileMgr(FM), SourceMgr(SM),
Chris Lattner22eb9722006-06-18 05:43:12 +000047 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000048 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000049 ScratchBuf = new ScratchBuffer(SourceMgr);
50
Chris Lattner22eb9722006-06-18 05:43:12 +000051 // Clear stats.
52 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
53 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000054 NumEnteredSourceFiles = 0;
55 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000056 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner3665f162006-07-04 07:26:10 +000057 MaxIncludeStackDepth = 0; NumMultiIncludeFileOptzn = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000058 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000059
Chris Lattner22eb9722006-06-18 05:43:12 +000060 // Macro expansion is enabled.
61 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000062 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000063
64 // There is no file-change handler yet.
65 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000066 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000067
Chris Lattner8ff71992006-07-06 05:17:39 +000068 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
69 // This gets unpoisoned where it is allowed.
70 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
71
Chris Lattnerb8761832006-06-24 21:31:03 +000072 // Initialize the pragma handlers.
73 PragmaHandlers = new PragmaNamespace(0);
74 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000075
76 // Initialize builtin macros like __LINE__ and friends.
77 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000078}
79
80Preprocessor::~Preprocessor() {
81 // Free any active lexers.
82 delete CurLexer;
83
Chris Lattner69772b02006-07-02 20:34:39 +000084 while (!IncludeMacroStack.empty()) {
85 delete IncludeMacroStack.back().TheLexer;
86 delete IncludeMacroStack.back().TheMacroExpander;
87 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000088 }
Chris Lattnerb8761832006-06-24 21:31:03 +000089
90 // Release pragma information.
91 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000092
93 // Delete the scratch buffer info.
94 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000095}
96
97/// getFileInfo - Return the PerFileInfo structure for the specified
98/// FileEntry.
99Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
100 if (FE->getUID() >= FileInfo.size())
101 FileInfo.resize(FE->getUID()+1);
102 return FileInfo[FE->getUID()];
103}
104
Chris Lattner87d3bec2006-10-17 03:44:32 +0000105/// AddPPKeyword - Register a preprocessor keyword like "define" "undef" or
106/// "elif".
107static void AddPPKeyword(tok::PPKeywordKind PPID,
108 const char *Name, unsigned NameLen, Preprocessor &PP) {
109 PP.getIdentifierInfo(Name, Name+NameLen)->setPPKeywordID(PPID);
110}
Chris Lattner22eb9722006-06-18 05:43:12 +0000111
Chris Lattner720f2702006-10-17 04:03:44 +0000112/// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or
113/// "property".
114static void AddObjCKeyword(tok::ObjCKeywordKind ObjCID,
115 const char *Name, unsigned NameLen,
116 Preprocessor &PP) {
117 PP.getIdentifierInfo(Name, Name+NameLen)->setObjCKeywordID(ObjCID);
118}
119
Chris Lattner22eb9722006-06-18 05:43:12 +0000120/// AddKeywords - Add all keywords to the symbol table.
121///
122void Preprocessor::AddKeywords() {
123 enum {
124 C90Shift = 0,
125 EXTC90 = 1 << C90Shift,
126 NOTC90 = 2 << C90Shift,
127 C99Shift = 2,
128 EXTC99 = 1 << C99Shift,
129 NOTC99 = 2 << C99Shift,
130 CPPShift = 4,
131 EXTCPP = 1 << CPPShift,
132 NOTCPP = 2 << CPPShift,
133 Mask = 3
134 };
135
136 // Add keywords and tokens for the current language.
137#define KEYWORD(NAME, FLAGS) \
Chris Lattner02f1f4f2006-07-29 03:52:46 +0000138 AddKeyword(#NAME, tok::kw_ ## NAME, \
Chris Lattner6d998552006-08-04 06:11:48 +0000139 ((FLAGS) >> C90Shift) & Mask, \
140 ((FLAGS) >> C99Shift) & Mask, \
141 ((FLAGS) >> CPPShift) & Mask);
Chris Lattner22eb9722006-06-18 05:43:12 +0000142#define ALIAS(NAME, TOK) \
143 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
Chris Lattner87d3bec2006-10-17 03:44:32 +0000144#define PPKEYWORD(NAME) \
145 AddPPKeyword(tok::pp_##NAME, #NAME, strlen(#NAME), *this);
Chris Lattner720f2702006-10-17 04:03:44 +0000146#define OBJC1_AT_KEYWORD(NAME) \
147 if (Features.ObjC1) \
148 AddObjCKeyword(tok::objc_##NAME, #NAME, strlen(#NAME), *this);
149#define OBJC2_AT_KEYWORD(NAME) \
150 if (Features.ObjC2) \
151 AddObjCKeyword(tok::objc_##NAME, #NAME, strlen(#NAME), *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000152#include "clang/Basic/TokenKinds.def"
153}
154
Chris Lattner87d3bec2006-10-17 03:44:32 +0000155/// AddKeyword - This method is used to associate a token ID with specific
156/// identifiers because they are language keywords. This causes the lexer to
157/// automatically map matching identifiers to specialized token codes.
158///
159/// The C90/C99/CPP flags are set to 0 if the token should be enabled in the
160/// specified langauge, set to 1 if it is an extension in the specified
161/// language, and set to 2 if disabled in the specified language.
162void Preprocessor::AddKeyword(const std::string &Keyword,
163 tok::TokenKind TokenCode,
164 int C90, int C99, int CPP) {
165 int Flags = Features.CPlusPlus ? CPP : (Features.C99 ? C99 : C90);
166
167 // Don't add this keyword if disabled in this language or if an extension
168 // and extensions are disabled.
169 if (Flags+Features.NoExtensions >= 2) return;
170
171 const char *Str = &Keyword[0];
172 IdentifierInfo &Info = *getIdentifierInfo(Str, Str+Keyword.size());
173 Info.setTokenID(TokenCode);
174 Info.setIsExtensionToken(Flags == 1);
175}
176
177
Chris Lattner22eb9722006-06-18 05:43:12 +0000178/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
179/// the specified LexerToken's location, translating the token's start
180/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000181void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000182 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000183 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000184}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000185
186void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
187 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
188 << getSpelling(Tok) << "'";
189
190 if (!DumpFlags) return;
191 std::cerr << "\t";
192 if (Tok.isAtStartOfLine())
193 std::cerr << " [StartOfLine]";
194 if (Tok.hasLeadingSpace())
195 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000196 if (Tok.isExpandDisabled())
197 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000198 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000199 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000200 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
201 << "']";
202 }
203}
204
205void Preprocessor::DumpMacro(const MacroInfo &MI) const {
206 std::cerr << "MACRO: ";
207 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
208 DumpToken(MI.getReplacementToken(i));
209 std::cerr << " ";
210 }
211 std::cerr << "\n";
212}
213
Chris Lattner22eb9722006-06-18 05:43:12 +0000214void Preprocessor::PrintStats() {
215 std::cerr << "\n*** Preprocessor Stats:\n";
216 std::cerr << FileInfo.size() << " files tracked.\n";
217 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
218 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
219 NumOnceOnlyFiles += FileInfo[i].isImport;
220 if (MaxNumIncludes < FileInfo[i].NumIncludes)
221 MaxNumIncludes = FileInfo[i].NumIncludes;
222 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
223 }
224 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
225 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
226 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
227
228 std::cerr << NumDirectives << " directives found:\n";
229 std::cerr << " " << NumDefined << " #define.\n";
230 std::cerr << " " << NumUndefined << " #undef.\n";
231 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
Chris Lattner3665f162006-07-04 07:26:10 +0000232 std::cerr << " " << NumMultiIncludeFileOptzn << " #includes skipped due to"
233 << " the multi-include optimization.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000234 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
235 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
236 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
237 std::cerr << " " << NumElse << " #else/#elif.\n";
238 std::cerr << " " << NumEndif << " #endif.\n";
239 std::cerr << " " << NumPragma << " #pragma.\n";
240 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
241
Chris Lattner78186052006-07-09 00:45:31 +0000242 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
243 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000244 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000245 std::cerr << (NumFastTokenPaste+NumTokenPaste)
246 << " token paste (##) operations performed, "
247 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000248}
249
250//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000251// Token Spelling
252//===----------------------------------------------------------------------===//
253
254
255/// getSpelling() - Return the 'spelling' of this token. The spelling of a
256/// token are the characters used to represent the token in the source file
257/// after trigraph expansion and escaped-newline folding. In particular, this
258/// wants to get the true, uncanonicalized, spelling of things like digraphs
259/// UCNs, etc.
260std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
261 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
262
263 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000264 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000265 if (!Tok.needsCleaning())
266 return std::string(TokStart, TokStart+Tok.getLength());
267
Chris Lattnerd01e2912006-06-18 16:22:51 +0000268 std::string Result;
269 Result.reserve(Tok.getLength());
270
Chris Lattneref9eae12006-07-04 22:33:12 +0000271 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000272 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
273 Ptr != End; ) {
274 unsigned CharSize;
275 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
276 Ptr += CharSize;
277 }
278 assert(Result.size() != unsigned(Tok.getLength()) &&
279 "NeedsCleaning flag set on something that didn't need cleaning!");
280 return Result;
281}
282
283/// getSpelling - This method is used to get the spelling of a token into a
284/// preallocated buffer, instead of as an std::string. The caller is required
285/// to allocate enough space for the token, which is guaranteed to be at least
286/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000287///
288/// Note that this method may do two possible things: it may either fill in
289/// the buffer specified with characters, or it may *change the input pointer*
290/// to point to a constant buffer with the data already in it (avoiding a
291/// copy). The caller is not allowed to modify the returned buffer pointer
292/// if an internal buffer is returned.
293unsigned Preprocessor::getSpelling(const LexerToken &Tok,
294 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000295 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
296
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000297 // If this token is an identifier, just return the string from the identifier
298 // table, which is very quick.
299 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
300 Buffer = II->getName();
301 return Tok.getLength();
302 }
303
304 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000305 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000306
307 // If this token contains nothing interesting, return it directly.
308 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000309 Buffer = TokStart;
310 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000311 }
312 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000313 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000314 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
315 Ptr != End; ) {
316 unsigned CharSize;
317 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
318 Ptr += CharSize;
319 }
320 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
321 "NeedsCleaning flag set on something that didn't need cleaning!");
322
323 return OutBuf-Buffer;
324}
325
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000326
327/// CreateString - Plop the specified string into a scratch buffer and return a
328/// location for it. If specified, the source location provides a source
329/// location for the token.
330SourceLocation Preprocessor::
331CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
332 if (SLoc.isValid())
333 return ScratchBuf->getToken(Buf, Len, SLoc);
334 return ScratchBuf->getToken(Buf, Len);
335}
336
337
Chris Lattnerd01e2912006-06-18 16:22:51 +0000338//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000339// Source File Location Methods.
340//===----------------------------------------------------------------------===//
341
342
343/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
344/// return null on failure. isAngled indicates whether the file reference is
345/// for system #include's or not (i.e. using <> instead of "").
346const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000347 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000348 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000349 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000350 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000351 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000352
353 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000354 // FIXME: Portability. This should be a sys::Path interface, this doesn't
355 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000356 if (Filename[0] == '/') {
357 // If this was an #include_next "/absolute/file", fail.
358 if (FromDir) return 0;
359
360 // Otherwise, just return the file.
361 return FileMgr.getFile(Filename);
362 }
363
364 // Step #0, unless disabled, check to see if the file is in the #includer's
365 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000366 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000367 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
368 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000369 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000370 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000371 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000372 if (const FileEntry *FE =
373 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000374 if (CurDirLookup)
375 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000376 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000377 CurDir = 0;
378
379 // This file is a system header or C++ unfriendly if the old file is.
380 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000381 return FE;
382 }
383 }
384 }
385
386 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000387 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000388
389 // If this is a #include_next request, start searching after the directory the
390 // file was found in.
391 if (FromDir)
392 i = FromDir-&SearchDirs[0];
393
394 // Check each directory in sequence to see if it contains this file.
395 for (; i != SearchDirs.size(); ++i) {
396 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000397 // FIXME: Portability. Adding file to dir should be in sys::Path.
398 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
399 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000400 CurDir = &SearchDirs[i];
401
402 // This file is a system header or C++ unfriendly if the dir is.
403 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000404 return FE;
405 }
406 }
407
408 // Otherwise, didn't find it.
409 return 0;
410}
411
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000412/// isInPrimaryFile - Return true if we're in the top-level file, not in a
413/// #include.
414bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000415 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000416 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000417
Chris Lattner13044d92006-07-03 05:16:44 +0000418 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000419 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000420 if (IncludeMacroStack[i].TheLexer &&
421 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
422 return IncludeMacroStack[i].TheLexer->isMainFile();
423 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000424}
425
426/// getCurrentLexer - Return the current file lexer being lexed from. Note
427/// that this ignores any potentially active macro expansions and _Pragma
428/// expansions going on at the time.
429Lexer *Preprocessor::getCurrentFileLexer() const {
430 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
431
432 // Look for a stacked lexer.
433 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000434 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000435 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
436 return L;
437 }
438 return 0;
439}
440
441
Chris Lattner22eb9722006-06-18 05:43:12 +0000442/// EnterSourceFile - Add a source file to the top of the include stack and
443/// start lexing tokens from it instead of the current buffer. Return true
444/// on failure.
445void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000446 const DirectoryLookup *CurDir,
447 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000448 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000449 ++NumEnteredSourceFiles;
450
Chris Lattner69772b02006-07-02 20:34:39 +0000451 if (MaxIncludeStackDepth < IncludeMacroStack.size())
452 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000453
Chris Lattner22eb9722006-06-18 05:43:12 +0000454 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000455 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000456 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000457 EnterSourceFileWithLexer(TheLexer, CurDir);
458}
Chris Lattner22eb9722006-06-18 05:43:12 +0000459
Chris Lattner69772b02006-07-02 20:34:39 +0000460/// EnterSourceFile - Add a source file to the top of the include stack and
461/// start lexing tokens from it instead of the current buffer.
462void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
463 const DirectoryLookup *CurDir) {
464
465 // Add the current lexer to the include stack.
466 if (CurLexer || CurMacroExpander)
467 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
468 CurMacroExpander));
469
470 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000471 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000472 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000473
474 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000475 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000476 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
477
478 // Get the file entry for the current file.
479 if (const FileEntry *FE =
480 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
481 FileType = getFileInfo(FE).DirInfo;
482
Chris Lattner1840e492006-07-02 22:30:01 +0000483 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000484 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000485 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000486}
487
Chris Lattner69772b02006-07-02 20:34:39 +0000488
489
Chris Lattner22eb9722006-06-18 05:43:12 +0000490/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000491/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000492void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000493 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000494 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
495 CurMacroExpander));
496 CurLexer = 0;
497 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000498
Chris Lattneree8760b2006-07-15 07:42:55 +0000499 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000500}
501
Chris Lattner7667d0d2006-07-16 18:16:58 +0000502/// EnterTokenStream - Add a "macro" context to the top of the include stack,
503/// which will cause the lexer to start returning the specified tokens. Note
504/// that these tokens will be re-macro-expanded when/if expansion is enabled.
505/// This method assumes that the specified stream of tokens has a permanent
506/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000507void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000508 // Save our current state.
509 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
510 CurMacroExpander));
511 CurLexer = 0;
512 CurDirLookup = 0;
513
514 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000515 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000516}
517
518/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
519/// lexer stack. This should only be used in situations where the current
520/// state of the top-of-stack lexer is known.
521void Preprocessor::RemoveTopOfLexerStack() {
522 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
523 delete CurLexer;
524 delete CurMacroExpander;
525 CurLexer = IncludeMacroStack.back().TheLexer;
526 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
527 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
528 IncludeMacroStack.pop_back();
529}
530
Chris Lattner22eb9722006-06-18 05:43:12 +0000531//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000532// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000533//===----------------------------------------------------------------------===//
534
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000535/// RegisterBuiltinMacro - Register the specified identifier in the identifier
536/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000537IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000538 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000539 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000540
541 // Mark it as being a macro that is builtin.
542 MacroInfo *MI = new MacroInfo(SourceLocation());
543 MI->setIsBuiltinMacro();
544 Id->setMacroInfo(MI);
545 return Id;
546}
547
548
Chris Lattner677757a2006-06-28 05:26:32 +0000549/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
550/// identifier table.
551void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000552 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000553 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000554 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
555 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000556 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000557
558 // GCC Extensions.
559 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
560 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000561 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000562}
563
Chris Lattnerc2395832006-07-09 00:57:04 +0000564/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
565/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000566static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
567 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000568 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
569
570 // If the token isn't an identifier, it's always literally expanded.
571 if (II == 0) return true;
572
573 // If the identifier is a macro, and if that macro is enabled, it may be
574 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000575 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
576 // Fast expanding "#define X X" is ok, because X would be disabled.
577 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000578 return false;
579
580 // If this is an object-like macro invocation, it is safe to trivially expand
581 // it.
582 if (MI->isObjectLike()) return true;
583
584 // If this is a function-like macro invocation, it's safe to trivially expand
585 // as long as the identifier is not a macro argument.
586 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
587 I != E; ++I)
588 if (*I == II)
589 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000590
Chris Lattnerc2395832006-07-09 00:57:04 +0000591 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000592}
593
Chris Lattnerc2395832006-07-09 00:57:04 +0000594
Chris Lattnerafe603f2006-07-11 04:02:46 +0000595/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
596/// lexed is a '('. If so, consume the token and return true, if not, this
597/// method should have no observable side-effect on the lexed tokens.
598bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000599 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000600 unsigned Val;
601 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000602 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000603 else
604 Val = CurMacroExpander->isNextTokenLParen();
605
606 if (Val == 2) {
607 // If we ran off the end of the lexer or macro expander, walk the include
608 // stack, looking for whatever will return the next token.
609 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
610 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
611 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000612 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000613 else
614 Val = Entry.TheMacroExpander->isNextTokenLParen();
615 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000616 }
617
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000618 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
619 // have found something that isn't a '(' or we found the end of the
620 // translation unit. In either case, return false.
621 if (Val != 1)
622 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000623
624 LexerToken Tok;
625 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000626 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
627 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000628}
Chris Lattner677757a2006-06-28 05:26:32 +0000629
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000630/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
631/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000632bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000633 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000634
635 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
636 if (MI->isBuiltinMacro()) {
637 ExpandBuiltinMacro(Identifier);
638 return false;
639 }
640
Chris Lattner81278c62006-10-14 19:03:49 +0000641 // If this is the first use of a target-specific macro, warn about it.
642 if (MI->isTargetSpecific()) {
643 MI->setIsTargetSpecific(false); // Don't warn on second use.
644 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
645 diag::port_target_macro_use);
646 }
647
Chris Lattneree8760b2006-07-15 07:42:55 +0000648 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000649 /// for each macro argument, the list of tokens that were provided to the
650 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000651 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000652
653 // If this is a function-like macro, read the arguments.
654 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000655 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
656 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000657 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000658 return true;
659
Chris Lattner78186052006-07-09 00:45:31 +0000660 // Remember that we are now parsing the arguments to a macro invocation.
661 // Preprocessor directives used inside macro arguments are not portable, and
662 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000663 InMacroArgs = true;
664 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000665
666 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000667 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000668
669 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000670 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000671
672 ++NumFnMacroExpanded;
673 } else {
674 ++NumMacroExpanded;
675 }
Chris Lattner13044d92006-07-03 05:16:44 +0000676
677 // Notice that this macro has been used.
678 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000679
680 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000681
682 // If this macro expands to no tokens, don't bother to push it onto the
683 // expansion stack, only to take it right back off.
684 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000685 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000686 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000687
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000688 // Ignore this macro use, just return the next token in the current
689 // buffer.
690 bool HadLeadingSpace = Identifier.hasLeadingSpace();
691 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
692
693 Lex(Identifier);
694
695 // If the identifier isn't on some OTHER line, inherit the leading
696 // whitespace/first-on-a-line property of this token. This handles
697 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
698 // empty.
699 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000700 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
701 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000702 }
703 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000704 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000705
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000706 } else if (MI->getNumTokens() == 1 &&
707 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000708 // Otherwise, if this macro expands into a single trivially-expanded
709 // token: expand it now. This handles common cases like
710 // "#define VAL 42".
711
712 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
713 // identifier to the expanded token.
714 bool isAtStartOfLine = Identifier.isAtStartOfLine();
715 bool hasLeadingSpace = Identifier.hasLeadingSpace();
716
717 // Remember where the token is instantiated.
718 SourceLocation InstantiateLoc = Identifier.getLocation();
719
720 // Replace the result token.
721 Identifier = MI->getReplacementToken(0);
722
723 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000724 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
725 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000726
727 // Update the tokens location to include both its logical and physical
728 // locations.
729 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000730 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000731 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000732
Chris Lattner6e4bf522006-07-27 06:59:25 +0000733 // If this is #define X X, we must mark the result as unexpandible.
734 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
735 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000736 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000737
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000738 // Since this is not an identifier token, it can't be macro expanded, so
739 // we're done.
740 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000741 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000742 }
743
Chris Lattner78186052006-07-09 00:45:31 +0000744 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000745 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000746
747 // Now that the macro is at the top of the include stack, ask the
748 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000749 Lex(Identifier);
750 return false;
751}
752
Chris Lattneree8760b2006-07-15 07:42:55 +0000753/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000754/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000755/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000756MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
757 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000758 // The number of fixed arguments to parse.
759 unsigned NumFixedArgsLeft = MI->getNumArgs();
760 bool isVariadic = MI->isVariadic();
761
Chris Lattner78186052006-07-09 00:45:31 +0000762 // Outer loop, while there are more arguments, keep reading them.
763 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000764 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000765 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000766
767 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000768 // argument is separated by an EOF token. Use a SmallVector so we can avoid
769 // heap allocations in the common case.
770 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000771
772 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000773 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000774 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
775 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000776
Chris Lattner78186052006-07-09 00:45:31 +0000777 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000778 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
779 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000780 LexUnexpandedToken(Tok);
781
782 if (Tok.getKind() == tok::eof) {
783 Diag(MacroName, diag::err_unterm_macro_invoc);
784 // Do not lose the EOF. Return it to the client.
785 MacroName = Tok;
786 return 0;
787 } else if (Tok.getKind() == tok::r_paren) {
788 // If we found the ) token, the macro arg list is done.
789 if (NumParens-- == 0)
790 break;
791 } else if (Tok.getKind() == tok::l_paren) {
792 ++NumParens;
793 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
794 // Comma ends this argument if there are more fixed arguments expected.
795 if (NumFixedArgsLeft)
796 break;
797
Chris Lattner2ada5d32006-07-15 07:51:24 +0000798 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000799 if (!isVariadic) {
800 // Emit the diagnostic at the macro name in case there is a missing ).
801 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000802 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000803 return 0;
804 }
805 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000806 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
807 // If this is a comment token in the argument list and we're just in
808 // -C mode (not -CC mode), discard the comment.
809 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000810 }
811
812 ArgTokens.push_back(Tok);
813 }
814
Chris Lattnera12dd152006-07-11 04:09:02 +0000815 // Empty arguments are standard in C99 and supported as an extension in
816 // other modes.
817 if (ArgTokens.empty() && !Features.C99)
818 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000819
Chris Lattner36b6e812006-07-21 06:38:30 +0000820 // Add a marker EOF token to the end of the token list for this argument.
821 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000822 EOFTok.startToken();
823 EOFTok.setKind(tok::eof);
824 EOFTok.setLocation(Tok.getLocation());
825 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000826 ArgTokens.push_back(EOFTok);
827 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000828 --NumFixedArgsLeft;
829 };
830
831 // Okay, we either found the r_paren. Check to see if we parsed too few
832 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000833 unsigned MinArgsExpected = MI->getNumArgs();
834
Chris Lattner775d8322006-07-29 04:39:41 +0000835 // See MacroArgs instance var for description of this.
836 bool isVarargsElided = false;
837
Chris Lattner2ada5d32006-07-15 07:51:24 +0000838 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000839 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000840 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000841 // Varargs where the named vararg parameter is missing: ok as extension.
842 // #define A(x, ...)
843 // A("blah")
844 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000845
846 // Remember this occurred if this is a C99 macro invocation with at least
847 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000848 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000849 } else if (MI->getNumArgs() == 1) {
850 // #define A(x)
851 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000852 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000853
854 // Empty arguments are standard in C99 and supported as an extension in
855 // other modes.
856 if (ArgTokens.empty() && !Features.C99)
857 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000858 } else {
859 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000860 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000861 return 0;
862 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000863
864 // Add a marker EOF token to the end of the token list for this argument.
865 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000866 Tok.startToken();
867 Tok.setKind(tok::eof);
868 Tok.setLocation(EndLoc);
869 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000870 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000871 }
872
Chris Lattner775d8322006-07-29 04:39:41 +0000873 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000874}
875
Chris Lattnerc673f902006-06-30 06:10:41 +0000876/// ComputeDATE_TIME - Compute the current time, enter it into the specified
877/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
878/// the identifier tokens inserted.
879static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000880 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000881 time_t TT = time(0);
882 struct tm *TM = localtime(&TT);
883
884 static const char * const Months[] = {
885 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
886 };
887
888 char TmpBuffer[100];
889 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
890 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000891 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000892
893 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000894 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000895}
896
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000897/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
898/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000899void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000900 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000901 IdentifierInfo *II = Tok.getIdentifierInfo();
902 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000903
904 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
905 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000906 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000907 return Handle_Pragma(Tok);
908
Chris Lattner78186052006-07-09 00:45:31 +0000909 ++NumBuiltinMacroExpanded;
910
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000911 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000912
913 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000914 Tok.setIdentifierInfo(0);
915 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000916
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000917 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000918 // __LINE__ expands to a simple numeric value.
919 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
920 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000921 Tok.setKind(tok::numeric_constant);
922 Tok.setLength(Length);
923 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000924 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000925 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000926 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000927 Diag(Tok, diag::ext_pp_base_file);
928 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
929 while (NextLoc.getFileID() != 0) {
930 Loc = NextLoc;
931 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
932 }
933 }
934
Chris Lattner0766e592006-07-03 01:07:01 +0000935 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
936 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000937 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000938 Tok.setKind(tok::string_literal);
939 Tok.setLength(FN.size());
940 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000941 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000942 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000943 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000944 Tok.setKind(tok::string_literal);
945 Tok.setLength(strlen("\"Mmm dd yyyy\""));
946 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000947 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000948 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000949 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000950 Tok.setKind(tok::string_literal);
951 Tok.setLength(strlen("\"hh:mm:ss\""));
952 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000953 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000954 Diag(Tok, diag::ext_pp_include_level);
955
956 // Compute the include depth of this token.
957 unsigned Depth = 0;
958 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
959 for (; Loc.getFileID() != 0; ++Depth)
960 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
961
962 // __INCLUDE_LEVEL__ expands to a simple numeric value.
963 sprintf(TmpBuffer, "%u", Depth);
964 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000965 Tok.setKind(tok::numeric_constant);
966 Tok.setLength(Length);
967 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000968 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000969 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
970 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
971 Diag(Tok, diag::ext_pp_timestamp);
972
973 // Get the file that we are lexing out of. If we're currently lexing from
974 // a macro, dig into the include stack.
975 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000976 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000977
978 if (TheLexer)
979 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
980
981 // If this file is older than the file it depends on, emit a diagnostic.
982 const char *Result;
983 if (CurFile) {
984 time_t TT = CurFile->getModificationTime();
985 struct tm *TM = localtime(&TT);
986 Result = asctime(TM);
987 } else {
988 Result = "??? ??? ?? ??:??:?? ????\n";
989 }
990 TmpBuffer[0] = '"';
991 strcpy(TmpBuffer+1, Result);
992 unsigned Len = strlen(TmpBuffer);
993 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000994 Tok.setKind(tok::string_literal);
995 Tok.setLength(Len);
996 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000997 } else {
998 assert(0 && "Unknown identifier!");
999 }
1000}
Chris Lattner677757a2006-06-28 05:26:32 +00001001
Chris Lattner13044d92006-07-03 05:16:44 +00001002namespace {
1003struct UnusedIdentifierReporter : public IdentifierVisitor {
1004 Preprocessor &PP;
1005 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
1006
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001007 void VisitIdentifier(IdentifierInfo &II) const {
1008 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1009 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +00001010 }
1011};
1012}
1013
Chris Lattner677757a2006-06-28 05:26:32 +00001014//===----------------------------------------------------------------------===//
1015// Lexer Event Handling.
1016//===----------------------------------------------------------------------===//
1017
Chris Lattnercefc7682006-07-08 08:28:12 +00001018/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1019/// identifier information for the token and install it into the token.
1020IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
1021 const char *BufPtr) {
1022 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
1023 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1024
1025 // Look up this token, see if it is a macro, or if it is a language keyword.
1026 IdentifierInfo *II;
1027 if (BufPtr && !Identifier.needsCleaning()) {
1028 // No cleaning needed, just use the characters from the lexed buffer.
1029 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1030 } else {
1031 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
1032 const char *TmpBuf = (char*)alloca(Identifier.getLength());
1033 unsigned Size = getSpelling(Identifier, TmpBuf);
1034 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1035 }
Chris Lattner8c204872006-10-14 05:19:21 +00001036 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001037 return II;
1038}
1039
1040
Chris Lattner677757a2006-06-28 05:26:32 +00001041/// HandleIdentifier - This callback is invoked when the lexer reads an
1042/// identifier. This callback looks up the identifier in the map and/or
1043/// potentially macro expands it or turns it into a named token (like 'for').
1044void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001045 assert(Identifier.getIdentifierInfo() &&
1046 "Can't handle identifiers without identifier info!");
1047
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001048 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001049
1050 // If this identifier was poisoned, and if it was not produced from a macro
1051 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001052 if (II.isPoisoned() && CurLexer) {
1053 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1054 Diag(Identifier, diag::err_pp_used_poisoned_id);
1055 else
1056 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1057 }
Chris Lattner677757a2006-06-28 05:26:32 +00001058
Chris Lattner78186052006-07-09 00:45:31 +00001059 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +00001060 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001061 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1062 if (MI->isEnabled()) {
1063 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1064 return;
1065 } else {
1066 // C99 6.10.3.4p2 says that a disabled macro may never again be
1067 // expanded, even if it's in a context where it could be expanded in the
1068 // future.
Chris Lattner8c204872006-10-14 05:19:21 +00001069 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001070 }
1071 }
Chris Lattner063400e2006-10-14 19:54:15 +00001072 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1073 // If this identifier is a macro on some other target, emit a diagnostic.
1074 // This diagnosic is only emitted when macro expansion is enabled, because
1075 // the macro would not have been expanded for the other target either.
1076 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1077 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1078 diag::port_target_macro_use);
1079
1080 }
Chris Lattner677757a2006-06-28 05:26:32 +00001081
1082 // Change the kind of this identifier to the appropriate token kind, e.g.
1083 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001084 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001085
1086 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001087 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001088}
1089
Chris Lattner22eb9722006-06-18 05:43:12 +00001090/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1091/// the current file. This either returns the EOF token or pops a level off
1092/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001093bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001094 assert(!CurMacroExpander &&
1095 "Ending a file when currently in a macro!");
1096
Chris Lattner371ac8a2006-07-04 07:11:10 +00001097 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001098 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001099 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001100 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001101 // Okay, this has a controlling macro, remember in PerFileInfo.
1102 if (const FileEntry *FE =
1103 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1104 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001105 }
1106 }
1107
Chris Lattner22eb9722006-06-18 05:43:12 +00001108 // If this is a #include'd file, pop it off the include stack and continue
1109 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001110 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001111 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001112 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001113
1114 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001115 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001116 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1117
1118 // Get the file entry for the current file.
1119 if (const FileEntry *FE =
1120 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1121 FileType = getFileInfo(FE).DirInfo;
1122
Chris Lattner0c885f52006-06-21 06:50:18 +00001123 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001124 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001125 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001126
1127 // Client should lex another token.
1128 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001129 }
1130
Chris Lattner8c204872006-10-14 05:19:21 +00001131 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001132 CurLexer->BufferPtr = CurLexer->BufferEnd;
1133 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001134 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001135
1136 // We're done with the #included file.
1137 delete CurLexer;
1138 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001139
Chris Lattner03f83482006-07-10 06:16:26 +00001140 // This is the end of the top-level file. If the diag::pp_macro_not_used
1141 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1142 // have not been used.
1143 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1144 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001145
1146 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001147}
1148
1149/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001150/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001151bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 assert(CurMacroExpander && !CurLexer &&
1153 "Ending a macro when currently in a #include file!");
1154
Chris Lattner22eb9722006-06-18 05:43:12 +00001155 delete CurMacroExpander;
1156
Chris Lattner69772b02006-07-02 20:34:39 +00001157 // Handle this like a #include file being popped off the stack.
1158 CurMacroExpander = 0;
1159 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001160}
1161
1162
1163//===----------------------------------------------------------------------===//
1164// Utility Methods for Preprocessor Directive Handling.
1165//===----------------------------------------------------------------------===//
1166
1167/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1168/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001169void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001170 LexerToken Tmp;
1171 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001172 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001173 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001174}
1175
1176/// ReadMacroName - Lex and validate a macro name, which occurs after a
1177/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001178/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1179/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001180/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001181void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001182 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001183 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001184
1185 // Missing macro name?
1186 if (MacroNameTok.getKind() == tok::eom)
1187 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1188
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001189 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1190 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001191 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001192 // Fall through on error.
1193 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001194 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001195
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001196 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1197 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001198 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001199 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001200 } else if (isDefineUndef && II->getMacroInfo() &&
1201 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001202 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001203 if (isDefineUndef == 1)
1204 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1205 else
1206 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001207 } else {
1208 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001209 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001210 }
1211
Chris Lattner22eb9722006-06-18 05:43:12 +00001212 // Invalid macro name, read and discard the rest of the line. Then set the
1213 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001214 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001215 return DiscardUntilEndOfDirective();
1216}
1217
1218/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1219/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001220void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001221 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001222 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001223 // There should be no tokens after the directive, but we allow them as an
1224 // extension.
1225 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001226 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1227 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001228 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001229}
1230
1231
1232
1233/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1234/// decided that the subsequent tokens are in the #if'd out portion of the
1235/// file. Lex the rest of the file, until we see an #endif. If
1236/// FoundNonSkipPortion is true, then we have already emitted code for part of
1237/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1238/// is true, then #else directives are ok, if not, then we have already seen one
1239/// so a #else directive is a duplicate. When this returns, the caller can lex
1240/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001241void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001242 bool FoundNonSkipPortion,
1243 bool FoundElse) {
1244 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001245 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001246 "Lexing a macro, not a file?");
1247
1248 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1249 FoundNonSkipPortion, FoundElse);
1250
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001251 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1252 // disabling warnings, etc.
1253 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001254 LexerToken Tok;
1255 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001256 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001257
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001258 // If this is the end of the buffer, we have an error.
1259 if (Tok.getKind() == tok::eof) {
1260 // Emit errors for each unterminated conditional on the stack, including
1261 // the current one.
1262 while (!CurLexer->ConditionalStack.empty()) {
1263 Diag(CurLexer->ConditionalStack.back().IfLoc,
1264 diag::err_pp_unterminated_conditional);
1265 CurLexer->ConditionalStack.pop_back();
1266 }
1267
1268 // Just return and let the caller lex after this #include.
1269 break;
1270 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001271
1272 // If this token is not a preprocessor directive, just skip it.
1273 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1274 continue;
1275
1276 // We just parsed a # character at the start of a line, so we're in
1277 // directive mode. Tell the lexer this so any newlines we see will be
1278 // converted into an EOM token (this terminates the macro).
1279 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001280 CurLexer->KeepCommentMode = false;
1281
Chris Lattner22eb9722006-06-18 05:43:12 +00001282
1283 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001284 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001285
1286 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1287 // something bogus), skip it.
1288 if (Tok.getKind() != tok::identifier) {
1289 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001290 // Restore comment saving mode.
1291 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001292 continue;
1293 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001294
Chris Lattner22eb9722006-06-18 05:43:12 +00001295 // If the first letter isn't i or e, it isn't intesting to us. We know that
1296 // this is safe in the face of spelling differences, because there is no way
1297 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001298 // allows us to avoid looking up the identifier info for #define/#undef and
1299 // other common directives.
1300 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1301 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001302 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1303 FirstChar != 'i' && FirstChar != 'e') {
1304 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001305 // Restore comment saving mode.
1306 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001307 continue;
1308 }
1309
Chris Lattnere60165f2006-06-22 06:36:29 +00001310 // Get the identifier name without trigraphs or embedded newlines. Note
1311 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1312 // when skipping.
1313 // TODO: could do this with zero copies in the no-clean case by using
1314 // strncmp below.
1315 char Directive[20];
1316 unsigned IdLen;
1317 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1318 IdLen = Tok.getLength();
1319 memcpy(Directive, RawCharData, IdLen);
1320 Directive[IdLen] = 0;
1321 } else {
1322 std::string DirectiveStr = getSpelling(Tok);
1323 IdLen = DirectiveStr.size();
1324 if (IdLen >= 20) {
1325 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001326 // Restore comment saving mode.
1327 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001328 continue;
1329 }
1330 memcpy(Directive, &DirectiveStr[0], IdLen);
1331 Directive[IdLen] = 0;
1332 }
1333
Chris Lattner22eb9722006-06-18 05:43:12 +00001334 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001335 if ((IdLen == 2) || // "if"
1336 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1337 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001338 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1339 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001340 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001341 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001342 /*foundnonskip*/false,
1343 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001344 }
1345 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001346 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001347 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001348 PPConditionalInfo CondInfo;
1349 CondInfo.WasSkipping = true; // Silence bogus warning.
1350 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1351 assert(!InCond && "Can't be skipping if not in a conditional!");
1352
1353 // If we popped the outermost skipping block, we're done skipping!
1354 if (!CondInfo.WasSkipping)
1355 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001356 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001357 // #else directive in a skipping conditional. If not in some other
1358 // skipping conditional, and if #else hasn't already been seen, enter it
1359 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001360 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001361 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1362
1363 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001364 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001365
1366 // Note that we've seen a #else in this conditional.
1367 CondInfo.FoundElse = true;
1368
1369 // If the conditional is at the top level, and the #if block wasn't
1370 // entered, enter the #else block now.
1371 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1372 CondInfo.FoundNonSkip = true;
1373 break;
1374 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001375 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001376 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1377
1378 bool ShouldEnter;
1379 // If this is in a skipping block or if we're already handled this #if
1380 // block, don't bother parsing the condition.
1381 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001382 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001383 ShouldEnter = false;
1384 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001385 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001386 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001387 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1388 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001389 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001390 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001391 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001392 }
1393
1394 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001395 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001396
1397 // If this condition is true, enter it!
1398 if (ShouldEnter) {
1399 CondInfo.FoundNonSkip = true;
1400 break;
1401 }
1402 }
1403 }
1404
1405 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001406 // Restore comment saving mode.
1407 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001408 }
1409
1410 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1411 // of the file, just stop skipping and return to lexing whatever came after
1412 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001413 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001414}
1415
1416//===----------------------------------------------------------------------===//
1417// Preprocessor Directive Handling.
1418//===----------------------------------------------------------------------===//
1419
1420/// HandleDirective - This callback is invoked when the lexer sees a # token
1421/// at the start of a line. This consumes the directive, modifies the
1422/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1423/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001424void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001425 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001426
1427 // We just parsed a # character at the start of a line, so we're in directive
1428 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001429 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001430 CurLexer->ParsingPreprocessorDirective = true;
1431
1432 ++NumDirectives;
1433
Chris Lattner371ac8a2006-07-04 07:11:10 +00001434 // We are about to read a token. For the multiple-include optimization FA to
1435 // work, we have to remember if we had read any tokens *before* this
1436 // pp-directive.
1437 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1438
Chris Lattner78186052006-07-09 00:45:31 +00001439 // Read the next token, the directive flavor. This isn't expanded due to
1440 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001441 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001442
Chris Lattner78186052006-07-09 00:45:31 +00001443 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1444 // #define A(x) #x
1445 // A(abc
1446 // #warning blah
1447 // def)
1448 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001449 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001450 Diag(Result, diag::ext_embedded_directive);
1451
Chris Lattner22eb9722006-06-18 05:43:12 +00001452 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001453 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001454 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001455
Chris Lattner22eb9722006-06-18 05:43:12 +00001456 case tok::numeric_constant:
1457 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001458 DiscardUntilEndOfDirective();
1459 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001460 default:
1461 IdentifierInfo *II = Result.getIdentifierInfo();
1462 if (II == 0) break; // Not an identifier.
1463
1464 // Ask what the preprocessor keyword ID is.
1465 switch (II->getPPKeywordID()) {
1466 default: break;
1467 // C99 6.10.1 - Conditional Inclusion.
1468 case tok::pp_if:
1469 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1470 case tok::pp_ifdef:
1471 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1472 case tok::pp_ifndef:
1473 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1474 case tok::pp_elif:
1475 return HandleElifDirective(Result);
1476 case tok::pp_else:
1477 return HandleElseDirective(Result);
1478 case tok::pp_endif:
1479 return HandleEndifDirective(Result);
1480
1481 // C99 6.10.2 - Source File Inclusion.
1482 case tok::pp_include:
1483 return HandleIncludeDirective(Result); // Handle #include.
1484
1485 // C99 6.10.3 - Macro Replacement.
1486 case tok::pp_define:
1487 return HandleDefineDirective(Result, false);
1488 case tok::pp_undef:
1489 return HandleUndefDirective(Result);
1490
1491 // C99 6.10.4 - Line Control.
1492 case tok::pp_line:
1493 // FIXME: implement #line
1494 DiscardUntilEndOfDirective();
1495 return;
1496
1497 // C99 6.10.5 - Error Directive.
1498 case tok::pp_error:
1499 return HandleUserDiagnosticDirective(Result, false);
1500
1501 // C99 6.10.6 - Pragma Directive.
1502 case tok::pp_pragma:
1503 return HandlePragmaDirective();
1504
1505 // GNU Extensions.
1506 case tok::pp_import:
1507 return HandleImportDirective(Result);
1508 case tok::pp_include_next:
1509 return HandleIncludeNextDirective(Result);
1510
1511 case tok::pp_warning:
1512 Diag(Result, diag::ext_pp_warning_directive);
1513 return HandleUserDiagnosticDirective(Result, true);
1514 case tok::pp_ident:
1515 return HandleIdentSCCSDirective(Result);
1516 case tok::pp_sccs:
1517 return HandleIdentSCCSDirective(Result);
1518 case tok::pp_assert:
1519 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001520 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001521 case tok::pp_unassert:
1522 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001523 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001524
1525 // clang extensions.
1526 case tok::pp_define_target:
1527 return HandleDefineDirective(Result, true);
1528 case tok::pp_define_other_target:
1529 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001530 }
1531 break;
1532 }
1533
1534 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001535 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001536
1537 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001538 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001539
1540 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001541}
1542
Chris Lattner01d66cc2006-07-03 22:16:27 +00001543void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001544 bool isWarning) {
1545 // Read the rest of the line raw. We do this because we don't want macros
1546 // to be expanded and we don't require that the tokens be valid preprocessing
1547 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1548 // collapse multiple consequtive white space between tokens, but this isn't
1549 // specified by the standard.
1550 std::string Message = CurLexer->ReadToEndOfLine();
1551
1552 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001553 return Diag(Tok, DiagID, Message);
1554}
1555
1556/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1557///
1558void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001559 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001560 Diag(Tok, diag::ext_pp_ident_directive);
1561
Chris Lattner371ac8a2006-07-04 07:11:10 +00001562 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001563 LexerToken StrTok;
1564 Lex(StrTok);
1565
1566 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001567 if (StrTok.getKind() != tok::string_literal &&
1568 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001569 return Diag(StrTok, diag::err_pp_malformed_ident);
1570
1571 // Verify that there is nothing after the string, other than EOM.
1572 CheckEndOfDirective("#ident");
1573
1574 if (IdentHandler)
1575 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001576}
1577
Chris Lattnerb8761832006-06-24 21:31:03 +00001578//===----------------------------------------------------------------------===//
1579// Preprocessor Include Directive Handling.
1580//===----------------------------------------------------------------------===//
1581
Chris Lattner22eb9722006-06-18 05:43:12 +00001582/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1583/// file to be included from the lexer, then include it! This is a common
1584/// routine with functionality shared between #include, #include_next and
1585/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001586void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001587 const DirectoryLookup *LookupFrom,
1588 bool isImport) {
1589 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001590
Chris Lattner22eb9722006-06-18 05:43:12 +00001591 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001592 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001593
1594 // If the token kind is EOM, the error has already been diagnosed.
1595 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001596 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001597
1598 // Verify that there is nothing after the filename, other than EOM. Use the
1599 // preprocessor to lex this in case lexing the filename entered a macro.
1600 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001601
1602 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001603 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001604 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1605
Chris Lattner269c2322006-06-25 06:23:00 +00001606 // Find out whether the filename is <x> or "x".
1607 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001608
1609 // Remove the quotes.
1610 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1611
Chris Lattner22eb9722006-06-18 05:43:12 +00001612 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001613 const DirectoryLookup *CurDir;
1614 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001615 if (File == 0)
1616 return Diag(FilenameTok, diag::err_pp_file_not_found);
1617
1618 // Get information about this file.
1619 PerFileInfo &FileInfo = getFileInfo(File);
1620
1621 // If this is a #import directive, check that we have not already imported
1622 // this header.
1623 if (isImport) {
1624 // If this has already been imported, don't import it again.
1625 FileInfo.isImport = true;
1626
1627 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001628 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001629 } else {
1630 // Otherwise, if this is a #include of a file that was previously #import'd
1631 // or if this is the second #include of a #pragma once file, ignore it.
1632 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001633 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001634 }
Chris Lattner3665f162006-07-04 07:26:10 +00001635
1636 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1637 // if the macro that guards it is defined, we know the #include has no effect.
1638 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1639 ++NumMultiIncludeFileOptzn;
1640 return;
1641 }
1642
Chris Lattner22eb9722006-06-18 05:43:12 +00001643
1644 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001645 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001646 if (FileID == 0)
1647 return Diag(FilenameTok, diag::err_pp_file_not_found);
1648
1649 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001650 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001651
1652 // Increment the number of times this file has been included.
1653 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001654}
1655
1656/// HandleIncludeNextDirective - Implements #include_next.
1657///
Chris Lattnercb283342006-06-18 06:48:37 +00001658void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1659 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001660
1661 // #include_next is like #include, except that we start searching after
1662 // the current found directory. If we can't do this, issue a
1663 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001664 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001665 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001666 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001667 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001668 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001669 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001670 } else {
1671 // Start looking up in the next directory.
1672 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001673 }
1674
1675 return HandleIncludeDirective(IncludeNextTok, Lookup);
1676}
1677
1678/// HandleImportDirective - Implements #import.
1679///
Chris Lattnercb283342006-06-18 06:48:37 +00001680void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1681 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001682
1683 return HandleIncludeDirective(ImportTok, 0, true);
1684}
1685
Chris Lattnerb8761832006-06-24 21:31:03 +00001686//===----------------------------------------------------------------------===//
1687// Preprocessor Macro Directive Handling.
1688//===----------------------------------------------------------------------===//
1689
Chris Lattnercefc7682006-07-08 08:28:12 +00001690/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1691/// definition has just been read. Lex the rest of the arguments and the
1692/// closing ), updating MI with what we learn. Return true if an error occurs
1693/// parsing the arg list.
1694bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1695 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001696 while (1) {
1697 LexUnexpandedToken(Tok);
1698 switch (Tok.getKind()) {
1699 case tok::r_paren:
1700 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001701 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001702 // Otherwise we have #define FOO(A,)
1703 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1704 return true;
1705 case tok::ellipsis: // #define X(... -> C99 varargs
1706 // Warn if use of C99 feature in non-C99 mode.
1707 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1708
1709 // Lex the token after the identifier.
1710 LexUnexpandedToken(Tok);
1711 if (Tok.getKind() != tok::r_paren) {
1712 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1713 return true;
1714 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001715 // Add the __VA_ARGS__ identifier as an argument.
1716 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001717 MI->setIsC99Varargs();
1718 return false;
1719 case tok::eom: // #define X(
1720 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1721 return true;
1722 default: // #define X(1
1723 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1724 return true;
1725 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001726 IdentifierInfo *II = Tok.getIdentifierInfo();
1727
1728 // If this is already used as an argument, it is used multiple times (e.g.
1729 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001730 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001731 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1732 return true;
1733 }
1734
1735 // Add the argument to the macro info.
1736 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001737
1738 // Lex the token after the identifier.
1739 LexUnexpandedToken(Tok);
1740
1741 switch (Tok.getKind()) {
1742 default: // #define X(A B
1743 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1744 return true;
1745 case tok::r_paren: // #define X(A)
1746 return false;
1747 case tok::comma: // #define X(A,
1748 break;
1749 case tok::ellipsis: // #define X(A... -> GCC extension
1750 // Diagnose extension.
1751 Diag(Tok, diag::ext_named_variadic_macro);
1752
1753 // Lex the token after the identifier.
1754 LexUnexpandedToken(Tok);
1755 if (Tok.getKind() != tok::r_paren) {
1756 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1757 return true;
1758 }
1759
1760 MI->setIsGNUVarargs();
1761 return false;
1762 }
1763 }
1764 }
1765}
1766
Chris Lattner22eb9722006-06-18 05:43:12 +00001767/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001768/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1769/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001770///
Chris Lattner81278c62006-10-14 19:03:49 +00001771void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1772 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001773 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001774
Chris Lattner22eb9722006-06-18 05:43:12 +00001775 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001776 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001777
1778 // Error reading macro name? If so, diagnostic already issued.
1779 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001780 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001781
Chris Lattner457fc152006-07-29 06:30:25 +00001782 // If we are supposed to keep comments in #defines, reenable comment saving
1783 // mode.
1784 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1785
Chris Lattner063400e2006-10-14 19:54:15 +00001786 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001787 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001788 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001789
Chris Lattner063400e2006-10-14 19:54:15 +00001790 // If the identifier is an 'other target' macro, clear this bit.
1791 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1792
1793
Chris Lattner22eb9722006-06-18 05:43:12 +00001794 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001795 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001796
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001797 // If this is a function-like macro definition, parse the argument list,
1798 // marking each of the identifiers as being used as macro arguments. Also,
1799 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001800 if (Tok.getKind() == tok::eom) {
1801 // If there is no body to this macro, we have no special handling here.
1802 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001803 // This is a function-like macro definition. Read the argument list.
1804 MI->setIsFunctionLike();
1805 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001806 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001807 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001808 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001809 if (CurLexer->ParsingPreprocessorDirective)
1810 DiscardUntilEndOfDirective();
1811 return;
1812 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001813
Chris Lattner815a1f92006-07-08 20:48:04 +00001814 // Read the first token after the arg list for down below.
1815 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001816 } else if (!Tok.hasLeadingSpace()) {
1817 // C99 requires whitespace between the macro definition and the body. Emit
1818 // a diagnostic for something like "#define X+".
1819 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001820 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001821 } else {
1822 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1823 // one in some cases!
1824 }
1825 } else {
1826 // This is a normal token with leading space. Clear the leading space
1827 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001828 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001829 }
1830
Chris Lattner7e374832006-07-29 03:46:57 +00001831 // If this is a definition of a variadic C99 function-like macro, not using
1832 // the GNU named varargs extension, enabled __VA_ARGS__.
1833
1834 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1835 // This gets unpoisoned where it is allowed.
1836 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1837 if (MI->isC99Varargs())
1838 Ident__VA_ARGS__->setIsPoisoned(false);
1839
Chris Lattner22eb9722006-06-18 05:43:12 +00001840 // Read the rest of the macro body.
1841 while (Tok.getKind() != tok::eom) {
1842 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001843
1844 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001845 // parameters in function-like macro expansions.
1846 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001847 // Get the next token of the macro.
1848 LexUnexpandedToken(Tok);
1849 continue;
1850 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001851
Chris Lattner815a1f92006-07-08 20:48:04 +00001852 // Get the next token of the macro.
1853 LexUnexpandedToken(Tok);
1854
1855 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001856 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001857 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001858 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001859 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001860
1861 // Disable __VA_ARGS__ again.
1862 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001863 return;
1864 }
1865
1866 // Things look ok, add the param name token to the macro.
1867 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001868
Chris Lattner22eb9722006-06-18 05:43:12 +00001869 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001870 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001871 }
Chris Lattner7e374832006-07-29 03:46:57 +00001872
1873 // Disable __VA_ARGS__ again.
1874 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001875
Chris Lattnerbff18d52006-07-06 04:49:18 +00001876 // Check that there is no paste (##) operator at the begining or end of the
1877 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001878 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001879 if (NumTokens != 0) {
1880 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001881 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001882 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001883 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001884 }
1885 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001886 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001887 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001888 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001889 }
1890 }
1891
Chris Lattner13044d92006-07-03 05:16:44 +00001892 // If this is the primary source file, remember that this macro hasn't been
1893 // used yet.
1894 if (isInPrimaryFile())
1895 MI->setIsUsed(false);
1896
Chris Lattner22eb9722006-06-18 05:43:12 +00001897 // Finally, if this identifier already had a macro defined for it, verify that
1898 // the macro bodies are identical and free the old definition.
1899 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001900 if (!OtherMI->isUsed())
1901 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1902
Chris Lattner22eb9722006-06-18 05:43:12 +00001903 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001904 // must be the same. C99 6.10.3.2.
1905 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001906 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1907 MacroNameTok.getIdentifierInfo()->getName());
1908 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1909 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001910 delete OtherMI;
1911 }
1912
1913 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001914}
1915
Chris Lattner063400e2006-10-14 19:54:15 +00001916/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1917void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1918 LexerToken MacroNameTok;
1919 ReadMacroName(MacroNameTok, 1);
1920
1921 // Error reading macro name? If so, diagnostic already issued.
1922 if (MacroNameTok.getKind() == tok::eom)
1923 return;
1924
1925 // Check to see if this is the last token on the #undef line.
1926 CheckEndOfDirective("#define_other_target");
1927
1928 // If there is already a macro defined by this name, turn it into a
1929 // target-specific define.
1930 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1931 MI->setIsTargetSpecific(true);
1932 return;
1933 }
1934
1935 // Mark the identifier as being a macro on some other target.
1936 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1937}
1938
Chris Lattner22eb9722006-06-18 05:43:12 +00001939
1940/// HandleUndefDirective - Implements #undef.
1941///
Chris Lattnercb283342006-06-18 06:48:37 +00001942void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001943 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001944
Chris Lattner22eb9722006-06-18 05:43:12 +00001945 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001946 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001947
1948 // Error reading macro name? If so, diagnostic already issued.
1949 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001950 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001951
1952 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001953 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001954
1955 // Okay, we finally have a valid identifier to undef.
1956 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1957
Chris Lattner063400e2006-10-14 19:54:15 +00001958 // #undef untaints an identifier if it were marked by define_other_target.
1959 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1960
Chris Lattner22eb9722006-06-18 05:43:12 +00001961 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001962 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001963
Chris Lattner13044d92006-07-03 05:16:44 +00001964 if (!MI->isUsed())
1965 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001966
1967 // Free macro definition.
1968 delete MI;
1969 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001970}
1971
1972
Chris Lattnerb8761832006-06-24 21:31:03 +00001973//===----------------------------------------------------------------------===//
1974// Preprocessor Conditional Directive Handling.
1975//===----------------------------------------------------------------------===//
1976
Chris Lattner22eb9722006-06-18 05:43:12 +00001977/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001978/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1979/// if any tokens have been returned or pp-directives activated before this
1980/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001981///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001982void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1983 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001984 ++NumIf;
1985 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001986
Chris Lattner22eb9722006-06-18 05:43:12 +00001987 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001988 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001989
1990 // Error reading macro name? If so, diagnostic already issued.
1991 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001992 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001993
1994 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001995 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1996
1997 // If the start of a top-level #ifdef, inform MIOpt.
1998 if (!ReadAnyTokensBeforeDirective &&
1999 CurLexer->getConditionalStackDepth() == 0) {
2000 assert(isIfndef && "#ifdef shouldn't reach here");
2001 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2002 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002003
Chris Lattner063400e2006-10-14 19:54:15 +00002004 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2005 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00002006
Chris Lattner81278c62006-10-14 19:03:49 +00002007 // If there is a macro, process it.
2008 if (MI) {
2009 // Mark it used.
2010 MI->setIsUsed(true);
2011
2012 // If this is the first use of a target-specific macro, warn about it.
2013 if (MI->isTargetSpecific()) {
2014 MI->setIsTargetSpecific(false); // Don't warn on second use.
2015 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2016 diag::port_target_macro_use);
2017 }
Chris Lattner063400e2006-10-14 19:54:15 +00002018 } else {
2019 // Use of a target-specific macro for some other target? If so, warn.
2020 if (MII->isOtherTargetMacro()) {
2021 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2022 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2023 diag::port_target_macro_use);
2024 }
Chris Lattner81278c62006-10-14 19:03:49 +00002025 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002026
Chris Lattner22eb9722006-06-18 05:43:12 +00002027 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002028 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002029 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002030 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002031 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002032 } else {
2033 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002034 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002035 /*Foundnonskip*/false,
2036 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002037 }
2038}
2039
2040/// HandleIfDirective - Implements the #if directive.
2041///
Chris Lattnera8654ca2006-07-04 17:42:08 +00002042void Preprocessor::HandleIfDirective(LexerToken &IfToken,
2043 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002044 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002045
Chris Lattner371ac8a2006-07-04 07:11:10 +00002046 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002047 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002048 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002049
2050 // Should we include the stuff contained by this directive?
2051 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002052 // If this condition is equivalent to #ifndef X, and if this is the first
2053 // directive seen, handle it for the multiple-include optimization.
2054 if (!ReadAnyTokensBeforeDirective &&
2055 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2056 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2057
Chris Lattner22eb9722006-06-18 05:43:12 +00002058 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002059 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002060 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002061 } else {
2062 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002063 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002064 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002065 }
2066}
2067
2068/// HandleEndifDirective - Implements the #endif directive.
2069///
Chris Lattnercb283342006-06-18 06:48:37 +00002070void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002071 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002072
Chris Lattner22eb9722006-06-18 05:43:12 +00002073 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002074 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002075
2076 PPConditionalInfo CondInfo;
2077 if (CurLexer->popConditionalLevel(CondInfo)) {
2078 // No conditionals on the stack: this is an #endif without an #if.
2079 return Diag(EndifToken, diag::err_pp_endif_without_if);
2080 }
2081
Chris Lattner371ac8a2006-07-04 07:11:10 +00002082 // If this the end of a top-level #endif, inform MIOpt.
2083 if (CurLexer->getConditionalStackDepth() == 0)
2084 CurLexer->MIOpt.ExitTopLevelConditional();
2085
Chris Lattner538d7f32006-07-20 04:31:52 +00002086 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002087 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002088}
2089
2090
Chris Lattnercb283342006-06-18 06:48:37 +00002091void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002092 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002093
Chris Lattner22eb9722006-06-18 05:43:12 +00002094 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002095 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002096
2097 PPConditionalInfo CI;
2098 if (CurLexer->popConditionalLevel(CI))
2099 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002100
2101 // If this is a top-level #else, inform the MIOpt.
2102 if (CurLexer->getConditionalStackDepth() == 0)
2103 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002104
2105 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002106 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002107
2108 // Finally, skip the rest of the contents of this block and return the first
2109 // token after it.
2110 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2111 /*FoundElse*/true);
2112}
2113
Chris Lattnercb283342006-06-18 06:48:37 +00002114void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002115 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002116
Chris Lattner22eb9722006-06-18 05:43:12 +00002117 // #elif directive in a non-skipping conditional... start skipping.
2118 // We don't care what the condition is, because we will always skip it (since
2119 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002120 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002121
2122 PPConditionalInfo CI;
2123 if (CurLexer->popConditionalLevel(CI))
2124 return Diag(ElifToken, diag::pp_err_elif_without_if);
2125
Chris Lattner371ac8a2006-07-04 07:11:10 +00002126 // If this is a top-level #elif, inform the MIOpt.
2127 if (CurLexer->getConditionalStackDepth() == 0)
2128 CurLexer->MIOpt.FoundTopLevelElse();
2129
Chris Lattner22eb9722006-06-18 05:43:12 +00002130 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002131 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002132
2133 // Finally, skip the rest of the contents of this block and return the first
2134 // token after it.
2135 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2136 /*FoundElse*/CI.FoundElse);
2137}
Chris Lattnerb8761832006-06-24 21:31:03 +00002138