blob: 35afb3e91a0c8d51e5d30d04570c6bd4f099522f [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 Lattner59a9ebd2006-10-18 05:34:33 +000045 FileManager &FM, SourceManager &SM,
46 HeaderSearch &Headers)
Chris Lattner02dffbd2006-10-14 07:50:21 +000047 : Diags(diags), Features(opts), Target(target), FileMgr(FM), SourceMgr(SM),
Chris Lattner59a9ebd2006-10-18 05:34:33 +000048 HeaderInfo(Headers),
Chris Lattnerc8997182006-06-22 05:52:16 +000049 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000050 ScratchBuf = new ScratchBuffer(SourceMgr);
51
Chris Lattner22eb9722006-06-18 05:43:12 +000052 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000053 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000054 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000055 NumEnteredSourceFiles = 0;
56 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000057 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000058 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000059 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000060
Chris Lattner22eb9722006-06-18 05:43:12 +000061 // Macro expansion is enabled.
62 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000063 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000064
65 // There is no file-change handler yet.
66 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000067 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000068
Chris Lattner8ff71992006-07-06 05:17:39 +000069 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
70 // This gets unpoisoned where it is allowed.
71 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
72
Chris Lattnerb8761832006-06-24 21:31:03 +000073 // Initialize the pragma handlers.
74 PragmaHandlers = new PragmaNamespace(0);
75 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000076
77 // Initialize builtin macros like __LINE__ and friends.
78 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000079}
80
81Preprocessor::~Preprocessor() {
82 // Free any active lexers.
83 delete CurLexer;
84
Chris Lattner69772b02006-07-02 20:34:39 +000085 while (!IncludeMacroStack.empty()) {
86 delete IncludeMacroStack.back().TheLexer;
87 delete IncludeMacroStack.back().TheMacroExpander;
88 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000089 }
Chris Lattnerb8761832006-06-24 21:31:03 +000090
91 // Release pragma information.
92 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000093
94 // Delete the scratch buffer info.
95 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000096}
97
Chris Lattner87d3bec2006-10-17 03:44:32 +000098/// AddPPKeyword - Register a preprocessor keyword like "define" "undef" or
99/// "elif".
100static void AddPPKeyword(tok::PPKeywordKind PPID,
101 const char *Name, unsigned NameLen, Preprocessor &PP) {
102 PP.getIdentifierInfo(Name, Name+NameLen)->setPPKeywordID(PPID);
103}
Chris Lattner22eb9722006-06-18 05:43:12 +0000104
Chris Lattner720f2702006-10-17 04:03:44 +0000105/// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or
106/// "property".
107static void AddObjCKeyword(tok::ObjCKeywordKind ObjCID,
108 const char *Name, unsigned NameLen,
109 Preprocessor &PP) {
110 PP.getIdentifierInfo(Name, Name+NameLen)->setObjCKeywordID(ObjCID);
111}
112
Chris Lattner22eb9722006-06-18 05:43:12 +0000113/// AddKeywords - Add all keywords to the symbol table.
114///
115void Preprocessor::AddKeywords() {
116 enum {
117 C90Shift = 0,
118 EXTC90 = 1 << C90Shift,
119 NOTC90 = 2 << C90Shift,
120 C99Shift = 2,
121 EXTC99 = 1 << C99Shift,
122 NOTC99 = 2 << C99Shift,
123 CPPShift = 4,
124 EXTCPP = 1 << CPPShift,
125 NOTCPP = 2 << CPPShift,
126 Mask = 3
127 };
128
129 // Add keywords and tokens for the current language.
130#define KEYWORD(NAME, FLAGS) \
Chris Lattner02f1f4f2006-07-29 03:52:46 +0000131 AddKeyword(#NAME, tok::kw_ ## NAME, \
Chris Lattner6d998552006-08-04 06:11:48 +0000132 ((FLAGS) >> C90Shift) & Mask, \
133 ((FLAGS) >> C99Shift) & Mask, \
134 ((FLAGS) >> CPPShift) & Mask);
Chris Lattner22eb9722006-06-18 05:43:12 +0000135#define ALIAS(NAME, TOK) \
136 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
Chris Lattner87d3bec2006-10-17 03:44:32 +0000137#define PPKEYWORD(NAME) \
138 AddPPKeyword(tok::pp_##NAME, #NAME, strlen(#NAME), *this);
Chris Lattner720f2702006-10-17 04:03:44 +0000139#define OBJC1_AT_KEYWORD(NAME) \
140 if (Features.ObjC1) \
141 AddObjCKeyword(tok::objc_##NAME, #NAME, strlen(#NAME), *this);
142#define OBJC2_AT_KEYWORD(NAME) \
143 if (Features.ObjC2) \
144 AddObjCKeyword(tok::objc_##NAME, #NAME, strlen(#NAME), *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000145#include "clang/Basic/TokenKinds.def"
146}
147
Chris Lattner87d3bec2006-10-17 03:44:32 +0000148/// AddKeyword - This method is used to associate a token ID with specific
149/// identifiers because they are language keywords. This causes the lexer to
150/// automatically map matching identifiers to specialized token codes.
151///
152/// The C90/C99/CPP flags are set to 0 if the token should be enabled in the
153/// specified langauge, set to 1 if it is an extension in the specified
154/// language, and set to 2 if disabled in the specified language.
155void Preprocessor::AddKeyword(const std::string &Keyword,
156 tok::TokenKind TokenCode,
157 int C90, int C99, int CPP) {
158 int Flags = Features.CPlusPlus ? CPP : (Features.C99 ? C99 : C90);
159
160 // Don't add this keyword if disabled in this language or if an extension
161 // and extensions are disabled.
162 if (Flags+Features.NoExtensions >= 2) return;
163
164 const char *Str = &Keyword[0];
165 IdentifierInfo &Info = *getIdentifierInfo(Str, Str+Keyword.size());
166 Info.setTokenID(TokenCode);
167 Info.setIsExtensionToken(Flags == 1);
168}
169
170
Chris Lattner22eb9722006-06-18 05:43:12 +0000171/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
172/// the specified LexerToken's location, translating the token's start
173/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000174void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000175 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000176 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000177}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000178
179void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
180 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
181 << getSpelling(Tok) << "'";
182
183 if (!DumpFlags) return;
184 std::cerr << "\t";
185 if (Tok.isAtStartOfLine())
186 std::cerr << " [StartOfLine]";
187 if (Tok.hasLeadingSpace())
188 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000189 if (Tok.isExpandDisabled())
190 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000191 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000192 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000193 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
194 << "']";
195 }
196}
197
198void Preprocessor::DumpMacro(const MacroInfo &MI) const {
199 std::cerr << "MACRO: ";
200 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
201 DumpToken(MI.getReplacementToken(i));
202 std::cerr << " ";
203 }
204 std::cerr << "\n";
205}
206
Chris Lattner22eb9722006-06-18 05:43:12 +0000207void Preprocessor::PrintStats() {
208 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000209 std::cerr << NumDirectives << " directives found:\n";
210 std::cerr << " " << NumDefined << " #define.\n";
211 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000212 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000213 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
214 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
215 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
216 std::cerr << " " << NumElse << " #else/#elif.\n";
217 std::cerr << " " << NumEndif << " #endif.\n";
218 std::cerr << " " << NumPragma << " #pragma.\n";
219 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
220
Chris Lattner78186052006-07-09 00:45:31 +0000221 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
222 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000223 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000224 std::cerr << (NumFastTokenPaste+NumTokenPaste)
225 << " token paste (##) operations performed, "
226 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000227}
228
229//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000230// Token Spelling
231//===----------------------------------------------------------------------===//
232
233
234/// getSpelling() - Return the 'spelling' of this token. The spelling of a
235/// token are the characters used to represent the token in the source file
236/// after trigraph expansion and escaped-newline folding. In particular, this
237/// wants to get the true, uncanonicalized, spelling of things like digraphs
238/// UCNs, etc.
239std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
240 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
241
242 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000243 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000244 if (!Tok.needsCleaning())
245 return std::string(TokStart, TokStart+Tok.getLength());
246
Chris Lattnerd01e2912006-06-18 16:22:51 +0000247 std::string Result;
248 Result.reserve(Tok.getLength());
249
Chris Lattneref9eae12006-07-04 22:33:12 +0000250 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000251 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
252 Ptr != End; ) {
253 unsigned CharSize;
254 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
255 Ptr += CharSize;
256 }
257 assert(Result.size() != unsigned(Tok.getLength()) &&
258 "NeedsCleaning flag set on something that didn't need cleaning!");
259 return Result;
260}
261
262/// getSpelling - This method is used to get the spelling of a token into a
263/// preallocated buffer, instead of as an std::string. The caller is required
264/// to allocate enough space for the token, which is guaranteed to be at least
265/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000266///
267/// Note that this method may do two possible things: it may either fill in
268/// the buffer specified with characters, or it may *change the input pointer*
269/// to point to a constant buffer with the data already in it (avoiding a
270/// copy). The caller is not allowed to modify the returned buffer pointer
271/// if an internal buffer is returned.
272unsigned Preprocessor::getSpelling(const LexerToken &Tok,
273 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000274 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
275
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000276 // If this token is an identifier, just return the string from the identifier
277 // table, which is very quick.
278 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
279 Buffer = II->getName();
280 return Tok.getLength();
281 }
282
283 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000284 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000285
286 // If this token contains nothing interesting, return it directly.
287 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000288 Buffer = TokStart;
289 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000290 }
291 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000292 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000293 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
294 Ptr != End; ) {
295 unsigned CharSize;
296 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
297 Ptr += CharSize;
298 }
299 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
300 "NeedsCleaning flag set on something that didn't need cleaning!");
301
302 return OutBuf-Buffer;
303}
304
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000305
306/// CreateString - Plop the specified string into a scratch buffer and return a
307/// location for it. If specified, the source location provides a source
308/// location for the token.
309SourceLocation Preprocessor::
310CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
311 if (SLoc.isValid())
312 return ScratchBuf->getToken(Buf, Len, SLoc);
313 return ScratchBuf->getToken(Buf, Len);
314}
315
316
Chris Lattnerd01e2912006-06-18 16:22:51 +0000317//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000318// Source File Location Methods.
319//===----------------------------------------------------------------------===//
320
321
322/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
323/// return null on failure. isAngled indicates whether the file reference is
324/// for system #include's or not (i.e. using <> instead of "").
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000325const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000326 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000327 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000328 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000329 // If the header lookup mechanism may be relative to the current file, pass in
330 // info about where the current file is.
331 const FileEntry *CurFileEnt = 0;
332 if (!isAngled && !FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000333 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000334 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000335 }
336
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000337 CurDir = CurDirLookup;
338 return HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner22eb9722006-06-18 05:43:12 +0000339}
340
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000341/// isInPrimaryFile - Return true if we're in the top-level file, not in a
342/// #include.
343bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000344 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000345 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000346
Chris Lattner13044d92006-07-03 05:16:44 +0000347 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000348 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000349 if (IncludeMacroStack[i].TheLexer &&
350 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
351 return IncludeMacroStack[i].TheLexer->isMainFile();
352 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000353}
354
355/// getCurrentLexer - Return the current file lexer being lexed from. Note
356/// that this ignores any potentially active macro expansions and _Pragma
357/// expansions going on at the time.
358Lexer *Preprocessor::getCurrentFileLexer() const {
359 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
360
361 // Look for a stacked lexer.
362 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000363 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000364 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
365 return L;
366 }
367 return 0;
368}
369
370
Chris Lattner22eb9722006-06-18 05:43:12 +0000371/// EnterSourceFile - Add a source file to the top of the include stack and
372/// start lexing tokens from it instead of the current buffer. Return true
373/// on failure.
374void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000375 const DirectoryLookup *CurDir,
376 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000377 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000378 ++NumEnteredSourceFiles;
379
Chris Lattner69772b02006-07-02 20:34:39 +0000380 if (MaxIncludeStackDepth < IncludeMacroStack.size())
381 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000382
Chris Lattner22eb9722006-06-18 05:43:12 +0000383 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000384 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000385 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000386 EnterSourceFileWithLexer(TheLexer, CurDir);
387}
Chris Lattner22eb9722006-06-18 05:43:12 +0000388
Chris Lattner69772b02006-07-02 20:34:39 +0000389/// EnterSourceFile - Add a source file to the top of the include stack and
390/// start lexing tokens from it instead of the current buffer.
391void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
392 const DirectoryLookup *CurDir) {
393
394 // Add the current lexer to the include stack.
395 if (CurLexer || CurMacroExpander)
396 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
397 CurMacroExpander));
398
399 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000400 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000401 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000402
403 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000404 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000405 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
406
407 // Get the file entry for the current file.
408 if (const FileEntry *FE =
409 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000410 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000411
Chris Lattner1840e492006-07-02 22:30:01 +0000412 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000413 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000414 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000415}
416
Chris Lattner69772b02006-07-02 20:34:39 +0000417
418
Chris Lattner22eb9722006-06-18 05:43:12 +0000419/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000420/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000421void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000422 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
423 CurMacroExpander));
424 CurLexer = 0;
425 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000426
Chris Lattneree8760b2006-07-15 07:42:55 +0000427 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000428}
429
Chris Lattner7667d0d2006-07-16 18:16:58 +0000430/// EnterTokenStream - Add a "macro" context to the top of the include stack,
431/// which will cause the lexer to start returning the specified tokens. Note
432/// that these tokens will be re-macro-expanded when/if expansion is enabled.
433/// This method assumes that the specified stream of tokens has a permanent
434/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000435void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000436 // Save our current state.
437 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
438 CurMacroExpander));
439 CurLexer = 0;
440 CurDirLookup = 0;
441
442 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000443 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000444}
445
446/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
447/// lexer stack. This should only be used in situations where the current
448/// state of the top-of-stack lexer is known.
449void Preprocessor::RemoveTopOfLexerStack() {
450 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
451 delete CurLexer;
452 delete CurMacroExpander;
453 CurLexer = IncludeMacroStack.back().TheLexer;
454 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
455 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
456 IncludeMacroStack.pop_back();
457}
458
Chris Lattner22eb9722006-06-18 05:43:12 +0000459//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000460// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000461//===----------------------------------------------------------------------===//
462
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000463/// RegisterBuiltinMacro - Register the specified identifier in the identifier
464/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000465IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000466 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000467 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000468
469 // Mark it as being a macro that is builtin.
470 MacroInfo *MI = new MacroInfo(SourceLocation());
471 MI->setIsBuiltinMacro();
472 Id->setMacroInfo(MI);
473 return Id;
474}
475
476
Chris Lattner677757a2006-06-28 05:26:32 +0000477/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
478/// identifier table.
479void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000480 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000481 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000482 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
483 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000484 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000485
486 // GCC Extensions.
487 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
488 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000489 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000490}
491
Chris Lattnerc2395832006-07-09 00:57:04 +0000492/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
493/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000494static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
495 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000496 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
497
498 // If the token isn't an identifier, it's always literally expanded.
499 if (II == 0) return true;
500
501 // If the identifier is a macro, and if that macro is enabled, it may be
502 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000503 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
504 // Fast expanding "#define X X" is ok, because X would be disabled.
505 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000506 return false;
507
508 // If this is an object-like macro invocation, it is safe to trivially expand
509 // it.
510 if (MI->isObjectLike()) return true;
511
512 // If this is a function-like macro invocation, it's safe to trivially expand
513 // as long as the identifier is not a macro argument.
514 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
515 I != E; ++I)
516 if (*I == II)
517 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000518
Chris Lattnerc2395832006-07-09 00:57:04 +0000519 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000520}
521
Chris Lattnerc2395832006-07-09 00:57:04 +0000522
Chris Lattnerafe603f2006-07-11 04:02:46 +0000523/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
524/// lexed is a '('. If so, consume the token and return true, if not, this
525/// method should have no observable side-effect on the lexed tokens.
526bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000527 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000528 unsigned Val;
529 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000530 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000531 else
532 Val = CurMacroExpander->isNextTokenLParen();
533
534 if (Val == 2) {
535 // If we ran off the end of the lexer or macro expander, walk the include
536 // stack, looking for whatever will return the next token.
537 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
538 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
539 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000540 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000541 else
542 Val = Entry.TheMacroExpander->isNextTokenLParen();
543 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000544 }
545
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000546 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
547 // have found something that isn't a '(' or we found the end of the
548 // translation unit. In either case, return false.
549 if (Val != 1)
550 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000551
552 LexerToken Tok;
553 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000554 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
555 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000556}
Chris Lattner677757a2006-06-28 05:26:32 +0000557
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000558/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
559/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000560bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000561 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000562
563 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
564 if (MI->isBuiltinMacro()) {
565 ExpandBuiltinMacro(Identifier);
566 return false;
567 }
568
Chris Lattner81278c62006-10-14 19:03:49 +0000569 // If this is the first use of a target-specific macro, warn about it.
570 if (MI->isTargetSpecific()) {
571 MI->setIsTargetSpecific(false); // Don't warn on second use.
572 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
573 diag::port_target_macro_use);
574 }
575
Chris Lattneree8760b2006-07-15 07:42:55 +0000576 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000577 /// for each macro argument, the list of tokens that were provided to the
578 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000579 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000580
581 // If this is a function-like macro, read the arguments.
582 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000583 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
584 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000585 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000586 return true;
587
Chris Lattner78186052006-07-09 00:45:31 +0000588 // Remember that we are now parsing the arguments to a macro invocation.
589 // Preprocessor directives used inside macro arguments are not portable, and
590 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000591 InMacroArgs = true;
592 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000593
594 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000595 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000596
597 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000598 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000599
600 ++NumFnMacroExpanded;
601 } else {
602 ++NumMacroExpanded;
603 }
Chris Lattner13044d92006-07-03 05:16:44 +0000604
605 // Notice that this macro has been used.
606 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000607
608 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000609
610 // If this macro expands to no tokens, don't bother to push it onto the
611 // expansion stack, only to take it right back off.
612 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000613 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000614 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000615
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000616 // Ignore this macro use, just return the next token in the current
617 // buffer.
618 bool HadLeadingSpace = Identifier.hasLeadingSpace();
619 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
620
621 Lex(Identifier);
622
623 // If the identifier isn't on some OTHER line, inherit the leading
624 // whitespace/first-on-a-line property of this token. This handles
625 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
626 // empty.
627 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000628 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
629 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000630 }
631 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000632 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000633
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000634 } else if (MI->getNumTokens() == 1 &&
635 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000636 // Otherwise, if this macro expands into a single trivially-expanded
637 // token: expand it now. This handles common cases like
638 // "#define VAL 42".
639
640 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
641 // identifier to the expanded token.
642 bool isAtStartOfLine = Identifier.isAtStartOfLine();
643 bool hasLeadingSpace = Identifier.hasLeadingSpace();
644
645 // Remember where the token is instantiated.
646 SourceLocation InstantiateLoc = Identifier.getLocation();
647
648 // Replace the result token.
649 Identifier = MI->getReplacementToken(0);
650
651 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000652 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
653 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000654
655 // Update the tokens location to include both its logical and physical
656 // locations.
657 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000658 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000659 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000660
Chris Lattner6e4bf522006-07-27 06:59:25 +0000661 // If this is #define X X, we must mark the result as unexpandible.
662 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
663 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000664 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000665
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000666 // Since this is not an identifier token, it can't be macro expanded, so
667 // we're done.
668 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000669 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000670 }
671
Chris Lattner78186052006-07-09 00:45:31 +0000672 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000673 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000674
675 // Now that the macro is at the top of the include stack, ask the
676 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000677 Lex(Identifier);
678 return false;
679}
680
Chris Lattneree8760b2006-07-15 07:42:55 +0000681/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000682/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000683/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000684MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
685 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000686 // The number of fixed arguments to parse.
687 unsigned NumFixedArgsLeft = MI->getNumArgs();
688 bool isVariadic = MI->isVariadic();
689
Chris Lattner78186052006-07-09 00:45:31 +0000690 // Outer loop, while there are more arguments, keep reading them.
691 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000692 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000693 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000694
695 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000696 // argument is separated by an EOF token. Use a SmallVector so we can avoid
697 // heap allocations in the common case.
698 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000699
700 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000701 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000702 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
703 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000704
Chris Lattner78186052006-07-09 00:45:31 +0000705 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000706 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
707 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000708 LexUnexpandedToken(Tok);
709
710 if (Tok.getKind() == tok::eof) {
711 Diag(MacroName, diag::err_unterm_macro_invoc);
712 // Do not lose the EOF. Return it to the client.
713 MacroName = Tok;
714 return 0;
715 } else if (Tok.getKind() == tok::r_paren) {
716 // If we found the ) token, the macro arg list is done.
717 if (NumParens-- == 0)
718 break;
719 } else if (Tok.getKind() == tok::l_paren) {
720 ++NumParens;
721 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
722 // Comma ends this argument if there are more fixed arguments expected.
723 if (NumFixedArgsLeft)
724 break;
725
Chris Lattner2ada5d32006-07-15 07:51:24 +0000726 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000727 if (!isVariadic) {
728 // Emit the diagnostic at the macro name in case there is a missing ).
729 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000730 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000731 return 0;
732 }
733 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000734 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
735 // If this is a comment token in the argument list and we're just in
736 // -C mode (not -CC mode), discard the comment.
737 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000738 }
739
740 ArgTokens.push_back(Tok);
741 }
742
Chris Lattnera12dd152006-07-11 04:09:02 +0000743 // Empty arguments are standard in C99 and supported as an extension in
744 // other modes.
745 if (ArgTokens.empty() && !Features.C99)
746 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000747
Chris Lattner36b6e812006-07-21 06:38:30 +0000748 // Add a marker EOF token to the end of the token list for this argument.
749 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000750 EOFTok.startToken();
751 EOFTok.setKind(tok::eof);
752 EOFTok.setLocation(Tok.getLocation());
753 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000754 ArgTokens.push_back(EOFTok);
755 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000756 --NumFixedArgsLeft;
757 };
758
759 // Okay, we either found the r_paren. Check to see if we parsed too few
760 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000761 unsigned MinArgsExpected = MI->getNumArgs();
762
Chris Lattner775d8322006-07-29 04:39:41 +0000763 // See MacroArgs instance var for description of this.
764 bool isVarargsElided = false;
765
Chris Lattner2ada5d32006-07-15 07:51:24 +0000766 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000767 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000768 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000769 // Varargs where the named vararg parameter is missing: ok as extension.
770 // #define A(x, ...)
771 // A("blah")
772 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000773
774 // Remember this occurred if this is a C99 macro invocation with at least
775 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000776 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000777 } else if (MI->getNumArgs() == 1) {
778 // #define A(x)
779 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000780 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000781
782 // Empty arguments are standard in C99 and supported as an extension in
783 // other modes.
784 if (ArgTokens.empty() && !Features.C99)
785 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000786 } else {
787 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000788 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000789 return 0;
790 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000791
792 // Add a marker EOF token to the end of the token list for this argument.
793 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000794 Tok.startToken();
795 Tok.setKind(tok::eof);
796 Tok.setLocation(EndLoc);
797 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000798 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000799 }
800
Chris Lattner775d8322006-07-29 04:39:41 +0000801 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000802}
803
Chris Lattnerc673f902006-06-30 06:10:41 +0000804/// ComputeDATE_TIME - Compute the current time, enter it into the specified
805/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
806/// the identifier tokens inserted.
807static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000808 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000809 time_t TT = time(0);
810 struct tm *TM = localtime(&TT);
811
812 static const char * const Months[] = {
813 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
814 };
815
816 char TmpBuffer[100];
817 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
818 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000819 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000820
821 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000822 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000823}
824
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000825/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
826/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000827void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000828 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000829 IdentifierInfo *II = Tok.getIdentifierInfo();
830 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000831
832 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
833 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000834 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000835 return Handle_Pragma(Tok);
836
Chris Lattner78186052006-07-09 00:45:31 +0000837 ++NumBuiltinMacroExpanded;
838
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000839 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000840
841 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000842 Tok.setIdentifierInfo(0);
843 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000844
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000845 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000846 // __LINE__ expands to a simple numeric value.
847 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
848 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000849 Tok.setKind(tok::numeric_constant);
850 Tok.setLength(Length);
851 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000852 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000853 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000854 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000855 Diag(Tok, diag::ext_pp_base_file);
856 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
857 while (NextLoc.getFileID() != 0) {
858 Loc = NextLoc;
859 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
860 }
861 }
862
Chris Lattner0766e592006-07-03 01:07:01 +0000863 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
864 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000865 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000866 Tok.setKind(tok::string_literal);
867 Tok.setLength(FN.size());
868 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000869 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000870 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000871 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000872 Tok.setKind(tok::string_literal);
873 Tok.setLength(strlen("\"Mmm dd yyyy\""));
874 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000875 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000876 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000877 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000878 Tok.setKind(tok::string_literal);
879 Tok.setLength(strlen("\"hh:mm:ss\""));
880 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000881 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000882 Diag(Tok, diag::ext_pp_include_level);
883
884 // Compute the include depth of this token.
885 unsigned Depth = 0;
886 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
887 for (; Loc.getFileID() != 0; ++Depth)
888 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
889
890 // __INCLUDE_LEVEL__ expands to a simple numeric value.
891 sprintf(TmpBuffer, "%u", Depth);
892 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000893 Tok.setKind(tok::numeric_constant);
894 Tok.setLength(Length);
895 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000896 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000897 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
898 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
899 Diag(Tok, diag::ext_pp_timestamp);
900
901 // Get the file that we are lexing out of. If we're currently lexing from
902 // a macro, dig into the include stack.
903 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000904 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000905
906 if (TheLexer)
907 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
908
909 // If this file is older than the file it depends on, emit a diagnostic.
910 const char *Result;
911 if (CurFile) {
912 time_t TT = CurFile->getModificationTime();
913 struct tm *TM = localtime(&TT);
914 Result = asctime(TM);
915 } else {
916 Result = "??? ??? ?? ??:??:?? ????\n";
917 }
918 TmpBuffer[0] = '"';
919 strcpy(TmpBuffer+1, Result);
920 unsigned Len = strlen(TmpBuffer);
921 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000922 Tok.setKind(tok::string_literal);
923 Tok.setLength(Len);
924 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000925 } else {
926 assert(0 && "Unknown identifier!");
927 }
928}
Chris Lattner677757a2006-06-28 05:26:32 +0000929
Chris Lattner13044d92006-07-03 05:16:44 +0000930namespace {
931struct UnusedIdentifierReporter : public IdentifierVisitor {
932 Preprocessor &PP;
933 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
934
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000935 void VisitIdentifier(IdentifierInfo &II) const {
936 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
937 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000938 }
939};
940}
941
Chris Lattner677757a2006-06-28 05:26:32 +0000942//===----------------------------------------------------------------------===//
943// Lexer Event Handling.
944//===----------------------------------------------------------------------===//
945
Chris Lattnercefc7682006-07-08 08:28:12 +0000946/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
947/// identifier information for the token and install it into the token.
948IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
949 const char *BufPtr) {
950 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
951 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
952
953 // Look up this token, see if it is a macro, or if it is a language keyword.
954 IdentifierInfo *II;
955 if (BufPtr && !Identifier.needsCleaning()) {
956 // No cleaning needed, just use the characters from the lexed buffer.
957 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
958 } else {
959 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
960 const char *TmpBuf = (char*)alloca(Identifier.getLength());
961 unsigned Size = getSpelling(Identifier, TmpBuf);
962 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
963 }
Chris Lattner8c204872006-10-14 05:19:21 +0000964 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000965 return II;
966}
967
968
Chris Lattner677757a2006-06-28 05:26:32 +0000969/// HandleIdentifier - This callback is invoked when the lexer reads an
970/// identifier. This callback looks up the identifier in the map and/or
971/// potentially macro expands it or turns it into a named token (like 'for').
972void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000973 assert(Identifier.getIdentifierInfo() &&
974 "Can't handle identifiers without identifier info!");
975
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000976 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000977
978 // If this identifier was poisoned, and if it was not produced from a macro
979 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000980 if (II.isPoisoned() && CurLexer) {
981 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
982 Diag(Identifier, diag::err_pp_used_poisoned_id);
983 else
984 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
985 }
Chris Lattner677757a2006-06-28 05:26:32 +0000986
Chris Lattner78186052006-07-09 00:45:31 +0000987 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000988 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000989 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
990 if (MI->isEnabled()) {
991 if (!HandleMacroExpandedIdentifier(Identifier, MI))
992 return;
993 } else {
994 // C99 6.10.3.4p2 says that a disabled macro may never again be
995 // expanded, even if it's in a context where it could be expanded in the
996 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000997 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000998 }
999 }
Chris Lattner063400e2006-10-14 19:54:15 +00001000 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1001 // If this identifier is a macro on some other target, emit a diagnostic.
1002 // This diagnosic is only emitted when macro expansion is enabled, because
1003 // the macro would not have been expanded for the other target either.
1004 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1005 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1006 diag::port_target_macro_use);
1007
1008 }
Chris Lattner677757a2006-06-28 05:26:32 +00001009
1010 // Change the kind of this identifier to the appropriate token kind, e.g.
1011 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001012 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001013
1014 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001015 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001016}
1017
Chris Lattner22eb9722006-06-18 05:43:12 +00001018/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1019/// the current file. This either returns the EOF token or pops a level off
1020/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001021bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001022 assert(!CurMacroExpander &&
1023 "Ending a file when currently in a macro!");
1024
Chris Lattner371ac8a2006-07-04 07:11:10 +00001025 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001026 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001027 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001028 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001029 // Okay, this has a controlling macro, remember in PerFileInfo.
1030 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001031 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1032 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001033 }
1034 }
1035
Chris Lattner22eb9722006-06-18 05:43:12 +00001036 // If this is a #include'd file, pop it off the include stack and continue
1037 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001038 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001039 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001040 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001041
1042 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001043 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001044 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1045
1046 // Get the file entry for the current file.
1047 if (const FileEntry *FE =
1048 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001049 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001050
Chris Lattner0c885f52006-06-21 06:50:18 +00001051 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001052 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001053 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001054
1055 // Client should lex another token.
1056 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001057 }
1058
Chris Lattner8c204872006-10-14 05:19:21 +00001059 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001060 CurLexer->BufferPtr = CurLexer->BufferEnd;
1061 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001062 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001063
1064 // We're done with the #included file.
1065 delete CurLexer;
1066 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001067
Chris Lattner03f83482006-07-10 06:16:26 +00001068 // This is the end of the top-level file. If the diag::pp_macro_not_used
1069 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1070 // have not been used.
1071 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1072 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001073
1074 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001075}
1076
1077/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001078/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001079bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001080 assert(CurMacroExpander && !CurLexer &&
1081 "Ending a macro when currently in a #include file!");
1082
Chris Lattner22eb9722006-06-18 05:43:12 +00001083 delete CurMacroExpander;
1084
Chris Lattner69772b02006-07-02 20:34:39 +00001085 // Handle this like a #include file being popped off the stack.
1086 CurMacroExpander = 0;
1087 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001088}
1089
1090
1091//===----------------------------------------------------------------------===//
1092// Utility Methods for Preprocessor Directive Handling.
1093//===----------------------------------------------------------------------===//
1094
1095/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1096/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001097void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001098 LexerToken Tmp;
1099 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001100 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001101 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001102}
1103
1104/// ReadMacroName - Lex and validate a macro name, which occurs after a
1105/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001106/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1107/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001108/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001109void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001110 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001111 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001112
1113 // Missing macro name?
1114 if (MacroNameTok.getKind() == tok::eom)
1115 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1116
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001117 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1118 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001119 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001120 // Fall through on error.
1121 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001122 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001123
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001124 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1125 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001126 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001127 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001128 } else if (isDefineUndef && II->getMacroInfo() &&
1129 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001130 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001131 if (isDefineUndef == 1)
1132 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1133 else
1134 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 } else {
1136 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001137 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001138 }
1139
Chris Lattner22eb9722006-06-18 05:43:12 +00001140 // Invalid macro name, read and discard the rest of the line. Then set the
1141 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001142 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001143 return DiscardUntilEndOfDirective();
1144}
1145
1146/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1147/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001148void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001149 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001150 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001151 // There should be no tokens after the directive, but we allow them as an
1152 // extension.
1153 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001154 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1155 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001156 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001157}
1158
1159
1160
1161/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1162/// decided that the subsequent tokens are in the #if'd out portion of the
1163/// file. Lex the rest of the file, until we see an #endif. If
1164/// FoundNonSkipPortion is true, then we have already emitted code for part of
1165/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1166/// is true, then #else directives are ok, if not, then we have already seen one
1167/// so a #else directive is a duplicate. When this returns, the caller can lex
1168/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001169void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001170 bool FoundNonSkipPortion,
1171 bool FoundElse) {
1172 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001173 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001174 "Lexing a macro, not a file?");
1175
1176 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1177 FoundNonSkipPortion, FoundElse);
1178
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001179 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1180 // disabling warnings, etc.
1181 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001182 LexerToken Tok;
1183 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001184 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001185
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001186 // If this is the end of the buffer, we have an error.
1187 if (Tok.getKind() == tok::eof) {
1188 // Emit errors for each unterminated conditional on the stack, including
1189 // the current one.
1190 while (!CurLexer->ConditionalStack.empty()) {
1191 Diag(CurLexer->ConditionalStack.back().IfLoc,
1192 diag::err_pp_unterminated_conditional);
1193 CurLexer->ConditionalStack.pop_back();
1194 }
1195
1196 // Just return and let the caller lex after this #include.
1197 break;
1198 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001199
1200 // If this token is not a preprocessor directive, just skip it.
1201 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1202 continue;
1203
1204 // We just parsed a # character at the start of a line, so we're in
1205 // directive mode. Tell the lexer this so any newlines we see will be
1206 // converted into an EOM token (this terminates the macro).
1207 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001208 CurLexer->KeepCommentMode = false;
1209
Chris Lattner22eb9722006-06-18 05:43:12 +00001210
1211 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001212 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001213
1214 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1215 // something bogus), skip it.
1216 if (Tok.getKind() != tok::identifier) {
1217 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001218 // Restore comment saving mode.
1219 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001220 continue;
1221 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001222
Chris Lattner22eb9722006-06-18 05:43:12 +00001223 // If the first letter isn't i or e, it isn't intesting to us. We know that
1224 // this is safe in the face of spelling differences, because there is no way
1225 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001226 // allows us to avoid looking up the identifier info for #define/#undef and
1227 // other common directives.
1228 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1229 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001230 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1231 FirstChar != 'i' && FirstChar != 'e') {
1232 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001233 // Restore comment saving mode.
1234 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001235 continue;
1236 }
1237
Chris Lattnere60165f2006-06-22 06:36:29 +00001238 // Get the identifier name without trigraphs or embedded newlines. Note
1239 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1240 // when skipping.
1241 // TODO: could do this with zero copies in the no-clean case by using
1242 // strncmp below.
1243 char Directive[20];
1244 unsigned IdLen;
1245 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1246 IdLen = Tok.getLength();
1247 memcpy(Directive, RawCharData, IdLen);
1248 Directive[IdLen] = 0;
1249 } else {
1250 std::string DirectiveStr = getSpelling(Tok);
1251 IdLen = DirectiveStr.size();
1252 if (IdLen >= 20) {
1253 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001254 // Restore comment saving mode.
1255 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001256 continue;
1257 }
1258 memcpy(Directive, &DirectiveStr[0], IdLen);
1259 Directive[IdLen] = 0;
1260 }
1261
Chris Lattner22eb9722006-06-18 05:43:12 +00001262 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001263 if ((IdLen == 2) || // "if"
1264 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1265 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001266 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1267 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001268 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001269 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001270 /*foundnonskip*/false,
1271 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001272 }
1273 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001274 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001275 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001276 PPConditionalInfo CondInfo;
1277 CondInfo.WasSkipping = true; // Silence bogus warning.
1278 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1279 assert(!InCond && "Can't be skipping if not in a conditional!");
1280
1281 // If we popped the outermost skipping block, we're done skipping!
1282 if (!CondInfo.WasSkipping)
1283 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001284 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001285 // #else directive in a skipping conditional. If not in some other
1286 // skipping conditional, and if #else hasn't already been seen, enter it
1287 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001288 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001289 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1290
1291 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001292 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001293
1294 // Note that we've seen a #else in this conditional.
1295 CondInfo.FoundElse = true;
1296
1297 // If the conditional is at the top level, and the #if block wasn't
1298 // entered, enter the #else block now.
1299 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1300 CondInfo.FoundNonSkip = true;
1301 break;
1302 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001303 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001304 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1305
1306 bool ShouldEnter;
1307 // If this is in a skipping block or if we're already handled this #if
1308 // block, don't bother parsing the condition.
1309 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001310 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001311 ShouldEnter = false;
1312 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001313 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001314 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001315 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1316 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001317 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001318 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001319 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001320 }
1321
1322 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001323 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001324
1325 // If this condition is true, enter it!
1326 if (ShouldEnter) {
1327 CondInfo.FoundNonSkip = true;
1328 break;
1329 }
1330 }
1331 }
1332
1333 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001334 // Restore comment saving mode.
1335 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001336 }
1337
1338 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1339 // of the file, just stop skipping and return to lexing whatever came after
1340 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001341 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001342}
1343
1344//===----------------------------------------------------------------------===//
1345// Preprocessor Directive Handling.
1346//===----------------------------------------------------------------------===//
1347
1348/// HandleDirective - This callback is invoked when the lexer sees a # token
1349/// at the start of a line. This consumes the directive, modifies the
1350/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1351/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001352void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001353 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001354
1355 // We just parsed a # character at the start of a line, so we're in directive
1356 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001357 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001358 CurLexer->ParsingPreprocessorDirective = true;
1359
1360 ++NumDirectives;
1361
Chris Lattner371ac8a2006-07-04 07:11:10 +00001362 // We are about to read a token. For the multiple-include optimization FA to
1363 // work, we have to remember if we had read any tokens *before* this
1364 // pp-directive.
1365 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1366
Chris Lattner78186052006-07-09 00:45:31 +00001367 // Read the next token, the directive flavor. This isn't expanded due to
1368 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001369 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001370
Chris Lattner78186052006-07-09 00:45:31 +00001371 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1372 // #define A(x) #x
1373 // A(abc
1374 // #warning blah
1375 // def)
1376 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001377 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001378 Diag(Result, diag::ext_embedded_directive);
1379
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001381 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001382 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001383
Chris Lattner22eb9722006-06-18 05:43:12 +00001384 case tok::numeric_constant:
1385 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001386 DiscardUntilEndOfDirective();
1387 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001388 default:
1389 IdentifierInfo *II = Result.getIdentifierInfo();
1390 if (II == 0) break; // Not an identifier.
1391
1392 // Ask what the preprocessor keyword ID is.
1393 switch (II->getPPKeywordID()) {
1394 default: break;
1395 // C99 6.10.1 - Conditional Inclusion.
1396 case tok::pp_if:
1397 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1398 case tok::pp_ifdef:
1399 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1400 case tok::pp_ifndef:
1401 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1402 case tok::pp_elif:
1403 return HandleElifDirective(Result);
1404 case tok::pp_else:
1405 return HandleElseDirective(Result);
1406 case tok::pp_endif:
1407 return HandleEndifDirective(Result);
1408
1409 // C99 6.10.2 - Source File Inclusion.
1410 case tok::pp_include:
1411 return HandleIncludeDirective(Result); // Handle #include.
1412
1413 // C99 6.10.3 - Macro Replacement.
1414 case tok::pp_define:
1415 return HandleDefineDirective(Result, false);
1416 case tok::pp_undef:
1417 return HandleUndefDirective(Result);
1418
1419 // C99 6.10.4 - Line Control.
1420 case tok::pp_line:
1421 // FIXME: implement #line
1422 DiscardUntilEndOfDirective();
1423 return;
1424
1425 // C99 6.10.5 - Error Directive.
1426 case tok::pp_error:
1427 return HandleUserDiagnosticDirective(Result, false);
1428
1429 // C99 6.10.6 - Pragma Directive.
1430 case tok::pp_pragma:
1431 return HandlePragmaDirective();
1432
1433 // GNU Extensions.
1434 case tok::pp_import:
1435 return HandleImportDirective(Result);
1436 case tok::pp_include_next:
1437 return HandleIncludeNextDirective(Result);
1438
1439 case tok::pp_warning:
1440 Diag(Result, diag::ext_pp_warning_directive);
1441 return HandleUserDiagnosticDirective(Result, true);
1442 case tok::pp_ident:
1443 return HandleIdentSCCSDirective(Result);
1444 case tok::pp_sccs:
1445 return HandleIdentSCCSDirective(Result);
1446 case tok::pp_assert:
1447 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001448 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001449 case tok::pp_unassert:
1450 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001451 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001452
1453 // clang extensions.
1454 case tok::pp_define_target:
1455 return HandleDefineDirective(Result, true);
1456 case tok::pp_define_other_target:
1457 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001458 }
1459 break;
1460 }
1461
1462 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001463 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001464
1465 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001466 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001467
1468 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001469}
1470
Chris Lattner01d66cc2006-07-03 22:16:27 +00001471void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001472 bool isWarning) {
1473 // Read the rest of the line raw. We do this because we don't want macros
1474 // to be expanded and we don't require that the tokens be valid preprocessing
1475 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1476 // collapse multiple consequtive white space between tokens, but this isn't
1477 // specified by the standard.
1478 std::string Message = CurLexer->ReadToEndOfLine();
1479
1480 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001481 return Diag(Tok, DiagID, Message);
1482}
1483
1484/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1485///
1486void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001487 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001488 Diag(Tok, diag::ext_pp_ident_directive);
1489
Chris Lattner371ac8a2006-07-04 07:11:10 +00001490 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001491 LexerToken StrTok;
1492 Lex(StrTok);
1493
1494 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001495 if (StrTok.getKind() != tok::string_literal &&
1496 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001497 return Diag(StrTok, diag::err_pp_malformed_ident);
1498
1499 // Verify that there is nothing after the string, other than EOM.
1500 CheckEndOfDirective("#ident");
1501
1502 if (IdentHandler)
1503 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001504}
1505
Chris Lattnerb8761832006-06-24 21:31:03 +00001506//===----------------------------------------------------------------------===//
1507// Preprocessor Include Directive Handling.
1508//===----------------------------------------------------------------------===//
1509
Chris Lattner22eb9722006-06-18 05:43:12 +00001510/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1511/// file to be included from the lexer, then include it! This is a common
1512/// routine with functionality shared between #include, #include_next and
1513/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001514void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001515 const DirectoryLookup *LookupFrom,
1516 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001517
Chris Lattner22eb9722006-06-18 05:43:12 +00001518 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001519 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001520
1521 // If the token kind is EOM, the error has already been diagnosed.
1522 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001523 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001524
1525 // Verify that there is nothing after the filename, other than EOM. Use the
1526 // preprocessor to lex this in case lexing the filename entered a macro.
1527 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001528
1529 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001530 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001531 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1532
Chris Lattner269c2322006-06-25 06:23:00 +00001533 // Find out whether the filename is <x> or "x".
1534 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001535
1536 // Remove the quotes.
1537 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1538
Chris Lattner22eb9722006-06-18 05:43:12 +00001539 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001540 const DirectoryLookup *CurDir;
1541 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001542 if (File == 0)
1543 return Diag(FilenameTok, diag::err_pp_file_not_found);
1544
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001545 // Ask HeaderInfo if we should enter this #include file.
1546 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1547 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001548 return;
1549 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001550
1551 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001552 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001553 if (FileID == 0)
1554 return Diag(FilenameTok, diag::err_pp_file_not_found);
1555
1556 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001557 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001558}
1559
1560/// HandleIncludeNextDirective - Implements #include_next.
1561///
Chris Lattnercb283342006-06-18 06:48:37 +00001562void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1563 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001564
1565 // #include_next is like #include, except that we start searching after
1566 // the current found directory. If we can't do this, issue a
1567 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001568 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001569 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001571 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001572 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001573 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001574 } else {
1575 // Start looking up in the next directory.
1576 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001577 }
1578
1579 return HandleIncludeDirective(IncludeNextTok, Lookup);
1580}
1581
1582/// HandleImportDirective - Implements #import.
1583///
Chris Lattnercb283342006-06-18 06:48:37 +00001584void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1585 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001586
1587 return HandleIncludeDirective(ImportTok, 0, true);
1588}
1589
Chris Lattnerb8761832006-06-24 21:31:03 +00001590//===----------------------------------------------------------------------===//
1591// Preprocessor Macro Directive Handling.
1592//===----------------------------------------------------------------------===//
1593
Chris Lattnercefc7682006-07-08 08:28:12 +00001594/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1595/// definition has just been read. Lex the rest of the arguments and the
1596/// closing ), updating MI with what we learn. Return true if an error occurs
1597/// parsing the arg list.
1598bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1599 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001600 while (1) {
1601 LexUnexpandedToken(Tok);
1602 switch (Tok.getKind()) {
1603 case tok::r_paren:
1604 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001605 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001606 // Otherwise we have #define FOO(A,)
1607 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1608 return true;
1609 case tok::ellipsis: // #define X(... -> C99 varargs
1610 // Warn if use of C99 feature in non-C99 mode.
1611 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1612
1613 // Lex the token after the identifier.
1614 LexUnexpandedToken(Tok);
1615 if (Tok.getKind() != tok::r_paren) {
1616 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1617 return true;
1618 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001619 // Add the __VA_ARGS__ identifier as an argument.
1620 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001621 MI->setIsC99Varargs();
1622 return false;
1623 case tok::eom: // #define X(
1624 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1625 return true;
1626 default: // #define X(1
1627 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1628 return true;
1629 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001630 IdentifierInfo *II = Tok.getIdentifierInfo();
1631
1632 // If this is already used as an argument, it is used multiple times (e.g.
1633 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001634 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001635 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1636 return true;
1637 }
1638
1639 // Add the argument to the macro info.
1640 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001641
1642 // Lex the token after the identifier.
1643 LexUnexpandedToken(Tok);
1644
1645 switch (Tok.getKind()) {
1646 default: // #define X(A B
1647 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1648 return true;
1649 case tok::r_paren: // #define X(A)
1650 return false;
1651 case tok::comma: // #define X(A,
1652 break;
1653 case tok::ellipsis: // #define X(A... -> GCC extension
1654 // Diagnose extension.
1655 Diag(Tok, diag::ext_named_variadic_macro);
1656
1657 // Lex the token after the identifier.
1658 LexUnexpandedToken(Tok);
1659 if (Tok.getKind() != tok::r_paren) {
1660 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1661 return true;
1662 }
1663
1664 MI->setIsGNUVarargs();
1665 return false;
1666 }
1667 }
1668 }
1669}
1670
Chris Lattner22eb9722006-06-18 05:43:12 +00001671/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001672/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1673/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001674///
Chris Lattner81278c62006-10-14 19:03:49 +00001675void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1676 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001677 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001678
Chris Lattner22eb9722006-06-18 05:43:12 +00001679 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001680 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001681
1682 // Error reading macro name? If so, diagnostic already issued.
1683 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001684 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001685
Chris Lattner457fc152006-07-29 06:30:25 +00001686 // If we are supposed to keep comments in #defines, reenable comment saving
1687 // mode.
1688 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1689
Chris Lattner063400e2006-10-14 19:54:15 +00001690 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001691 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001692 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001693
Chris Lattner063400e2006-10-14 19:54:15 +00001694 // If the identifier is an 'other target' macro, clear this bit.
1695 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1696
1697
Chris Lattner22eb9722006-06-18 05:43:12 +00001698 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001699 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001700
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001701 // If this is a function-like macro definition, parse the argument list,
1702 // marking each of the identifiers as being used as macro arguments. Also,
1703 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001704 if (Tok.getKind() == tok::eom) {
1705 // If there is no body to this macro, we have no special handling here.
1706 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001707 // This is a function-like macro definition. Read the argument list.
1708 MI->setIsFunctionLike();
1709 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001710 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001711 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001712 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001713 if (CurLexer->ParsingPreprocessorDirective)
1714 DiscardUntilEndOfDirective();
1715 return;
1716 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001717
Chris Lattner815a1f92006-07-08 20:48:04 +00001718 // Read the first token after the arg list for down below.
1719 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001720 } else if (!Tok.hasLeadingSpace()) {
1721 // C99 requires whitespace between the macro definition and the body. Emit
1722 // a diagnostic for something like "#define X+".
1723 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001724 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001725 } else {
1726 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1727 // one in some cases!
1728 }
1729 } else {
1730 // This is a normal token with leading space. Clear the leading space
1731 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001732 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001733 }
1734
Chris Lattner7e374832006-07-29 03:46:57 +00001735 // If this is a definition of a variadic C99 function-like macro, not using
1736 // the GNU named varargs extension, enabled __VA_ARGS__.
1737
1738 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1739 // This gets unpoisoned where it is allowed.
1740 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1741 if (MI->isC99Varargs())
1742 Ident__VA_ARGS__->setIsPoisoned(false);
1743
Chris Lattner22eb9722006-06-18 05:43:12 +00001744 // Read the rest of the macro body.
1745 while (Tok.getKind() != tok::eom) {
1746 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001747
1748 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001749 // parameters in function-like macro expansions.
1750 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001751 // Get the next token of the macro.
1752 LexUnexpandedToken(Tok);
1753 continue;
1754 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001755
Chris Lattner815a1f92006-07-08 20:48:04 +00001756 // Get the next token of the macro.
1757 LexUnexpandedToken(Tok);
1758
1759 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001760 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001761 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001762 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001763 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001764
1765 // Disable __VA_ARGS__ again.
1766 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001767 return;
1768 }
1769
1770 // Things look ok, add the param name token to the macro.
1771 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001772
Chris Lattner22eb9722006-06-18 05:43:12 +00001773 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001774 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001775 }
Chris Lattner7e374832006-07-29 03:46:57 +00001776
1777 // Disable __VA_ARGS__ again.
1778 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001779
Chris Lattnerbff18d52006-07-06 04:49:18 +00001780 // Check that there is no paste (##) operator at the begining or end of the
1781 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001782 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001783 if (NumTokens != 0) {
1784 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001785 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001786 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001787 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001788 }
1789 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001790 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001791 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001792 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001793 }
1794 }
1795
Chris Lattner13044d92006-07-03 05:16:44 +00001796 // If this is the primary source file, remember that this macro hasn't been
1797 // used yet.
1798 if (isInPrimaryFile())
1799 MI->setIsUsed(false);
1800
Chris Lattner22eb9722006-06-18 05:43:12 +00001801 // Finally, if this identifier already had a macro defined for it, verify that
1802 // the macro bodies are identical and free the old definition.
1803 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001804 if (!OtherMI->isUsed())
1805 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1806
Chris Lattner22eb9722006-06-18 05:43:12 +00001807 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001808 // must be the same. C99 6.10.3.2.
1809 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001810 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1811 MacroNameTok.getIdentifierInfo()->getName());
1812 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1813 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001814 delete OtherMI;
1815 }
1816
1817 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001818}
1819
Chris Lattner063400e2006-10-14 19:54:15 +00001820/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1821void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1822 LexerToken MacroNameTok;
1823 ReadMacroName(MacroNameTok, 1);
1824
1825 // Error reading macro name? If so, diagnostic already issued.
1826 if (MacroNameTok.getKind() == tok::eom)
1827 return;
1828
1829 // Check to see if this is the last token on the #undef line.
1830 CheckEndOfDirective("#define_other_target");
1831
1832 // If there is already a macro defined by this name, turn it into a
1833 // target-specific define.
1834 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1835 MI->setIsTargetSpecific(true);
1836 return;
1837 }
1838
1839 // Mark the identifier as being a macro on some other target.
1840 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1841}
1842
Chris Lattner22eb9722006-06-18 05:43:12 +00001843
1844/// HandleUndefDirective - Implements #undef.
1845///
Chris Lattnercb283342006-06-18 06:48:37 +00001846void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001847 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001848
Chris Lattner22eb9722006-06-18 05:43:12 +00001849 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001850 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001851
1852 // Error reading macro name? If so, diagnostic already issued.
1853 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001854 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001855
1856 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001857 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001858
1859 // Okay, we finally have a valid identifier to undef.
1860 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1861
Chris Lattner063400e2006-10-14 19:54:15 +00001862 // #undef untaints an identifier if it were marked by define_other_target.
1863 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1864
Chris Lattner22eb9722006-06-18 05:43:12 +00001865 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001866 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001867
Chris Lattner13044d92006-07-03 05:16:44 +00001868 if (!MI->isUsed())
1869 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001870
1871 // Free macro definition.
1872 delete MI;
1873 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001874}
1875
1876
Chris Lattnerb8761832006-06-24 21:31:03 +00001877//===----------------------------------------------------------------------===//
1878// Preprocessor Conditional Directive Handling.
1879//===----------------------------------------------------------------------===//
1880
Chris Lattner22eb9722006-06-18 05:43:12 +00001881/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001882/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1883/// if any tokens have been returned or pp-directives activated before this
1884/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001885///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001886void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1887 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001888 ++NumIf;
1889 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001890
Chris Lattner22eb9722006-06-18 05:43:12 +00001891 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001892 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001893
1894 // Error reading macro name? If so, diagnostic already issued.
1895 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001896 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001897
1898 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001899 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1900
1901 // If the start of a top-level #ifdef, inform MIOpt.
1902 if (!ReadAnyTokensBeforeDirective &&
1903 CurLexer->getConditionalStackDepth() == 0) {
1904 assert(isIfndef && "#ifdef shouldn't reach here");
1905 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1906 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001907
Chris Lattner063400e2006-10-14 19:54:15 +00001908 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1909 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001910
Chris Lattner81278c62006-10-14 19:03:49 +00001911 // If there is a macro, process it.
1912 if (MI) {
1913 // Mark it used.
1914 MI->setIsUsed(true);
1915
1916 // If this is the first use of a target-specific macro, warn about it.
1917 if (MI->isTargetSpecific()) {
1918 MI->setIsTargetSpecific(false); // Don't warn on second use.
1919 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1920 diag::port_target_macro_use);
1921 }
Chris Lattner063400e2006-10-14 19:54:15 +00001922 } else {
1923 // Use of a target-specific macro for some other target? If so, warn.
1924 if (MII->isOtherTargetMacro()) {
1925 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1926 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1927 diag::port_target_macro_use);
1928 }
Chris Lattner81278c62006-10-14 19:03:49 +00001929 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001930
Chris Lattner22eb9722006-06-18 05:43:12 +00001931 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001932 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001933 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001934 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001935 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001936 } else {
1937 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001938 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001939 /*Foundnonskip*/false,
1940 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001941 }
1942}
1943
1944/// HandleIfDirective - Implements the #if directive.
1945///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001946void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1947 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001948 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001949
Chris Lattner371ac8a2006-07-04 07:11:10 +00001950 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001951 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001952 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001953
1954 // Should we include the stuff contained by this directive?
1955 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001956 // If this condition is equivalent to #ifndef X, and if this is the first
1957 // directive seen, handle it for the multiple-include optimization.
1958 if (!ReadAnyTokensBeforeDirective &&
1959 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1960 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1961
Chris Lattner22eb9722006-06-18 05:43:12 +00001962 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001963 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001964 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001965 } else {
1966 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001967 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001968 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001969 }
1970}
1971
1972/// HandleEndifDirective - Implements the #endif directive.
1973///
Chris Lattnercb283342006-06-18 06:48:37 +00001974void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001975 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001976
Chris Lattner22eb9722006-06-18 05:43:12 +00001977 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001978 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001979
1980 PPConditionalInfo CondInfo;
1981 if (CurLexer->popConditionalLevel(CondInfo)) {
1982 // No conditionals on the stack: this is an #endif without an #if.
1983 return Diag(EndifToken, diag::err_pp_endif_without_if);
1984 }
1985
Chris Lattner371ac8a2006-07-04 07:11:10 +00001986 // If this the end of a top-level #endif, inform MIOpt.
1987 if (CurLexer->getConditionalStackDepth() == 0)
1988 CurLexer->MIOpt.ExitTopLevelConditional();
1989
Chris Lattner538d7f32006-07-20 04:31:52 +00001990 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001991 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001992}
1993
1994
Chris Lattnercb283342006-06-18 06:48:37 +00001995void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001996 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001997
Chris Lattner22eb9722006-06-18 05:43:12 +00001998 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001999 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002000
2001 PPConditionalInfo CI;
2002 if (CurLexer->popConditionalLevel(CI))
2003 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002004
2005 // If this is a top-level #else, inform the MIOpt.
2006 if (CurLexer->getConditionalStackDepth() == 0)
2007 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002008
2009 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002010 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002011
2012 // Finally, skip the rest of the contents of this block and return the first
2013 // token after it.
2014 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2015 /*FoundElse*/true);
2016}
2017
Chris Lattnercb283342006-06-18 06:48:37 +00002018void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002019 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002020
Chris Lattner22eb9722006-06-18 05:43:12 +00002021 // #elif directive in a non-skipping conditional... start skipping.
2022 // We don't care what the condition is, because we will always skip it (since
2023 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002024 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002025
2026 PPConditionalInfo CI;
2027 if (CurLexer->popConditionalLevel(CI))
2028 return Diag(ElifToken, diag::pp_err_elif_without_if);
2029
Chris Lattner371ac8a2006-07-04 07:11:10 +00002030 // If this is a top-level #elif, inform the MIOpt.
2031 if (CurLexer->getConditionalStackDepth() == 0)
2032 CurLexer->MIOpt.FoundTopLevelElse();
2033
Chris Lattner22eb9722006-06-18 05:43:12 +00002034 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002035 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002036
2037 // Finally, skip the rest of the contents of this block and return the first
2038 // token after it.
2039 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2040 /*FoundElse*/CI.FoundElse);
2041}
Chris Lattnerb8761832006-06-24 21:31:03 +00002042