blob: 702af741369010adcc10aab8f0dcb4d82a9ffdfa [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 Lattner7a4af3b2006-07-26 06:26:52 +000035#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000036#include <iostream>
37using namespace llvm;
38using namespace clang;
39
40//===----------------------------------------------------------------------===//
41
42Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
43 FileManager &FM, SourceManager &SM)
44 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
45 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000046 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000047 ScratchBuf = new ScratchBuffer(SourceMgr);
48
Chris Lattner22eb9722006-06-18 05:43:12 +000049 // Clear stats.
50 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
51 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000052 NumEnteredSourceFiles = 0;
53 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000054 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner3665f162006-07-04 07:26:10 +000055 MaxIncludeStackDepth = 0; NumMultiIncludeFileOptzn = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000056 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000057
Chris Lattner22eb9722006-06-18 05:43:12 +000058 // Macro expansion is enabled.
59 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000060 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000061
62 // There is no file-change handler yet.
63 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000064 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000065
Chris Lattner8ff71992006-07-06 05:17:39 +000066 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
67 // This gets unpoisoned where it is allowed.
68 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
69
Chris Lattnerb8761832006-06-24 21:31:03 +000070 // Initialize the pragma handlers.
71 PragmaHandlers = new PragmaNamespace(0);
72 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000073
74 // Initialize builtin macros like __LINE__ and friends.
75 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000076}
77
78Preprocessor::~Preprocessor() {
79 // Free any active lexers.
80 delete CurLexer;
81
Chris Lattner69772b02006-07-02 20:34:39 +000082 while (!IncludeMacroStack.empty()) {
83 delete IncludeMacroStack.back().TheLexer;
84 delete IncludeMacroStack.back().TheMacroExpander;
85 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000086 }
Chris Lattnerb8761832006-06-24 21:31:03 +000087
88 // Release pragma information.
89 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000090
91 // Delete the scratch buffer info.
92 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000093}
94
95/// getFileInfo - Return the PerFileInfo structure for the specified
96/// FileEntry.
97Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
98 if (FE->getUID() >= FileInfo.size())
99 FileInfo.resize(FE->getUID()+1);
100 return FileInfo[FE->getUID()];
101}
102
103
104/// AddKeywords - Add all keywords to the symbol table.
105///
106void Preprocessor::AddKeywords() {
107 enum {
108 C90Shift = 0,
109 EXTC90 = 1 << C90Shift,
110 NOTC90 = 2 << C90Shift,
111 C99Shift = 2,
112 EXTC99 = 1 << C99Shift,
113 NOTC99 = 2 << C99Shift,
114 CPPShift = 4,
115 EXTCPP = 1 << CPPShift,
116 NOTCPP = 2 << CPPShift,
117 Mask = 3
118 };
119
120 // Add keywords and tokens for the current language.
121#define KEYWORD(NAME, FLAGS) \
Chris Lattner02f1f4f2006-07-29 03:52:46 +0000122 AddKeyword(#NAME, tok::kw_ ## NAME, \
Chris Lattner6d998552006-08-04 06:11:48 +0000123 ((FLAGS) >> C90Shift) & Mask, \
124 ((FLAGS) >> C99Shift) & Mask, \
125 ((FLAGS) >> CPPShift) & Mask);
Chris Lattner22eb9722006-06-18 05:43:12 +0000126#define ALIAS(NAME, TOK) \
127 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
128#include "clang/Basic/TokenKinds.def"
129}
130
131/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
132/// the specified LexerToken's location, translating the token's start
133/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000134void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000135 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000136 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000137}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000138
139void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
140 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
141 << getSpelling(Tok) << "'";
142
143 if (!DumpFlags) return;
144 std::cerr << "\t";
145 if (Tok.isAtStartOfLine())
146 std::cerr << " [StartOfLine]";
147 if (Tok.hasLeadingSpace())
148 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000149 if (Tok.isExpandDisabled())
150 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000151 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000152 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000153 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
154 << "']";
155 }
156}
157
158void Preprocessor::DumpMacro(const MacroInfo &MI) const {
159 std::cerr << "MACRO: ";
160 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
161 DumpToken(MI.getReplacementToken(i));
162 std::cerr << " ";
163 }
164 std::cerr << "\n";
165}
166
Chris Lattner22eb9722006-06-18 05:43:12 +0000167void Preprocessor::PrintStats() {
168 std::cerr << "\n*** Preprocessor Stats:\n";
169 std::cerr << FileInfo.size() << " files tracked.\n";
170 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
171 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
172 NumOnceOnlyFiles += FileInfo[i].isImport;
173 if (MaxNumIncludes < FileInfo[i].NumIncludes)
174 MaxNumIncludes = FileInfo[i].NumIncludes;
175 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
176 }
177 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
178 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
179 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
180
181 std::cerr << NumDirectives << " directives found:\n";
182 std::cerr << " " << NumDefined << " #define.\n";
183 std::cerr << " " << NumUndefined << " #undef.\n";
184 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
Chris Lattner3665f162006-07-04 07:26:10 +0000185 std::cerr << " " << NumMultiIncludeFileOptzn << " #includes skipped due to"
186 << " the multi-include optimization.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000187 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
188 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
189 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
190 std::cerr << " " << NumElse << " #else/#elif.\n";
191 std::cerr << " " << NumEndif << " #endif.\n";
192 std::cerr << " " << NumPragma << " #pragma.\n";
193 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
194
Chris Lattner78186052006-07-09 00:45:31 +0000195 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
196 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000197 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000198 std::cerr << (NumFastTokenPaste+NumTokenPaste)
199 << " token paste (##) operations performed, "
200 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000201}
202
203//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000204// Token Spelling
205//===----------------------------------------------------------------------===//
206
207
208/// getSpelling() - Return the 'spelling' of this token. The spelling of a
209/// token are the characters used to represent the token in the source file
210/// after trigraph expansion and escaped-newline folding. In particular, this
211/// wants to get the true, uncanonicalized, spelling of things like digraphs
212/// UCNs, etc.
213std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
214 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
215
216 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000217 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218 if (!Tok.needsCleaning())
219 return std::string(TokStart, TokStart+Tok.getLength());
220
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 std::string Result;
222 Result.reserve(Tok.getLength());
223
Chris Lattneref9eae12006-07-04 22:33:12 +0000224 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
226 Ptr != End; ) {
227 unsigned CharSize;
228 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
229 Ptr += CharSize;
230 }
231 assert(Result.size() != unsigned(Tok.getLength()) &&
232 "NeedsCleaning flag set on something that didn't need cleaning!");
233 return Result;
234}
235
236/// getSpelling - This method is used to get the spelling of a token into a
237/// preallocated buffer, instead of as an std::string. The caller is required
238/// to allocate enough space for the token, which is guaranteed to be at least
239/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000240///
241/// Note that this method may do two possible things: it may either fill in
242/// the buffer specified with characters, or it may *change the input pointer*
243/// to point to a constant buffer with the data already in it (avoiding a
244/// copy). The caller is not allowed to modify the returned buffer pointer
245/// if an internal buffer is returned.
246unsigned Preprocessor::getSpelling(const LexerToken &Tok,
247 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000248 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
249
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000250 // If this token is an identifier, just return the string from the identifier
251 // table, which is very quick.
252 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
253 Buffer = II->getName();
254 return Tok.getLength();
255 }
256
257 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000258 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000259
260 // If this token contains nothing interesting, return it directly.
261 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000262 Buffer = TokStart;
263 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000264 }
265 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000266 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000267 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
268 Ptr != End; ) {
269 unsigned CharSize;
270 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
271 Ptr += CharSize;
272 }
273 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
274 "NeedsCleaning flag set on something that didn't need cleaning!");
275
276 return OutBuf-Buffer;
277}
278
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000279
280/// CreateString - Plop the specified string into a scratch buffer and return a
281/// location for it. If specified, the source location provides a source
282/// location for the token.
283SourceLocation Preprocessor::
284CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
285 if (SLoc.isValid())
286 return ScratchBuf->getToken(Buf, Len, SLoc);
287 return ScratchBuf->getToken(Buf, Len);
288}
289
290
Chris Lattnerd01e2912006-06-18 16:22:51 +0000291//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000292// Source File Location Methods.
293//===----------------------------------------------------------------------===//
294
295
296/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
297/// return null on failure. isAngled indicates whether the file reference is
298/// for system #include's or not (i.e. using <> instead of "").
299const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000300 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000301 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000302 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000303 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000304 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000305
306 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000307 // FIXME: Portability. This should be a sys::Path interface, this doesn't
308 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000309 if (Filename[0] == '/') {
310 // If this was an #include_next "/absolute/file", fail.
311 if (FromDir) return 0;
312
313 // Otherwise, just return the file.
314 return FileMgr.getFile(Filename);
315 }
316
317 // Step #0, unless disabled, check to see if the file is in the #includer's
318 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000319 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000320 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
321 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000322 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000323 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000324 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000325 if (const FileEntry *FE =
326 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000327 if (CurDirLookup)
328 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000329 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000330 CurDir = 0;
331
332 // This file is a system header or C++ unfriendly if the old file is.
333 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000334 return FE;
335 }
336 }
337 }
338
339 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000340 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000341
342 // If this is a #include_next request, start searching after the directory the
343 // file was found in.
344 if (FromDir)
345 i = FromDir-&SearchDirs[0];
346
347 // Check each directory in sequence to see if it contains this file.
348 for (; i != SearchDirs.size(); ++i) {
349 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000350 // FIXME: Portability. Adding file to dir should be in sys::Path.
351 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
352 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000353 CurDir = &SearchDirs[i];
354
355 // This file is a system header or C++ unfriendly if the dir is.
356 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000357 return FE;
358 }
359 }
360
361 // Otherwise, didn't find it.
362 return 0;
363}
364
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000365/// isInPrimaryFile - Return true if we're in the top-level file, not in a
366/// #include.
367bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000368 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000369 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000370
Chris Lattner13044d92006-07-03 05:16:44 +0000371 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000372 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000373 if (IncludeMacroStack[i].TheLexer &&
374 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
375 return IncludeMacroStack[i].TheLexer->isMainFile();
376 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000377}
378
379/// getCurrentLexer - Return the current file lexer being lexed from. Note
380/// that this ignores any potentially active macro expansions and _Pragma
381/// expansions going on at the time.
382Lexer *Preprocessor::getCurrentFileLexer() const {
383 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
384
385 // Look for a stacked lexer.
386 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000387 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000388 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
389 return L;
390 }
391 return 0;
392}
393
394
Chris Lattner22eb9722006-06-18 05:43:12 +0000395/// EnterSourceFile - Add a source file to the top of the include stack and
396/// start lexing tokens from it instead of the current buffer. Return true
397/// on failure.
398void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000399 const DirectoryLookup *CurDir,
400 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000401 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000402 ++NumEnteredSourceFiles;
403
Chris Lattner69772b02006-07-02 20:34:39 +0000404 if (MaxIncludeStackDepth < IncludeMacroStack.size())
405 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000406
Chris Lattner22eb9722006-06-18 05:43:12 +0000407 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000408 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000409 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000410 EnterSourceFileWithLexer(TheLexer, CurDir);
411}
Chris Lattner22eb9722006-06-18 05:43:12 +0000412
Chris Lattner69772b02006-07-02 20:34:39 +0000413/// EnterSourceFile - Add a source file to the top of the include stack and
414/// start lexing tokens from it instead of the current buffer.
415void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
416 const DirectoryLookup *CurDir) {
417
418 // Add the current lexer to the include stack.
419 if (CurLexer || CurMacroExpander)
420 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
421 CurMacroExpander));
422
423 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000424 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000425 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000426
427 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000428 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000429 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
430
431 // Get the file entry for the current file.
432 if (const FileEntry *FE =
433 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
434 FileType = getFileInfo(FE).DirInfo;
435
Chris Lattner1840e492006-07-02 22:30:01 +0000436 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000437 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000438 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000439}
440
Chris Lattner69772b02006-07-02 20:34:39 +0000441
442
Chris Lattner22eb9722006-06-18 05:43:12 +0000443/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000444/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000445void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000446 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000447 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000448 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
449 CurMacroExpander));
450 CurLexer = 0;
451 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000452
Chris Lattneree8760b2006-07-15 07:42:55 +0000453 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000454}
455
Chris Lattner7667d0d2006-07-16 18:16:58 +0000456/// EnterTokenStream - Add a "macro" context to the top of the include stack,
457/// which will cause the lexer to start returning the specified tokens. Note
458/// that these tokens will be re-macro-expanded when/if expansion is enabled.
459/// This method assumes that the specified stream of tokens has a permanent
460/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000461void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000462 // Save our current state.
463 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
464 CurMacroExpander));
465 CurLexer = 0;
466 CurDirLookup = 0;
467
468 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000469 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000470}
471
472/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
473/// lexer stack. This should only be used in situations where the current
474/// state of the top-of-stack lexer is known.
475void Preprocessor::RemoveTopOfLexerStack() {
476 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
477 delete CurLexer;
478 delete CurMacroExpander;
479 CurLexer = IncludeMacroStack.back().TheLexer;
480 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
481 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
482 IncludeMacroStack.pop_back();
483}
484
Chris Lattner22eb9722006-06-18 05:43:12 +0000485//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000486// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000487//===----------------------------------------------------------------------===//
488
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000489/// RegisterBuiltinMacro - Register the specified identifier in the identifier
490/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000491IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000492 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000493 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000494
495 // Mark it as being a macro that is builtin.
496 MacroInfo *MI = new MacroInfo(SourceLocation());
497 MI->setIsBuiltinMacro();
498 Id->setMacroInfo(MI);
499 return Id;
500}
501
502
Chris Lattner677757a2006-06-28 05:26:32 +0000503/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
504/// identifier table.
505void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000506 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000507 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000508 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
509 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000510 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000511
512 // GCC Extensions.
513 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
514 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000515 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000516}
517
Chris Lattnerc2395832006-07-09 00:57:04 +0000518/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
519/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000520static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
521 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000522 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
523
524 // If the token isn't an identifier, it's always literally expanded.
525 if (II == 0) return true;
526
527 // If the identifier is a macro, and if that macro is enabled, it may be
528 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000529 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
530 // Fast expanding "#define X X" is ok, because X would be disabled.
531 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000532 return false;
533
534 // If this is an object-like macro invocation, it is safe to trivially expand
535 // it.
536 if (MI->isObjectLike()) return true;
537
538 // If this is a function-like macro invocation, it's safe to trivially expand
539 // as long as the identifier is not a macro argument.
540 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
541 I != E; ++I)
542 if (*I == II)
543 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000544
Chris Lattnerc2395832006-07-09 00:57:04 +0000545 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000546}
547
Chris Lattnerc2395832006-07-09 00:57:04 +0000548
Chris Lattnerafe603f2006-07-11 04:02:46 +0000549/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
550/// lexed is a '('. If so, consume the token and return true, if not, this
551/// method should have no observable side-effect on the lexed tokens.
552bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000553 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000554 unsigned Val;
555 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000556 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000557 else
558 Val = CurMacroExpander->isNextTokenLParen();
559
560 if (Val == 2) {
561 // If we ran off the end of the lexer or macro expander, walk the include
562 // stack, looking for whatever will return the next token.
563 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
564 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
565 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000566 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000567 else
568 Val = Entry.TheMacroExpander->isNextTokenLParen();
569 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000570 }
571
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000572 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
573 // have found something that isn't a '(' or we found the end of the
574 // translation unit. In either case, return false.
575 if (Val != 1)
576 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000577
578 LexerToken Tok;
579 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000580 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
581 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000582}
Chris Lattner677757a2006-06-28 05:26:32 +0000583
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000584/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
585/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000586bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000587 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000588
589 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
590 if (MI->isBuiltinMacro()) {
591 ExpandBuiltinMacro(Identifier);
592 return false;
593 }
594
Chris Lattneree8760b2006-07-15 07:42:55 +0000595 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000596 /// for each macro argument, the list of tokens that were provided to the
597 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000598 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000599
600 // If this is a function-like macro, read the arguments.
601 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000602 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
603 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000604 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000605 return true;
606
Chris Lattner78186052006-07-09 00:45:31 +0000607 // Remember that we are now parsing the arguments to a macro invocation.
608 // Preprocessor directives used inside macro arguments are not portable, and
609 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000610 InMacroArgs = true;
611 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000612
613 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000614 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000615
616 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000617 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000618
619 ++NumFnMacroExpanded;
620 } else {
621 ++NumMacroExpanded;
622 }
Chris Lattner13044d92006-07-03 05:16:44 +0000623
624 // Notice that this macro has been used.
625 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000626
627 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000628
629 // If this macro expands to no tokens, don't bother to push it onto the
630 // expansion stack, only to take it right back off.
631 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000632 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000633 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000634
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000635 // Ignore this macro use, just return the next token in the current
636 // buffer.
637 bool HadLeadingSpace = Identifier.hasLeadingSpace();
638 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
639
640 Lex(Identifier);
641
642 // If the identifier isn't on some OTHER line, inherit the leading
643 // whitespace/first-on-a-line property of this token. This handles
644 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
645 // empty.
646 if (!Identifier.isAtStartOfLine()) {
647 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
648 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
649 }
650 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000651 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000652
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000653 } else if (MI->getNumTokens() == 1 &&
654 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000655 // Otherwise, if this macro expands into a single trivially-expanded
656 // token: expand it now. This handles common cases like
657 // "#define VAL 42".
658
659 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
660 // identifier to the expanded token.
661 bool isAtStartOfLine = Identifier.isAtStartOfLine();
662 bool hasLeadingSpace = Identifier.hasLeadingSpace();
663
664 // Remember where the token is instantiated.
665 SourceLocation InstantiateLoc = Identifier.getLocation();
666
667 // Replace the result token.
668 Identifier = MI->getReplacementToken(0);
669
670 // Restore the StartOfLine/LeadingSpace markers.
671 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
672 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
673
674 // Update the tokens location to include both its logical and physical
675 // locations.
676 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000677 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000678 Identifier.SetLocation(Loc);
679
Chris Lattner6e4bf522006-07-27 06:59:25 +0000680 // If this is #define X X, we must mark the result as unexpandible.
681 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
682 if (NewII->getMacroInfo() == MI)
683 Identifier.SetFlag(LexerToken::DisableExpand);
684
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000685 // Since this is not an identifier token, it can't be macro expanded, so
686 // we're done.
687 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000688 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000689 }
690
Chris Lattner78186052006-07-09 00:45:31 +0000691 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000692 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000693
694 // Now that the macro is at the top of the include stack, ask the
695 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000696 Lex(Identifier);
697 return false;
698}
699
Chris Lattneree8760b2006-07-15 07:42:55 +0000700/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000701/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000702/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000703MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
704 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000705 // The number of fixed arguments to parse.
706 unsigned NumFixedArgsLeft = MI->getNumArgs();
707 bool isVariadic = MI->isVariadic();
708
Chris Lattner78186052006-07-09 00:45:31 +0000709 // Outer loop, while there are more arguments, keep reading them.
710 LexerToken Tok;
711 Tok.SetKind(tok::comma);
712 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000713
714 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000715 // argument is separated by an EOF token. Use a SmallVector so we can avoid
716 // heap allocations in the common case.
717 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000718
719 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000720 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000721 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
722 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000723
Chris Lattner78186052006-07-09 00:45:31 +0000724 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000725 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
726 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000727 LexUnexpandedToken(Tok);
728
729 if (Tok.getKind() == tok::eof) {
730 Diag(MacroName, diag::err_unterm_macro_invoc);
731 // Do not lose the EOF. Return it to the client.
732 MacroName = Tok;
733 return 0;
734 } else if (Tok.getKind() == tok::r_paren) {
735 // If we found the ) token, the macro arg list is done.
736 if (NumParens-- == 0)
737 break;
738 } else if (Tok.getKind() == tok::l_paren) {
739 ++NumParens;
740 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
741 // Comma ends this argument if there are more fixed arguments expected.
742 if (NumFixedArgsLeft)
743 break;
744
Chris Lattner2ada5d32006-07-15 07:51:24 +0000745 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000746 if (!isVariadic) {
747 // Emit the diagnostic at the macro name in case there is a missing ).
748 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000749 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000750 return 0;
751 }
752 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000753 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
754 // If this is a comment token in the argument list and we're just in
755 // -C mode (not -CC mode), discard the comment.
756 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000757 }
758
759 ArgTokens.push_back(Tok);
760 }
761
Chris Lattnera12dd152006-07-11 04:09:02 +0000762 // Empty arguments are standard in C99 and supported as an extension in
763 // other modes.
764 if (ArgTokens.empty() && !Features.C99)
765 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000766
Chris Lattner36b6e812006-07-21 06:38:30 +0000767 // Add a marker EOF token to the end of the token list for this argument.
768 LexerToken EOFTok;
769 EOFTok.StartToken();
770 EOFTok.SetKind(tok::eof);
771 EOFTok.SetLocation(Tok.getLocation());
772 EOFTok.SetLength(0);
773 ArgTokens.push_back(EOFTok);
774 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000775 --NumFixedArgsLeft;
776 };
777
778 // Okay, we either found the r_paren. Check to see if we parsed too few
779 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000780 unsigned MinArgsExpected = MI->getNumArgs();
781
Chris Lattner775d8322006-07-29 04:39:41 +0000782 // See MacroArgs instance var for description of this.
783 bool isVarargsElided = false;
784
Chris Lattner2ada5d32006-07-15 07:51:24 +0000785 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000786 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000787 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000788 // Varargs where the named vararg parameter is missing: ok as extension.
789 // #define A(x, ...)
790 // A("blah")
791 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000792
793 // Remember this occurred if this is a C99 macro invocation with at least
794 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000795 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000796 } else if (MI->getNumArgs() == 1) {
797 // #define A(x)
798 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000799 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000800
801 // Empty arguments are standard in C99 and supported as an extension in
802 // other modes.
803 if (ArgTokens.empty() && !Features.C99)
804 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000805 } else {
806 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000807 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000808 return 0;
809 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000810
811 // Add a marker EOF token to the end of the token list for this argument.
812 SourceLocation EndLoc = Tok.getLocation();
813 Tok.StartToken();
814 Tok.SetKind(tok::eof);
815 Tok.SetLocation(EndLoc);
816 Tok.SetLength(0);
817 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000818 }
819
Chris Lattner775d8322006-07-29 04:39:41 +0000820 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000821}
822
Chris Lattnerc673f902006-06-30 06:10:41 +0000823/// ComputeDATE_TIME - Compute the current time, enter it into the specified
824/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
825/// the identifier tokens inserted.
826static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000827 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000828 time_t TT = time(0);
829 struct tm *TM = localtime(&TT);
830
831 static const char * const Months[] = {
832 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
833 };
834
835 char TmpBuffer[100];
836 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
837 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000838 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000839
840 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000841 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000842}
843
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000844/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
845/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000846void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000847 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000848 IdentifierInfo *II = Tok.getIdentifierInfo();
849 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000850
851 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
852 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000853 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000854 return Handle_Pragma(Tok);
855
Chris Lattner78186052006-07-09 00:45:31 +0000856 ++NumBuiltinMacroExpanded;
857
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000858 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000859
860 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000861 Tok.SetIdentifierInfo(0);
862 Tok.ClearFlag(LexerToken::NeedsCleaning);
863
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000864 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000865 // __LINE__ expands to a simple numeric value.
866 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
867 unsigned Length = strlen(TmpBuffer);
868 Tok.SetKind(tok::numeric_constant);
869 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000870 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000871 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000872 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000873 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000874 Diag(Tok, diag::ext_pp_base_file);
875 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
876 while (NextLoc.getFileID() != 0) {
877 Loc = NextLoc;
878 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
879 }
880 }
881
Chris Lattner0766e592006-07-03 01:07:01 +0000882 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
883 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000884 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner630b33c2006-07-01 22:46:53 +0000885 Tok.SetKind(tok::string_literal);
886 Tok.SetLength(FN.size());
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000887 Tok.SetLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000888 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000889 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000890 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000891 Tok.SetKind(tok::string_literal);
892 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
893 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000894 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000895 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000896 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000897 Tok.SetKind(tok::string_literal);
898 Tok.SetLength(strlen("\"hh:mm:ss\""));
899 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000900 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000901 Diag(Tok, diag::ext_pp_include_level);
902
903 // Compute the include depth of this token.
904 unsigned Depth = 0;
905 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
906 for (; Loc.getFileID() != 0; ++Depth)
907 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
908
909 // __INCLUDE_LEVEL__ expands to a simple numeric value.
910 sprintf(TmpBuffer, "%u", Depth);
911 unsigned Length = strlen(TmpBuffer);
912 Tok.SetKind(tok::numeric_constant);
913 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000914 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000915 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000916 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
917 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
918 Diag(Tok, diag::ext_pp_timestamp);
919
920 // Get the file that we are lexing out of. If we're currently lexing from
921 // a macro, dig into the include stack.
922 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000923 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000924
925 if (TheLexer)
926 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
927
928 // If this file is older than the file it depends on, emit a diagnostic.
929 const char *Result;
930 if (CurFile) {
931 time_t TT = CurFile->getModificationTime();
932 struct tm *TM = localtime(&TT);
933 Result = asctime(TM);
934 } else {
935 Result = "??? ??? ?? ??:??:?? ????\n";
936 }
937 TmpBuffer[0] = '"';
938 strcpy(TmpBuffer+1, Result);
939 unsigned Len = strlen(TmpBuffer);
940 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
941 Tok.SetKind(tok::string_literal);
942 Tok.SetLength(Len);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000943 Tok.SetLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000944 } else {
945 assert(0 && "Unknown identifier!");
946 }
947}
Chris Lattner677757a2006-06-28 05:26:32 +0000948
Chris Lattner13044d92006-07-03 05:16:44 +0000949namespace {
950struct UnusedIdentifierReporter : public IdentifierVisitor {
951 Preprocessor &PP;
952 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
953
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000954 void VisitIdentifier(IdentifierInfo &II) const {
955 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
956 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000957 }
958};
959}
960
Chris Lattner677757a2006-06-28 05:26:32 +0000961//===----------------------------------------------------------------------===//
962// Lexer Event Handling.
963//===----------------------------------------------------------------------===//
964
Chris Lattnercefc7682006-07-08 08:28:12 +0000965/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
966/// identifier information for the token and install it into the token.
967IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
968 const char *BufPtr) {
969 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
970 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
971
972 // Look up this token, see if it is a macro, or if it is a language keyword.
973 IdentifierInfo *II;
974 if (BufPtr && !Identifier.needsCleaning()) {
975 // No cleaning needed, just use the characters from the lexed buffer.
976 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
977 } else {
978 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
979 const char *TmpBuf = (char*)alloca(Identifier.getLength());
980 unsigned Size = getSpelling(Identifier, TmpBuf);
981 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
982 }
983 Identifier.SetIdentifierInfo(II);
984 return II;
985}
986
987
Chris Lattner677757a2006-06-28 05:26:32 +0000988/// HandleIdentifier - This callback is invoked when the lexer reads an
989/// identifier. This callback looks up the identifier in the map and/or
990/// potentially macro expands it or turns it into a named token (like 'for').
991void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000992 assert(Identifier.getIdentifierInfo() &&
993 "Can't handle identifiers without identifier info!");
994
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000995 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000996
997 // If this identifier was poisoned, and if it was not produced from a macro
998 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000999 if (II.isPoisoned() && CurLexer) {
1000 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1001 Diag(Identifier, diag::err_pp_used_poisoned_id);
1002 else
1003 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1004 }
Chris Lattner677757a2006-06-28 05:26:32 +00001005
Chris Lattner78186052006-07-09 00:45:31 +00001006 // If this is a macro to be expanded, do it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001007 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner6e4bf522006-07-27 06:59:25 +00001008 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1009 if (MI->isEnabled()) {
1010 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1011 return;
1012 } else {
1013 // C99 6.10.3.4p2 says that a disabled macro may never again be
1014 // expanded, even if it's in a context where it could be expanded in the
1015 // future.
1016 Identifier.SetFlag(LexerToken::DisableExpand);
1017 }
1018 }
Chris Lattner677757a2006-06-28 05:26:32 +00001019
1020 // Change the kind of this identifier to the appropriate token kind, e.g.
1021 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001022 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001023
1024 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001025 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001026}
1027
Chris Lattner22eb9722006-06-18 05:43:12 +00001028/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1029/// the current file. This either returns the EOF token or pops a level off
1030/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001031bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001032 assert(!CurMacroExpander &&
1033 "Ending a file when currently in a macro!");
1034
Chris Lattner371ac8a2006-07-04 07:11:10 +00001035 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001036 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001037 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001038 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001039 // Okay, this has a controlling macro, remember in PerFileInfo.
1040 if (const FileEntry *FE =
1041 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1042 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001043 }
1044 }
1045
Chris Lattner22eb9722006-06-18 05:43:12 +00001046 // If this is a #include'd file, pop it off the include stack and continue
1047 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001048 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001049 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001050 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001051
1052 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001053 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001054 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1055
1056 // Get the file entry for the current file.
1057 if (const FileEntry *FE =
1058 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1059 FileType = getFileInfo(FE).DirInfo;
1060
Chris Lattner0c885f52006-06-21 06:50:18 +00001061 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001062 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001063 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001064
1065 // Client should lex another token.
1066 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001067 }
1068
Chris Lattnerd01e2912006-06-18 16:22:51 +00001069 Result.StartToken();
1070 CurLexer->BufferPtr = CurLexer->BufferEnd;
1071 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001072 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001073
1074 // We're done with the #included file.
1075 delete CurLexer;
1076 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001077
Chris Lattner03f83482006-07-10 06:16:26 +00001078 // This is the end of the top-level file. If the diag::pp_macro_not_used
1079 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1080 // have not been used.
1081 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1082 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001083
1084 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001085}
1086
1087/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001088/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001089bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001090 assert(CurMacroExpander && !CurLexer &&
1091 "Ending a macro when currently in a #include file!");
1092
Chris Lattner22eb9722006-06-18 05:43:12 +00001093 delete CurMacroExpander;
1094
Chris Lattner69772b02006-07-02 20:34:39 +00001095 // Handle this like a #include file being popped off the stack.
1096 CurMacroExpander = 0;
1097 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001098}
1099
1100
1101//===----------------------------------------------------------------------===//
1102// Utility Methods for Preprocessor Directive Handling.
1103//===----------------------------------------------------------------------===//
1104
1105/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1106/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001107void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001108 LexerToken Tmp;
1109 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001110 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001111 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001112}
1113
1114/// ReadMacroName - Lex and validate a macro name, which occurs after a
1115/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001116/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1117/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001118/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001119void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001120 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001121 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001122
1123 // Missing macro name?
1124 if (MacroNameTok.getKind() == tok::eom)
1125 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1126
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001127 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1128 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001129 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001130 // Fall through on error.
1131 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001132 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001133
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001134 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1135 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001136 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001137 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001138 } else if (isDefineUndef && II->getMacroInfo() &&
1139 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001140 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001141 if (isDefineUndef == 1)
1142 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1143 else
1144 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001145 } else {
1146 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001147 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001148 }
1149
Chris Lattner22eb9722006-06-18 05:43:12 +00001150 // Invalid macro name, read and discard the rest of the line. Then set the
1151 // token kind to tok::eom.
1152 MacroNameTok.SetKind(tok::eom);
1153 return DiscardUntilEndOfDirective();
1154}
1155
1156/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1157/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001158void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001159 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001160 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001161 // There should be no tokens after the directive, but we allow them as an
1162 // extension.
1163 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001164 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1165 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001166 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001167}
1168
1169
1170
1171/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1172/// decided that the subsequent tokens are in the #if'd out portion of the
1173/// file. Lex the rest of the file, until we see an #endif. If
1174/// FoundNonSkipPortion is true, then we have already emitted code for part of
1175/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1176/// is true, then #else directives are ok, if not, then we have already seen one
1177/// so a #else directive is a duplicate. When this returns, the caller can lex
1178/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001179void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001180 bool FoundNonSkipPortion,
1181 bool FoundElse) {
1182 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001183 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001184 "Lexing a macro, not a file?");
1185
1186 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1187 FoundNonSkipPortion, FoundElse);
1188
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001189 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1190 // disabling warnings, etc.
1191 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001192 LexerToken Tok;
1193 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001194 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001195
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001196 // If this is the end of the buffer, we have an error.
1197 if (Tok.getKind() == tok::eof) {
1198 // Emit errors for each unterminated conditional on the stack, including
1199 // the current one.
1200 while (!CurLexer->ConditionalStack.empty()) {
1201 Diag(CurLexer->ConditionalStack.back().IfLoc,
1202 diag::err_pp_unterminated_conditional);
1203 CurLexer->ConditionalStack.pop_back();
1204 }
1205
1206 // Just return and let the caller lex after this #include.
1207 break;
1208 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001209
1210 // If this token is not a preprocessor directive, just skip it.
1211 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1212 continue;
1213
1214 // We just parsed a # character at the start of a line, so we're in
1215 // directive mode. Tell the lexer this so any newlines we see will be
1216 // converted into an EOM token (this terminates the macro).
1217 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001218 CurLexer->KeepCommentMode = false;
1219
Chris Lattner22eb9722006-06-18 05:43:12 +00001220
1221 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001222 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001223
1224 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1225 // something bogus), skip it.
1226 if (Tok.getKind() != tok::identifier) {
1227 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001228 // Restore comment saving mode.
1229 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001230 continue;
1231 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001232
Chris Lattner22eb9722006-06-18 05:43:12 +00001233 // If the first letter isn't i or e, it isn't intesting to us. We know that
1234 // this is safe in the face of spelling differences, because there is no way
1235 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001236 // allows us to avoid looking up the identifier info for #define/#undef and
1237 // other common directives.
1238 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1239 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001240 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1241 FirstChar != 'i' && FirstChar != 'e') {
1242 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001243 // Restore comment saving mode.
1244 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001245 continue;
1246 }
1247
Chris Lattnere60165f2006-06-22 06:36:29 +00001248 // Get the identifier name without trigraphs or embedded newlines. Note
1249 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1250 // when skipping.
1251 // TODO: could do this with zero copies in the no-clean case by using
1252 // strncmp below.
1253 char Directive[20];
1254 unsigned IdLen;
1255 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1256 IdLen = Tok.getLength();
1257 memcpy(Directive, RawCharData, IdLen);
1258 Directive[IdLen] = 0;
1259 } else {
1260 std::string DirectiveStr = getSpelling(Tok);
1261 IdLen = DirectiveStr.size();
1262 if (IdLen >= 20) {
1263 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001264 // Restore comment saving mode.
1265 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001266 continue;
1267 }
1268 memcpy(Directive, &DirectiveStr[0], IdLen);
1269 Directive[IdLen] = 0;
1270 }
1271
Chris Lattner22eb9722006-06-18 05:43:12 +00001272 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001273 if ((IdLen == 2) || // "if"
1274 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1275 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001276 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1277 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001278 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001279 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001280 /*foundnonskip*/false,
1281 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001282 }
1283 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001284 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001285 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001286 PPConditionalInfo CondInfo;
1287 CondInfo.WasSkipping = true; // Silence bogus warning.
1288 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1289 assert(!InCond && "Can't be skipping if not in a conditional!");
1290
1291 // If we popped the outermost skipping block, we're done skipping!
1292 if (!CondInfo.WasSkipping)
1293 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001294 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001295 // #else directive in a skipping conditional. If not in some other
1296 // skipping conditional, and if #else hasn't already been seen, enter it
1297 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001298 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001299 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1300
1301 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001302 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001303
1304 // Note that we've seen a #else in this conditional.
1305 CondInfo.FoundElse = true;
1306
1307 // If the conditional is at the top level, and the #if block wasn't
1308 // entered, enter the #else block now.
1309 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1310 CondInfo.FoundNonSkip = true;
1311 break;
1312 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001313 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001314 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1315
1316 bool ShouldEnter;
1317 // If this is in a skipping block or if we're already handled this #if
1318 // block, don't bother parsing the condition.
1319 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001320 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001321 ShouldEnter = false;
1322 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001323 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001324 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001325 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1326 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001327 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001328 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001329 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001330 }
1331
1332 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001333 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001334
1335 // If this condition is true, enter it!
1336 if (ShouldEnter) {
1337 CondInfo.FoundNonSkip = true;
1338 break;
1339 }
1340 }
1341 }
1342
1343 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001344 // Restore comment saving mode.
1345 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001346 }
1347
1348 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1349 // of the file, just stop skipping and return to lexing whatever came after
1350 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001351 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001352}
1353
1354//===----------------------------------------------------------------------===//
1355// Preprocessor Directive Handling.
1356//===----------------------------------------------------------------------===//
1357
1358/// HandleDirective - This callback is invoked when the lexer sees a # token
1359/// at the start of a line. This consumes the directive, modifies the
1360/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1361/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001362void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001363 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001364
1365 // We just parsed a # character at the start of a line, so we're in directive
1366 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001367 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001368 CurLexer->ParsingPreprocessorDirective = true;
1369
1370 ++NumDirectives;
1371
Chris Lattner371ac8a2006-07-04 07:11:10 +00001372 // We are about to read a token. For the multiple-include optimization FA to
1373 // work, we have to remember if we had read any tokens *before* this
1374 // pp-directive.
1375 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1376
Chris Lattner78186052006-07-09 00:45:31 +00001377 // Read the next token, the directive flavor. This isn't expanded due to
1378 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001379 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001380
Chris Lattner78186052006-07-09 00:45:31 +00001381 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1382 // #define A(x) #x
1383 // A(abc
1384 // #warning blah
1385 // def)
1386 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001387 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001388 Diag(Result, diag::ext_embedded_directive);
1389
Chris Lattner22eb9722006-06-18 05:43:12 +00001390 switch (Result.getKind()) {
1391 default: break;
1392 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001393 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001394
1395#if 0
1396 case tok::numeric_constant:
1397 // FIXME: implement # 7 line numbers!
1398 break;
1399#endif
1400 case tok::kw_else:
1401 return HandleElseDirective(Result);
1402 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001403 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001404 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001405 // Get the identifier name without trigraphs or embedded newlines.
1406 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001407 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001408 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001409 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001410 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001411 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001412 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001413 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001414 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1415 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001416 break;
1417 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001418 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001419 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001420 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001421 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001422 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001423 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001424 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001426 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001427 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001428 break;
1429 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001430 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001431 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001432 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001433 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001434 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001435 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001436 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001437 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001438 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1439 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001440 break;
1441 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001442 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1443 return HandleIncludeDirective(Result); // Handle #include.
1444 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001445 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001446 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001447 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001448 break;
1449 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001450 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001451 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001452 }
1453 break;
1454 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001455 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1456 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001457 break;
1458 }
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.
1495 if (StrTok.getKind() != tok::string_literal)
1496 return Diag(StrTok, diag::err_pp_malformed_ident);
1497
1498 // Verify that there is nothing after the string, other than EOM.
1499 CheckEndOfDirective("#ident");
1500
1501 if (IdentHandler)
1502 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001503}
1504
Chris Lattnerb8761832006-06-24 21:31:03 +00001505//===----------------------------------------------------------------------===//
1506// Preprocessor Include Directive Handling.
1507//===----------------------------------------------------------------------===//
1508
Chris Lattner22eb9722006-06-18 05:43:12 +00001509/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1510/// file to be included from the lexer, then include it! This is a common
1511/// routine with functionality shared between #include, #include_next and
1512/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001513void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001514 const DirectoryLookup *LookupFrom,
1515 bool isImport) {
1516 ++NumIncluded;
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
1545 // Get information about this file.
1546 PerFileInfo &FileInfo = getFileInfo(File);
1547
1548 // If this is a #import directive, check that we have not already imported
1549 // this header.
1550 if (isImport) {
1551 // If this has already been imported, don't import it again.
1552 FileInfo.isImport = true;
1553
1554 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001555 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001556 } else {
1557 // Otherwise, if this is a #include of a file that was previously #import'd
1558 // or if this is the second #include of a #pragma once file, ignore it.
1559 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001560 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001561 }
Chris Lattner3665f162006-07-04 07:26:10 +00001562
1563 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1564 // if the macro that guards it is defined, we know the #include has no effect.
1565 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1566 ++NumMultiIncludeFileOptzn;
1567 return;
1568 }
1569
Chris Lattner22eb9722006-06-18 05:43:12 +00001570
1571 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001572 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001573 if (FileID == 0)
1574 return Diag(FilenameTok, diag::err_pp_file_not_found);
1575
1576 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001577 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001578
1579 // Increment the number of times this file has been included.
1580 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001581}
1582
1583/// HandleIncludeNextDirective - Implements #include_next.
1584///
Chris Lattnercb283342006-06-18 06:48:37 +00001585void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1586 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001587
1588 // #include_next is like #include, except that we start searching after
1589 // the current found directory. If we can't do this, issue a
1590 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001591 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001592 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001593 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001594 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001595 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001596 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001597 } else {
1598 // Start looking up in the next directory.
1599 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001600 }
1601
1602 return HandleIncludeDirective(IncludeNextTok, Lookup);
1603}
1604
1605/// HandleImportDirective - Implements #import.
1606///
Chris Lattnercb283342006-06-18 06:48:37 +00001607void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1608 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001609
1610 return HandleIncludeDirective(ImportTok, 0, true);
1611}
1612
Chris Lattnerb8761832006-06-24 21:31:03 +00001613//===----------------------------------------------------------------------===//
1614// Preprocessor Macro Directive Handling.
1615//===----------------------------------------------------------------------===//
1616
Chris Lattnercefc7682006-07-08 08:28:12 +00001617/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1618/// definition has just been read. Lex the rest of the arguments and the
1619/// closing ), updating MI with what we learn. Return true if an error occurs
1620/// parsing the arg list.
1621bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1622 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001623 while (1) {
1624 LexUnexpandedToken(Tok);
1625 switch (Tok.getKind()) {
1626 case tok::r_paren:
1627 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001628 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001629 // Otherwise we have #define FOO(A,)
1630 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1631 return true;
1632 case tok::ellipsis: // #define X(... -> C99 varargs
1633 // Warn if use of C99 feature in non-C99 mode.
1634 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1635
1636 // Lex the token after the identifier.
1637 LexUnexpandedToken(Tok);
1638 if (Tok.getKind() != tok::r_paren) {
1639 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1640 return true;
1641 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001642 // Add the __VA_ARGS__ identifier as an argument.
1643 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001644 MI->setIsC99Varargs();
1645 return false;
1646 case tok::eom: // #define X(
1647 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1648 return true;
1649 default: // #define X(1
1650 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1651 return true;
1652 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001653 IdentifierInfo *II = Tok.getIdentifierInfo();
1654
1655 // If this is already used as an argument, it is used multiple times (e.g.
1656 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001657 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001658 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1659 return true;
1660 }
1661
1662 // Add the argument to the macro info.
1663 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001664
1665 // Lex the token after the identifier.
1666 LexUnexpandedToken(Tok);
1667
1668 switch (Tok.getKind()) {
1669 default: // #define X(A B
1670 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1671 return true;
1672 case tok::r_paren: // #define X(A)
1673 return false;
1674 case tok::comma: // #define X(A,
1675 break;
1676 case tok::ellipsis: // #define X(A... -> GCC extension
1677 // Diagnose extension.
1678 Diag(Tok, diag::ext_named_variadic_macro);
1679
1680 // Lex the token after the identifier.
1681 LexUnexpandedToken(Tok);
1682 if (Tok.getKind() != tok::r_paren) {
1683 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1684 return true;
1685 }
1686
1687 MI->setIsGNUVarargs();
1688 return false;
1689 }
1690 }
1691 }
1692}
1693
Chris Lattner22eb9722006-06-18 05:43:12 +00001694/// HandleDefineDirective - Implements #define. This consumes the entire macro
1695/// line then lets the caller lex the next real token.
1696///
Chris Lattnercb283342006-06-18 06:48:37 +00001697void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001698 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001699
Chris Lattner22eb9722006-06-18 05:43:12 +00001700 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001701 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001702
1703 // Error reading macro name? If so, diagnostic already issued.
1704 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001705 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001706
Chris Lattner457fc152006-07-29 06:30:25 +00001707 // If we are supposed to keep comments in #defines, reenable comment saving
1708 // mode.
1709 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1710
Chris Lattner50b497e2006-06-18 16:32:35 +00001711 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001712
1713 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001714 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001715
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001716 // If this is a function-like macro definition, parse the argument list,
1717 // marking each of the identifiers as being used as macro arguments. Also,
1718 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001719 if (Tok.getKind() == tok::eom) {
1720 // If there is no body to this macro, we have no special handling here.
1721 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001722 // This is a function-like macro definition. Read the argument list.
1723 MI->setIsFunctionLike();
1724 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001725 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001726 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001727 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001728 if (CurLexer->ParsingPreprocessorDirective)
1729 DiscardUntilEndOfDirective();
1730 return;
1731 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001732
Chris Lattner815a1f92006-07-08 20:48:04 +00001733 // Read the first token after the arg list for down below.
1734 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001735 } else if (!Tok.hasLeadingSpace()) {
1736 // C99 requires whitespace between the macro definition and the body. Emit
1737 // a diagnostic for something like "#define X+".
1738 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001739 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001740 } else {
1741 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1742 // one in some cases!
1743 }
1744 } else {
1745 // This is a normal token with leading space. Clear the leading space
1746 // marker on the first token to get proper expansion.
1747 Tok.ClearFlag(LexerToken::LeadingSpace);
1748 }
1749
Chris Lattner7e374832006-07-29 03:46:57 +00001750 // If this is a definition of a variadic C99 function-like macro, not using
1751 // the GNU named varargs extension, enabled __VA_ARGS__.
1752
1753 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1754 // This gets unpoisoned where it is allowed.
1755 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1756 if (MI->isC99Varargs())
1757 Ident__VA_ARGS__->setIsPoisoned(false);
1758
Chris Lattner22eb9722006-06-18 05:43:12 +00001759 // Read the rest of the macro body.
1760 while (Tok.getKind() != tok::eom) {
1761 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001762
1763 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001764 // parameters in function-like macro expansions.
1765 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001766 // Get the next token of the macro.
1767 LexUnexpandedToken(Tok);
1768 continue;
1769 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001770
Chris Lattner815a1f92006-07-08 20:48:04 +00001771 // Get the next token of the macro.
1772 LexUnexpandedToken(Tok);
1773
1774 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001775 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001776 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001777 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001778 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001779
1780 // Disable __VA_ARGS__ again.
1781 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001782 return;
1783 }
1784
1785 // Things look ok, add the param name token to the macro.
1786 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001787
Chris Lattner22eb9722006-06-18 05:43:12 +00001788 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001789 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001790 }
Chris Lattner7e374832006-07-29 03:46:57 +00001791
1792 // Disable __VA_ARGS__ again.
1793 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001794
Chris Lattnerbff18d52006-07-06 04:49:18 +00001795 // Check that there is no paste (##) operator at the begining or end of the
1796 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001797 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001798 if (NumTokens != 0) {
1799 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001800 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001801 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001802 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001803 }
1804 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001805 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001806 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001807 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001808 }
1809 }
1810
Chris Lattner13044d92006-07-03 05:16:44 +00001811 // If this is the primary source file, remember that this macro hasn't been
1812 // used yet.
1813 if (isInPrimaryFile())
1814 MI->setIsUsed(false);
1815
Chris Lattner22eb9722006-06-18 05:43:12 +00001816 // Finally, if this identifier already had a macro defined for it, verify that
1817 // the macro bodies are identical and free the old definition.
1818 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001819 if (!OtherMI->isUsed())
1820 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1821
Chris Lattner22eb9722006-06-18 05:43:12 +00001822 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001823 // must be the same. C99 6.10.3.2.
1824 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001825 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1826 MacroNameTok.getIdentifierInfo()->getName());
1827 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1828 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001829 delete OtherMI;
1830 }
1831
1832 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001833}
1834
1835
1836/// HandleUndefDirective - Implements #undef.
1837///
Chris Lattnercb283342006-06-18 06:48:37 +00001838void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001839 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001840
Chris Lattner22eb9722006-06-18 05:43:12 +00001841 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001842 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001843
1844 // Error reading macro name? If so, diagnostic already issued.
1845 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001846 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001847
1848 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001849 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001850
1851 // Okay, we finally have a valid identifier to undef.
1852 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1853
1854 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001855 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001856
Chris Lattner13044d92006-07-03 05:16:44 +00001857 if (!MI->isUsed())
1858 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001859
1860 // Free macro definition.
1861 delete MI;
1862 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001863}
1864
1865
Chris Lattnerb8761832006-06-24 21:31:03 +00001866//===----------------------------------------------------------------------===//
1867// Preprocessor Conditional Directive Handling.
1868//===----------------------------------------------------------------------===//
1869
Chris Lattner22eb9722006-06-18 05:43:12 +00001870/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001871/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1872/// if any tokens have been returned or pp-directives activated before this
1873/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001874///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001875void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1876 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001877 ++NumIf;
1878 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001879
Chris Lattner22eb9722006-06-18 05:43:12 +00001880 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001881 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001882
1883 // Error reading macro name? If so, diagnostic already issued.
1884 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001885 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001886
1887 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001888 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1889
1890 // If the start of a top-level #ifdef, inform MIOpt.
1891 if (!ReadAnyTokensBeforeDirective &&
1892 CurLexer->getConditionalStackDepth() == 0) {
1893 assert(isIfndef && "#ifdef shouldn't reach here");
1894 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1895 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001896
Chris Lattnera78a97e2006-07-03 05:42:18 +00001897 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1898
1899 // If there is a macro, mark it used.
1900 if (MI) MI->setIsUsed(true);
1901
Chris Lattner22eb9722006-06-18 05:43:12 +00001902 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001903 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001904 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001905 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001906 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001907 } else {
1908 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001909 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001910 /*Foundnonskip*/false,
1911 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001912 }
1913}
1914
1915/// HandleIfDirective - Implements the #if directive.
1916///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001917void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1918 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001919 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001920
Chris Lattner371ac8a2006-07-04 07:11:10 +00001921 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001922 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001923 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001924
1925 // Should we include the stuff contained by this directive?
1926 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001927 // If this condition is equivalent to #ifndef X, and if this is the first
1928 // directive seen, handle it for the multiple-include optimization.
1929 if (!ReadAnyTokensBeforeDirective &&
1930 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1931 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1932
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(IfToken.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(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001939 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001940 }
1941}
1942
1943/// HandleEndifDirective - Implements the #endif directive.
1944///
Chris Lattnercb283342006-06-18 06:48:37 +00001945void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001946 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001947
Chris Lattner22eb9722006-06-18 05:43:12 +00001948 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001949 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001950
1951 PPConditionalInfo CondInfo;
1952 if (CurLexer->popConditionalLevel(CondInfo)) {
1953 // No conditionals on the stack: this is an #endif without an #if.
1954 return Diag(EndifToken, diag::err_pp_endif_without_if);
1955 }
1956
Chris Lattner371ac8a2006-07-04 07:11:10 +00001957 // If this the end of a top-level #endif, inform MIOpt.
1958 if (CurLexer->getConditionalStackDepth() == 0)
1959 CurLexer->MIOpt.ExitTopLevelConditional();
1960
Chris Lattner538d7f32006-07-20 04:31:52 +00001961 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001962 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001963}
1964
1965
Chris Lattnercb283342006-06-18 06:48:37 +00001966void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001967 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001968
Chris Lattner22eb9722006-06-18 05:43:12 +00001969 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001970 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001971
1972 PPConditionalInfo CI;
1973 if (CurLexer->popConditionalLevel(CI))
1974 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001975
1976 // If this is a top-level #else, inform the MIOpt.
1977 if (CurLexer->getConditionalStackDepth() == 0)
1978 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001979
1980 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001981 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001982
1983 // Finally, skip the rest of the contents of this block and return the first
1984 // token after it.
1985 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1986 /*FoundElse*/true);
1987}
1988
Chris Lattnercb283342006-06-18 06:48:37 +00001989void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001990 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001991
Chris Lattner22eb9722006-06-18 05:43:12 +00001992 // #elif directive in a non-skipping conditional... start skipping.
1993 // We don't care what the condition is, because we will always skip it (since
1994 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001995 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001996
1997 PPConditionalInfo CI;
1998 if (CurLexer->popConditionalLevel(CI))
1999 return Diag(ElifToken, diag::pp_err_elif_without_if);
2000
Chris Lattner371ac8a2006-07-04 07:11:10 +00002001 // If this is a top-level #elif, inform the MIOpt.
2002 if (CurLexer->getConditionalStackDepth() == 0)
2003 CurLexer->MIOpt.FoundTopLevelElse();
2004
Chris Lattner22eb9722006-06-18 05:43:12 +00002005 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002006 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002007
2008 // Finally, skip the rest of the contents of this block and return the first
2009 // token after it.
2010 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2011 /*FoundElse*/CI.FoundElse);
2012}
Chris Lattnerb8761832006-06-24 21:31:03 +00002013