blob: 5dc2c925a9ac46e3e147f035d45f026bddf5352a [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.
16// -C -CC - Do not discard comments for cpp.
Chris Lattner22eb9722006-06-18 05:43:12 +000017// -d[MDNI] - Dump various things.
18// -fworking-directory - #line's with preprocessor's working dir.
19// -fpreprocessed
20// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
21// -W*
22// -w
23//
24// Messages to emit:
25// "Multiple include guards may be useful for:\n"
26//
Chris Lattner22eb9722006-06-18 05:43:12 +000027//===----------------------------------------------------------------------===//
28
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000031#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000032#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000033#include "clang/Basic/Diagnostic.h"
34#include "clang/Basic/FileManager.h"
35#include "clang/Basic/SourceManager.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000036#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000037#include <iostream>
38using namespace llvm;
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42
43Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
44 FileManager &FM, SourceManager &SM)
45 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
46 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000047 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000048 ScratchBuf = new ScratchBuffer(SourceMgr);
49
Chris Lattner22eb9722006-06-18 05:43:12 +000050 // Clear stats.
51 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
52 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000053 NumEnteredSourceFiles = 0;
54 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000055 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner3665f162006-07-04 07:26:10 +000056 MaxIncludeStackDepth = 0; NumMultiIncludeFileOptzn = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000057 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000058
Chris Lattner22eb9722006-06-18 05:43:12 +000059 // Macro expansion is enabled.
60 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000061 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000062
63 // There is no file-change handler yet.
64 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000065 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000066
Chris Lattner8ff71992006-07-06 05:17:39 +000067 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
68 // This gets unpoisoned where it is allowed.
69 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
70
Chris Lattnerb8761832006-06-24 21:31:03 +000071 // Initialize the pragma handlers.
72 PragmaHandlers = new PragmaNamespace(0);
73 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000074
75 // Initialize builtin macros like __LINE__ and friends.
76 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000077}
78
79Preprocessor::~Preprocessor() {
80 // Free any active lexers.
81 delete CurLexer;
82
Chris Lattner69772b02006-07-02 20:34:39 +000083 while (!IncludeMacroStack.empty()) {
84 delete IncludeMacroStack.back().TheLexer;
85 delete IncludeMacroStack.back().TheMacroExpander;
86 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000087 }
Chris Lattnerb8761832006-06-24 21:31:03 +000088
89 // Release pragma information.
90 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000091
92 // Delete the scratch buffer info.
93 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000094}
95
96/// getFileInfo - Return the PerFileInfo structure for the specified
97/// FileEntry.
98Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
99 if (FE->getUID() >= FileInfo.size())
100 FileInfo.resize(FE->getUID()+1);
101 return FileInfo[FE->getUID()];
102}
103
104
105/// AddKeywords - Add all keywords to the symbol table.
106///
107void Preprocessor::AddKeywords() {
108 enum {
109 C90Shift = 0,
110 EXTC90 = 1 << C90Shift,
111 NOTC90 = 2 << C90Shift,
112 C99Shift = 2,
113 EXTC99 = 1 << C99Shift,
114 NOTC99 = 2 << C99Shift,
115 CPPShift = 4,
116 EXTCPP = 1 << CPPShift,
117 NOTCPP = 2 << CPPShift,
118 Mask = 3
119 };
120
121 // Add keywords and tokens for the current language.
122#define KEYWORD(NAME, FLAGS) \
Chris Lattner02f1f4f2006-07-29 03:52:46 +0000123 AddKeyword(#NAME, tok::kw_ ## NAME, \
Chris Lattner22eb9722006-06-18 05:43:12 +0000124 (FLAGS >> C90Shift) & Mask, \
125 (FLAGS >> C99Shift) & Mask, \
126 (FLAGS >> CPPShift) & Mask);
127#define ALIAS(NAME, TOK) \
128 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
129#include "clang/Basic/TokenKinds.def"
130}
131
132/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
133/// the specified LexerToken's location, translating the token's start
134/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000135void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000136 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000137 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000138}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000139
140void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
141 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
142 << getSpelling(Tok) << "'";
143
144 if (!DumpFlags) return;
145 std::cerr << "\t";
146 if (Tok.isAtStartOfLine())
147 std::cerr << " [StartOfLine]";
148 if (Tok.hasLeadingSpace())
149 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000150 if (Tok.isExpandDisabled())
151 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000152 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000153 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000154 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
155 << "']";
156 }
157}
158
159void Preprocessor::DumpMacro(const MacroInfo &MI) const {
160 std::cerr << "MACRO: ";
161 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
162 DumpToken(MI.getReplacementToken(i));
163 std::cerr << " ";
164 }
165 std::cerr << "\n";
166}
167
Chris Lattner22eb9722006-06-18 05:43:12 +0000168void Preprocessor::PrintStats() {
169 std::cerr << "\n*** Preprocessor Stats:\n";
170 std::cerr << FileInfo.size() << " files tracked.\n";
171 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
172 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
173 NumOnceOnlyFiles += FileInfo[i].isImport;
174 if (MaxNumIncludes < FileInfo[i].NumIncludes)
175 MaxNumIncludes = FileInfo[i].NumIncludes;
176 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
177 }
178 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
179 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
180 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
181
182 std::cerr << NumDirectives << " directives found:\n";
183 std::cerr << " " << NumDefined << " #define.\n";
184 std::cerr << " " << NumUndefined << " #undef.\n";
185 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
Chris Lattner3665f162006-07-04 07:26:10 +0000186 std::cerr << " " << NumMultiIncludeFileOptzn << " #includes skipped due to"
187 << " the multi-include optimization.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000188 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
189 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
190 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
191 std::cerr << " " << NumElse << " #else/#elif.\n";
192 std::cerr << " " << NumEndif << " #endif.\n";
193 std::cerr << " " << NumPragma << " #pragma.\n";
194 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
195
Chris Lattner78186052006-07-09 00:45:31 +0000196 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
197 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000198 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000199 std::cerr << (NumFastTokenPaste+NumTokenPaste)
200 << " token paste (##) operations performed, "
201 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000202}
203
204//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000205// Token Spelling
206//===----------------------------------------------------------------------===//
207
208
209/// getSpelling() - Return the 'spelling' of this token. The spelling of a
210/// token are the characters used to represent the token in the source file
211/// after trigraph expansion and escaped-newline folding. In particular, this
212/// wants to get the true, uncanonicalized, spelling of things like digraphs
213/// UCNs, etc.
214std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
215 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
216
217 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000218 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000219 if (!Tok.needsCleaning())
220 return std::string(TokStart, TokStart+Tok.getLength());
221
Chris Lattnerd01e2912006-06-18 16:22:51 +0000222 std::string Result;
223 Result.reserve(Tok.getLength());
224
Chris Lattneref9eae12006-07-04 22:33:12 +0000225 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000226 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
227 Ptr != End; ) {
228 unsigned CharSize;
229 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
230 Ptr += CharSize;
231 }
232 assert(Result.size() != unsigned(Tok.getLength()) &&
233 "NeedsCleaning flag set on something that didn't need cleaning!");
234 return Result;
235}
236
237/// getSpelling - This method is used to get the spelling of a token into a
238/// preallocated buffer, instead of as an std::string. The caller is required
239/// to allocate enough space for the token, which is guaranteed to be at least
240/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000241///
242/// Note that this method may do two possible things: it may either fill in
243/// the buffer specified with characters, or it may *change the input pointer*
244/// to point to a constant buffer with the data already in it (avoiding a
245/// copy). The caller is not allowed to modify the returned buffer pointer
246/// if an internal buffer is returned.
247unsigned Preprocessor::getSpelling(const LexerToken &Tok,
248 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000249 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
250
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000251 // If this token is an identifier, just return the string from the identifier
252 // table, which is very quick.
253 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
254 Buffer = II->getName();
255 return Tok.getLength();
256 }
257
258 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000259 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000260
261 // If this token contains nothing interesting, return it directly.
262 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000263 Buffer = TokStart;
264 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000265 }
266 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000267 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000268 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
269 Ptr != End; ) {
270 unsigned CharSize;
271 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
272 Ptr += CharSize;
273 }
274 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
275 "NeedsCleaning flag set on something that didn't need cleaning!");
276
277 return OutBuf-Buffer;
278}
279
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000280
281/// CreateString - Plop the specified string into a scratch buffer and return a
282/// location for it. If specified, the source location provides a source
283/// location for the token.
284SourceLocation Preprocessor::
285CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
286 if (SLoc.isValid())
287 return ScratchBuf->getToken(Buf, Len, SLoc);
288 return ScratchBuf->getToken(Buf, Len);
289}
290
291
Chris Lattnerd01e2912006-06-18 16:22:51 +0000292//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000293// Source File Location Methods.
294//===----------------------------------------------------------------------===//
295
296
297/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
298/// return null on failure. isAngled indicates whether the file reference is
299/// for system #include's or not (i.e. using <> instead of "").
300const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000301 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000302 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000303 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000304 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000305 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000306
307 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000308 // FIXME: Portability. This should be a sys::Path interface, this doesn't
309 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000310 if (Filename[0] == '/') {
311 // If this was an #include_next "/absolute/file", fail.
312 if (FromDir) return 0;
313
314 // Otherwise, just return the file.
315 return FileMgr.getFile(Filename);
316 }
317
318 // Step #0, unless disabled, check to see if the file is in the #includer's
319 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000320 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000321 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
322 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000323 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000324 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000325 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000326 if (const FileEntry *FE =
327 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000328 if (CurDirLookup)
329 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000330 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000331 CurDir = 0;
332
333 // This file is a system header or C++ unfriendly if the old file is.
334 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000335 return FE;
336 }
337 }
338 }
339
340 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000341 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000342
343 // If this is a #include_next request, start searching after the directory the
344 // file was found in.
345 if (FromDir)
346 i = FromDir-&SearchDirs[0];
347
348 // Check each directory in sequence to see if it contains this file.
349 for (; i != SearchDirs.size(); ++i) {
350 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000351 // FIXME: Portability. Adding file to dir should be in sys::Path.
352 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
353 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000354 CurDir = &SearchDirs[i];
355
356 // This file is a system header or C++ unfriendly if the dir is.
357 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000358 return FE;
359 }
360 }
361
362 // Otherwise, didn't find it.
363 return 0;
364}
365
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000366/// isInPrimaryFile - Return true if we're in the top-level file, not in a
367/// #include.
368bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000369 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000370 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000371
Chris Lattner13044d92006-07-03 05:16:44 +0000372 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000373 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000374 if (IncludeMacroStack[i].TheLexer &&
375 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
376 return IncludeMacroStack[i].TheLexer->isMainFile();
377 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000378}
379
380/// getCurrentLexer - Return the current file lexer being lexed from. Note
381/// that this ignores any potentially active macro expansions and _Pragma
382/// expansions going on at the time.
383Lexer *Preprocessor::getCurrentFileLexer() const {
384 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
385
386 // Look for a stacked lexer.
387 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000388 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000389 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
390 return L;
391 }
392 return 0;
393}
394
395
Chris Lattner22eb9722006-06-18 05:43:12 +0000396/// EnterSourceFile - Add a source file to the top of the include stack and
397/// start lexing tokens from it instead of the current buffer. Return true
398/// on failure.
399void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000400 const DirectoryLookup *CurDir,
401 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000402 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000403 ++NumEnteredSourceFiles;
404
Chris Lattner69772b02006-07-02 20:34:39 +0000405 if (MaxIncludeStackDepth < IncludeMacroStack.size())
406 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000407
Chris Lattner22eb9722006-06-18 05:43:12 +0000408 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000409 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000410 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000411 EnterSourceFileWithLexer(TheLexer, CurDir);
412}
Chris Lattner22eb9722006-06-18 05:43:12 +0000413
Chris Lattner69772b02006-07-02 20:34:39 +0000414/// EnterSourceFile - Add a source file to the top of the include stack and
415/// start lexing tokens from it instead of the current buffer.
416void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
417 const DirectoryLookup *CurDir) {
418
419 // Add the current lexer to the include stack.
420 if (CurLexer || CurMacroExpander)
421 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
422 CurMacroExpander));
423
424 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000425 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000426 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000427
428 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000429 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000430 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
431
432 // Get the file entry for the current file.
433 if (const FileEntry *FE =
434 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
435 FileType = getFileInfo(FE).DirInfo;
436
Chris Lattner1840e492006-07-02 22:30:01 +0000437 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000438 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000439 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000440}
441
Chris Lattner69772b02006-07-02 20:34:39 +0000442
443
Chris Lattner22eb9722006-06-18 05:43:12 +0000444/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000445/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000446void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000447 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000448 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000449 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
450 CurMacroExpander));
451 CurLexer = 0;
452 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000453
Chris Lattneree8760b2006-07-15 07:42:55 +0000454 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000455}
456
Chris Lattner7667d0d2006-07-16 18:16:58 +0000457/// EnterTokenStream - Add a "macro" context to the top of the include stack,
458/// which will cause the lexer to start returning the specified tokens. Note
459/// that these tokens will be re-macro-expanded when/if expansion is enabled.
460/// This method assumes that the specified stream of tokens has a permanent
461/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000462void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000463 // Save our current state.
464 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
465 CurMacroExpander));
466 CurLexer = 0;
467 CurDirLookup = 0;
468
469 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000470 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000471}
472
473/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
474/// lexer stack. This should only be used in situations where the current
475/// state of the top-of-stack lexer is known.
476void Preprocessor::RemoveTopOfLexerStack() {
477 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
478 delete CurLexer;
479 delete CurMacroExpander;
480 CurLexer = IncludeMacroStack.back().TheLexer;
481 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
482 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
483 IncludeMacroStack.pop_back();
484}
485
Chris Lattner22eb9722006-06-18 05:43:12 +0000486//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000487// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000488//===----------------------------------------------------------------------===//
489
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000490/// RegisterBuiltinMacro - Register the specified identifier in the identifier
491/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000492IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000493 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000494 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000495
496 // Mark it as being a macro that is builtin.
497 MacroInfo *MI = new MacroInfo(SourceLocation());
498 MI->setIsBuiltinMacro();
499 Id->setMacroInfo(MI);
500 return Id;
501}
502
503
Chris Lattner677757a2006-06-28 05:26:32 +0000504/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
505/// identifier table.
506void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000507 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000508 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000509 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
510 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000511 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000512
513 // GCC Extensions.
514 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
515 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000516 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000517}
518
Chris Lattnerc2395832006-07-09 00:57:04 +0000519/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
520/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000521static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
522 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000523 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
524
525 // If the token isn't an identifier, it's always literally expanded.
526 if (II == 0) return true;
527
528 // If the identifier is a macro, and if that macro is enabled, it may be
529 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000530 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
531 // Fast expanding "#define X X" is ok, because X would be disabled.
532 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000533 return false;
534
535 // If this is an object-like macro invocation, it is safe to trivially expand
536 // it.
537 if (MI->isObjectLike()) return true;
538
539 // If this is a function-like macro invocation, it's safe to trivially expand
540 // as long as the identifier is not a macro argument.
541 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
542 I != E; ++I)
543 if (*I == II)
544 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000545
546 // If the argument is the __VA_ARGS__ token, we can't fast expand it.
547 if (!strcmp(II->getName(), "__VA_ARGS__"))
548 return false; // Identifier is macro argument.
549
Chris Lattnerc2395832006-07-09 00:57:04 +0000550 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000551}
552
Chris Lattnerc2395832006-07-09 00:57:04 +0000553
Chris Lattnerafe603f2006-07-11 04:02:46 +0000554/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
555/// lexed is a '('. If so, consume the token and return true, if not, this
556/// method should have no observable side-effect on the lexed tokens.
557bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000558 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000559 unsigned Val;
560 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000561 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000562 else
563 Val = CurMacroExpander->isNextTokenLParen();
564
565 if (Val == 2) {
566 // If we ran off the end of the lexer or macro expander, walk the include
567 // stack, looking for whatever will return the next token.
568 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
569 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
570 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000571 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000572 else
573 Val = Entry.TheMacroExpander->isNextTokenLParen();
574 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000575 }
576
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000577 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
578 // have found something that isn't a '(' or we found the end of the
579 // translation unit. In either case, return false.
580 if (Val != 1)
581 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000582
583 LexerToken Tok;
584 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000585 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
586 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000587}
Chris Lattner677757a2006-06-28 05:26:32 +0000588
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000589/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
590/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000591bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000592 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000593
594 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
595 if (MI->isBuiltinMacro()) {
596 ExpandBuiltinMacro(Identifier);
597 return false;
598 }
599
Chris Lattneree8760b2006-07-15 07:42:55 +0000600 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000601 /// for each macro argument, the list of tokens that were provided to the
602 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000603 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000604
605 // If this is a function-like macro, read the arguments.
606 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000607 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
608 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000609 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000610 return true;
611
Chris Lattner78186052006-07-09 00:45:31 +0000612 // Remember that we are now parsing the arguments to a macro invocation.
613 // Preprocessor directives used inside macro arguments are not portable, and
614 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000615 InMacroArgs = true;
616 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000617
618 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000619 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000620
621 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000622 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000623
624 ++NumFnMacroExpanded;
625 } else {
626 ++NumMacroExpanded;
627 }
Chris Lattner13044d92006-07-03 05:16:44 +0000628
629 // Notice that this macro has been used.
630 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000631
632 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000633
634 // If this macro expands to no tokens, don't bother to push it onto the
635 // expansion stack, only to take it right back off.
636 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000637 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000638 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000639
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000640 // Ignore this macro use, just return the next token in the current
641 // buffer.
642 bool HadLeadingSpace = Identifier.hasLeadingSpace();
643 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
644
645 Lex(Identifier);
646
647 // If the identifier isn't on some OTHER line, inherit the leading
648 // whitespace/first-on-a-line property of this token. This handles
649 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
650 // empty.
651 if (!Identifier.isAtStartOfLine()) {
652 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
653 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
654 }
655 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000656 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000657
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000658 } else if (MI->getNumTokens() == 1 &&
659 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000660 // Otherwise, if this macro expands into a single trivially-expanded
661 // token: expand it now. This handles common cases like
662 // "#define VAL 42".
663
664 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
665 // identifier to the expanded token.
666 bool isAtStartOfLine = Identifier.isAtStartOfLine();
667 bool hasLeadingSpace = Identifier.hasLeadingSpace();
668
669 // Remember where the token is instantiated.
670 SourceLocation InstantiateLoc = Identifier.getLocation();
671
672 // Replace the result token.
673 Identifier = MI->getReplacementToken(0);
674
675 // Restore the StartOfLine/LeadingSpace markers.
676 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
677 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
678
679 // Update the tokens location to include both its logical and physical
680 // locations.
681 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000682 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000683 Identifier.SetLocation(Loc);
684
Chris Lattner6e4bf522006-07-27 06:59:25 +0000685 // If this is #define X X, we must mark the result as unexpandible.
686 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
687 if (NewII->getMacroInfo() == MI)
688 Identifier.SetFlag(LexerToken::DisableExpand);
689
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000690 // Since this is not an identifier token, it can't be macro expanded, so
691 // we're done.
692 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000693 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000694 }
695
Chris Lattner78186052006-07-09 00:45:31 +0000696 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000697 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000698
699 // Now that the macro is at the top of the include stack, ask the
700 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000701 Lex(Identifier);
702 return false;
703}
704
Chris Lattneree8760b2006-07-15 07:42:55 +0000705/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000706/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000707/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000708MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
709 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000710 // The number of fixed arguments to parse.
711 unsigned NumFixedArgsLeft = MI->getNumArgs();
712 bool isVariadic = MI->isVariadic();
713
714 // If this is a C99-style varargs macro invocation, add an extra expected
Chris Lattner2ada5d32006-07-15 07:51:24 +0000715 // argument, which will catch all of the vararg args in one argument.
Chris Lattner78186052006-07-09 00:45:31 +0000716 if (MI->isC99Varargs())
717 ++NumFixedArgsLeft;
718
719 // Outer loop, while there are more arguments, keep reading them.
720 LexerToken Tok;
721 Tok.SetKind(tok::comma);
722 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000723
724 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000725 // argument is separated by an EOF token. Use a SmallVector so we can avoid
726 // heap allocations in the common case.
727 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000728
729 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000730 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000731 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
732 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000733
Chris Lattner78186052006-07-09 00:45:31 +0000734 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000735 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
736 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000737 LexUnexpandedToken(Tok);
738
739 if (Tok.getKind() == tok::eof) {
740 Diag(MacroName, diag::err_unterm_macro_invoc);
741 // Do not lose the EOF. Return it to the client.
742 MacroName = Tok;
743 return 0;
744 } else if (Tok.getKind() == tok::r_paren) {
745 // If we found the ) token, the macro arg list is done.
746 if (NumParens-- == 0)
747 break;
748 } else if (Tok.getKind() == tok::l_paren) {
749 ++NumParens;
750 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
751 // Comma ends this argument if there are more fixed arguments expected.
752 if (NumFixedArgsLeft)
753 break;
754
Chris Lattner2ada5d32006-07-15 07:51:24 +0000755 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000756 if (!isVariadic) {
757 // Emit the diagnostic at the macro name in case there is a missing ).
758 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000759 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000760 return 0;
761 }
762 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000763 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
764 // If this is a comment token in the argument list and we're just in
765 // -C mode (not -CC mode), discard the comment.
766 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000767 }
768
769 ArgTokens.push_back(Tok);
770 }
771
Chris Lattnera12dd152006-07-11 04:09:02 +0000772 // Empty arguments are standard in C99 and supported as an extension in
773 // other modes.
774 if (ArgTokens.empty() && !Features.C99)
775 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000776
Chris Lattner36b6e812006-07-21 06:38:30 +0000777 // Add a marker EOF token to the end of the token list for this argument.
778 LexerToken EOFTok;
779 EOFTok.StartToken();
780 EOFTok.SetKind(tok::eof);
781 EOFTok.SetLocation(Tok.getLocation());
782 EOFTok.SetLength(0);
783 ArgTokens.push_back(EOFTok);
784 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000785 --NumFixedArgsLeft;
786 };
787
788 // Okay, we either found the r_paren. Check to see if we parsed too few
789 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000790 unsigned MinArgsExpected = MI->getNumArgs();
791
792 // C99 expects us to pass at least one vararg arg (but as an extension, we
Chris Lattnerc2395832006-07-09 00:57:04 +0000793 // don't require this). GNU-style varargs already include the 'rest' name in
794 // the count.
795 MinArgsExpected += MI->isC99Varargs();
Chris Lattner78186052006-07-09 00:45:31 +0000796
Chris Lattner775d8322006-07-29 04:39:41 +0000797 // See MacroArgs instance var for description of this.
798 bool isVarargsElided = false;
799
Chris Lattner2ada5d32006-07-15 07:51:24 +0000800 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000801 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000802 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000803 // Varargs where the named vararg parameter is missing: ok as extension.
804 // #define A(x, ...)
805 // A("blah")
806 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000807
808 // Remember this occurred if this is a C99 macro invocation with at least
809 // one actual argument.
810 isVarargsElided = (MI->isC99Varargs() && MI->getNumArgs());
Chris Lattner78186052006-07-09 00:45:31 +0000811 } else if (MI->getNumArgs() == 1) {
812 // #define A(x)
813 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000814 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000815
816 // Empty arguments are standard in C99 and supported as an extension in
817 // other modes.
818 if (ArgTokens.empty() && !Features.C99)
819 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000820 } else {
821 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000822 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000823 return 0;
824 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000825
826 // Add a marker EOF token to the end of the token list for this argument.
827 SourceLocation EndLoc = Tok.getLocation();
828 Tok.StartToken();
829 Tok.SetKind(tok::eof);
830 Tok.SetLocation(EndLoc);
831 Tok.SetLength(0);
832 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000833 }
834
Chris Lattner775d8322006-07-29 04:39:41 +0000835 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000836}
837
Chris Lattnerc673f902006-06-30 06:10:41 +0000838/// ComputeDATE_TIME - Compute the current time, enter it into the specified
839/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
840/// the identifier tokens inserted.
841static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000842 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000843 time_t TT = time(0);
844 struct tm *TM = localtime(&TT);
845
846 static const char * const Months[] = {
847 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
848 };
849
850 char TmpBuffer[100];
851 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
852 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000853 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000854
855 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000856 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000857}
858
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000859/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
860/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000861void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000862 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000863 IdentifierInfo *II = Tok.getIdentifierInfo();
864 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000865
866 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
867 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000868 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000869 return Handle_Pragma(Tok);
870
Chris Lattner78186052006-07-09 00:45:31 +0000871 ++NumBuiltinMacroExpanded;
872
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000873 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000874
875 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000876 Tok.SetIdentifierInfo(0);
877 Tok.ClearFlag(LexerToken::NeedsCleaning);
878
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000879 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000880 // __LINE__ expands to a simple numeric value.
881 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
882 unsigned Length = strlen(TmpBuffer);
883 Tok.SetKind(tok::numeric_constant);
884 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000885 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000886 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000887 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000888 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000889 Diag(Tok, diag::ext_pp_base_file);
890 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
891 while (NextLoc.getFileID() != 0) {
892 Loc = NextLoc;
893 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
894 }
895 }
896
Chris Lattner0766e592006-07-03 01:07:01 +0000897 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
898 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000899 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner630b33c2006-07-01 22:46:53 +0000900 Tok.SetKind(tok::string_literal);
901 Tok.SetLength(FN.size());
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000902 Tok.SetLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000903 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000904 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000905 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000906 Tok.SetKind(tok::string_literal);
907 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
908 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000909 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000910 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000911 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000912 Tok.SetKind(tok::string_literal);
913 Tok.SetLength(strlen("\"hh:mm:ss\""));
914 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000915 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000916 Diag(Tok, diag::ext_pp_include_level);
917
918 // Compute the include depth of this token.
919 unsigned Depth = 0;
920 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
921 for (; Loc.getFileID() != 0; ++Depth)
922 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
923
924 // __INCLUDE_LEVEL__ expands to a simple numeric value.
925 sprintf(TmpBuffer, "%u", Depth);
926 unsigned Length = strlen(TmpBuffer);
927 Tok.SetKind(tok::numeric_constant);
928 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000929 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000930 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000931 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
932 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
933 Diag(Tok, diag::ext_pp_timestamp);
934
935 // Get the file that we are lexing out of. If we're currently lexing from
936 // a macro, dig into the include stack.
937 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000938 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000939
940 if (TheLexer)
941 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
942
943 // If this file is older than the file it depends on, emit a diagnostic.
944 const char *Result;
945 if (CurFile) {
946 time_t TT = CurFile->getModificationTime();
947 struct tm *TM = localtime(&TT);
948 Result = asctime(TM);
949 } else {
950 Result = "??? ??? ?? ??:??:?? ????\n";
951 }
952 TmpBuffer[0] = '"';
953 strcpy(TmpBuffer+1, Result);
954 unsigned Len = strlen(TmpBuffer);
955 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
956 Tok.SetKind(tok::string_literal);
957 Tok.SetLength(Len);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000958 Tok.SetLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000959 } else {
960 assert(0 && "Unknown identifier!");
961 }
962}
Chris Lattner677757a2006-06-28 05:26:32 +0000963
Chris Lattner13044d92006-07-03 05:16:44 +0000964namespace {
965struct UnusedIdentifierReporter : public IdentifierVisitor {
966 Preprocessor &PP;
967 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
968
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000969 void VisitIdentifier(IdentifierInfo &II) const {
970 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
971 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000972 }
973};
974}
975
Chris Lattner677757a2006-06-28 05:26:32 +0000976//===----------------------------------------------------------------------===//
977// Lexer Event Handling.
978//===----------------------------------------------------------------------===//
979
Chris Lattnercefc7682006-07-08 08:28:12 +0000980/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
981/// identifier information for the token and install it into the token.
982IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
983 const char *BufPtr) {
984 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
985 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
986
987 // Look up this token, see if it is a macro, or if it is a language keyword.
988 IdentifierInfo *II;
989 if (BufPtr && !Identifier.needsCleaning()) {
990 // No cleaning needed, just use the characters from the lexed buffer.
991 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
992 } else {
993 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
994 const char *TmpBuf = (char*)alloca(Identifier.getLength());
995 unsigned Size = getSpelling(Identifier, TmpBuf);
996 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
997 }
998 Identifier.SetIdentifierInfo(II);
999 return II;
1000}
1001
1002
Chris Lattner677757a2006-06-28 05:26:32 +00001003/// HandleIdentifier - This callback is invoked when the lexer reads an
1004/// identifier. This callback looks up the identifier in the map and/or
1005/// potentially macro expands it or turns it into a named token (like 'for').
1006void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001007 assert(Identifier.getIdentifierInfo() &&
1008 "Can't handle identifiers without identifier info!");
1009
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001010 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001011
1012 // If this identifier was poisoned, and if it was not produced from a macro
1013 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001014 if (II.isPoisoned() && CurLexer) {
1015 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1016 Diag(Identifier, diag::err_pp_used_poisoned_id);
1017 else
1018 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1019 }
Chris Lattner677757a2006-06-28 05:26:32 +00001020
Chris Lattner78186052006-07-09 00:45:31 +00001021 // If this is a macro to be expanded, do it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001022 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner6e4bf522006-07-27 06:59:25 +00001023 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1024 if (MI->isEnabled()) {
1025 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1026 return;
1027 } else {
1028 // C99 6.10.3.4p2 says that a disabled macro may never again be
1029 // expanded, even if it's in a context where it could be expanded in the
1030 // future.
1031 Identifier.SetFlag(LexerToken::DisableExpand);
1032 }
1033 }
Chris Lattner677757a2006-06-28 05:26:32 +00001034
1035 // Change the kind of this identifier to the appropriate token kind, e.g.
1036 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001037 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001038
1039 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001040 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001041}
1042
Chris Lattner22eb9722006-06-18 05:43:12 +00001043/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1044/// the current file. This either returns the EOF token or pops a level off
1045/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001046bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001047 assert(!CurMacroExpander &&
1048 "Ending a file when currently in a macro!");
1049
Chris Lattner371ac8a2006-07-04 07:11:10 +00001050 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001051 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001052 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001053 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001054 // Okay, this has a controlling macro, remember in PerFileInfo.
1055 if (const FileEntry *FE =
1056 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1057 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001058 }
1059 }
1060
Chris Lattner22eb9722006-06-18 05:43:12 +00001061 // If this is a #include'd file, pop it off the include stack and continue
1062 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001063 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001064 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001065 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001066
1067 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001068 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001069 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1070
1071 // Get the file entry for the current file.
1072 if (const FileEntry *FE =
1073 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1074 FileType = getFileInfo(FE).DirInfo;
1075
Chris Lattner0c885f52006-06-21 06:50:18 +00001076 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001077 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001078 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001079
1080 // Client should lex another token.
1081 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001082 }
1083
Chris Lattnerd01e2912006-06-18 16:22:51 +00001084 Result.StartToken();
1085 CurLexer->BufferPtr = CurLexer->BufferEnd;
1086 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001087 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001088
1089 // We're done with the #included file.
1090 delete CurLexer;
1091 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001092
Chris Lattner03f83482006-07-10 06:16:26 +00001093 // This is the end of the top-level file. If the diag::pp_macro_not_used
1094 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1095 // have not been used.
1096 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1097 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001098
1099 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001100}
1101
1102/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001103/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001104bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001105 assert(CurMacroExpander && !CurLexer &&
1106 "Ending a macro when currently in a #include file!");
1107
Chris Lattner22eb9722006-06-18 05:43:12 +00001108 delete CurMacroExpander;
1109
Chris Lattner69772b02006-07-02 20:34:39 +00001110 // Handle this like a #include file being popped off the stack.
1111 CurMacroExpander = 0;
1112 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001113}
1114
1115
1116//===----------------------------------------------------------------------===//
1117// Utility Methods for Preprocessor Directive Handling.
1118//===----------------------------------------------------------------------===//
1119
1120/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1121/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001122void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001123 LexerToken Tmp;
1124 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001125 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001126 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001127}
1128
1129/// ReadMacroName - Lex and validate a macro name, which occurs after a
1130/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001131/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1132/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001133/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001134void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001136 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001137
1138 // Missing macro name?
1139 if (MacroNameTok.getKind() == tok::eom)
1140 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1141
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001142 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1143 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001144 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001145 // Fall through on error.
1146 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001147 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001148
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001149 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1150 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001151 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001152 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001153 } else if (isDefineUndef && II->getMacroInfo() &&
1154 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001155 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001156 if (isDefineUndef == 1)
1157 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1158 else
1159 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001160 } else {
1161 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001162 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001163 }
1164
Chris Lattner22eb9722006-06-18 05:43:12 +00001165 // Invalid macro name, read and discard the rest of the line. Then set the
1166 // token kind to tok::eom.
1167 MacroNameTok.SetKind(tok::eom);
1168 return DiscardUntilEndOfDirective();
1169}
1170
1171/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1172/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001173void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001174 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001175 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001176 // There should be no tokens after the directive, but we allow them as an
1177 // extension.
1178 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001179 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1180 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001181 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001182}
1183
1184
1185
1186/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1187/// decided that the subsequent tokens are in the #if'd out portion of the
1188/// file. Lex the rest of the file, until we see an #endif. If
1189/// FoundNonSkipPortion is true, then we have already emitted code for part of
1190/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1191/// is true, then #else directives are ok, if not, then we have already seen one
1192/// so a #else directive is a duplicate. When this returns, the caller can lex
1193/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001194void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001195 bool FoundNonSkipPortion,
1196 bool FoundElse) {
1197 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001198 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001199 "Lexing a macro, not a file?");
1200
1201 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1202 FoundNonSkipPortion, FoundElse);
1203
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001204 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1205 // disabling warnings, etc.
1206 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001207 LexerToken Tok;
1208 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001209 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001210
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001211 // If this is the end of the buffer, we have an error.
1212 if (Tok.getKind() == tok::eof) {
1213 // Emit errors for each unterminated conditional on the stack, including
1214 // the current one.
1215 while (!CurLexer->ConditionalStack.empty()) {
1216 Diag(CurLexer->ConditionalStack.back().IfLoc,
1217 diag::err_pp_unterminated_conditional);
1218 CurLexer->ConditionalStack.pop_back();
1219 }
1220
1221 // Just return and let the caller lex after this #include.
1222 break;
1223 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001224
1225 // If this token is not a preprocessor directive, just skip it.
1226 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1227 continue;
1228
1229 // We just parsed a # character at the start of a line, so we're in
1230 // directive mode. Tell the lexer this so any newlines we see will be
1231 // converted into an EOM token (this terminates the macro).
1232 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001233 CurLexer->KeepCommentMode = false;
1234
Chris Lattner22eb9722006-06-18 05:43:12 +00001235
1236 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001237 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001238
1239 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1240 // something bogus), skip it.
1241 if (Tok.getKind() != tok::identifier) {
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 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001247
Chris Lattner22eb9722006-06-18 05:43:12 +00001248 // If the first letter isn't i or e, it isn't intesting to us. We know that
1249 // this is safe in the face of spelling differences, because there is no way
1250 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001251 // allows us to avoid looking up the identifier info for #define/#undef and
1252 // other common directives.
1253 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1254 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001255 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1256 FirstChar != 'i' && FirstChar != 'e') {
1257 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001258 // Restore comment saving mode.
1259 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001260 continue;
1261 }
1262
Chris Lattnere60165f2006-06-22 06:36:29 +00001263 // Get the identifier name without trigraphs or embedded newlines. Note
1264 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1265 // when skipping.
1266 // TODO: could do this with zero copies in the no-clean case by using
1267 // strncmp below.
1268 char Directive[20];
1269 unsigned IdLen;
1270 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1271 IdLen = Tok.getLength();
1272 memcpy(Directive, RawCharData, IdLen);
1273 Directive[IdLen] = 0;
1274 } else {
1275 std::string DirectiveStr = getSpelling(Tok);
1276 IdLen = DirectiveStr.size();
1277 if (IdLen >= 20) {
1278 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001279 // Restore comment saving mode.
1280 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001281 continue;
1282 }
1283 memcpy(Directive, &DirectiveStr[0], IdLen);
1284 Directive[IdLen] = 0;
1285 }
1286
Chris Lattner22eb9722006-06-18 05:43:12 +00001287 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001288 if ((IdLen == 2) || // "if"
1289 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1290 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001291 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1292 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001293 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001294 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001295 /*foundnonskip*/false,
1296 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001297 }
1298 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001299 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001300 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001301 PPConditionalInfo CondInfo;
1302 CondInfo.WasSkipping = true; // Silence bogus warning.
1303 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1304 assert(!InCond && "Can't be skipping if not in a conditional!");
1305
1306 // If we popped the outermost skipping block, we're done skipping!
1307 if (!CondInfo.WasSkipping)
1308 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001309 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 // #else directive in a skipping conditional. If not in some other
1311 // skipping conditional, and if #else hasn't already been seen, enter it
1312 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001313 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001314 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1315
1316 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001317 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001318
1319 // Note that we've seen a #else in this conditional.
1320 CondInfo.FoundElse = true;
1321
1322 // If the conditional is at the top level, and the #if block wasn't
1323 // entered, enter the #else block now.
1324 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1325 CondInfo.FoundNonSkip = true;
1326 break;
1327 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001328 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001329 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1330
1331 bool ShouldEnter;
1332 // If this is in a skipping block or if we're already handled this #if
1333 // block, don't bother parsing the condition.
1334 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001335 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001336 ShouldEnter = false;
1337 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001338 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001339 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001340 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1341 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001342 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001343 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001344 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 }
1346
1347 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001348 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001349
1350 // If this condition is true, enter it!
1351 if (ShouldEnter) {
1352 CondInfo.FoundNonSkip = true;
1353 break;
1354 }
1355 }
1356 }
1357
1358 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001359 // Restore comment saving mode.
1360 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001361 }
1362
1363 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1364 // of the file, just stop skipping and return to lexing whatever came after
1365 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001366 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001367}
1368
1369//===----------------------------------------------------------------------===//
1370// Preprocessor Directive Handling.
1371//===----------------------------------------------------------------------===//
1372
1373/// HandleDirective - This callback is invoked when the lexer sees a # token
1374/// at the start of a line. This consumes the directive, modifies the
1375/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1376/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001377void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001378 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001379
1380 // We just parsed a # character at the start of a line, so we're in directive
1381 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001382 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001383 CurLexer->ParsingPreprocessorDirective = true;
1384
1385 ++NumDirectives;
1386
Chris Lattner371ac8a2006-07-04 07:11:10 +00001387 // We are about to read a token. For the multiple-include optimization FA to
1388 // work, we have to remember if we had read any tokens *before* this
1389 // pp-directive.
1390 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1391
Chris Lattner78186052006-07-09 00:45:31 +00001392 // Read the next token, the directive flavor. This isn't expanded due to
1393 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001394 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001395
Chris Lattner78186052006-07-09 00:45:31 +00001396 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1397 // #define A(x) #x
1398 // A(abc
1399 // #warning blah
1400 // def)
1401 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001402 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001403 Diag(Result, diag::ext_embedded_directive);
1404
Chris Lattner22eb9722006-06-18 05:43:12 +00001405 switch (Result.getKind()) {
1406 default: break;
1407 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001408 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001409
1410#if 0
1411 case tok::numeric_constant:
1412 // FIXME: implement # 7 line numbers!
1413 break;
1414#endif
1415 case tok::kw_else:
1416 return HandleElseDirective(Result);
1417 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001418 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001419 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001420 // Get the identifier name without trigraphs or embedded newlines.
1421 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001422 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001423 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001424 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001425 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001426 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001427 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001428 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001429 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1430 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001431 break;
1432 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001433 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001434 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001435 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001436 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001437 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001438 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001439 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001440 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001441 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001442 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001443 break;
1444 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001445 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001446 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001447 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001448 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001449 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001450 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001451 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001452 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001453 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1454 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001455 break;
1456 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001457 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1458 return HandleIncludeDirective(Result); // Handle #include.
1459 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001460 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001461 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001462 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001463 break;
1464 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001465 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001466 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001467 }
1468 break;
1469 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001470 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1471 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001472 break;
1473 }
1474 break;
1475 }
1476
1477 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001478 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001479
1480 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001481 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001482
1483 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001484}
1485
Chris Lattner01d66cc2006-07-03 22:16:27 +00001486void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001487 bool isWarning) {
1488 // Read the rest of the line raw. We do this because we don't want macros
1489 // to be expanded and we don't require that the tokens be valid preprocessing
1490 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1491 // collapse multiple consequtive white space between tokens, but this isn't
1492 // specified by the standard.
1493 std::string Message = CurLexer->ReadToEndOfLine();
1494
1495 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001496 return Diag(Tok, DiagID, Message);
1497}
1498
1499/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1500///
1501void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001502 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001503 Diag(Tok, diag::ext_pp_ident_directive);
1504
Chris Lattner371ac8a2006-07-04 07:11:10 +00001505 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001506 LexerToken StrTok;
1507 Lex(StrTok);
1508
1509 // If the token kind isn't a string, it's a malformed directive.
1510 if (StrTok.getKind() != tok::string_literal)
1511 return Diag(StrTok, diag::err_pp_malformed_ident);
1512
1513 // Verify that there is nothing after the string, other than EOM.
1514 CheckEndOfDirective("#ident");
1515
1516 if (IdentHandler)
1517 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001518}
1519
Chris Lattnerb8761832006-06-24 21:31:03 +00001520//===----------------------------------------------------------------------===//
1521// Preprocessor Include Directive Handling.
1522//===----------------------------------------------------------------------===//
1523
Chris Lattner22eb9722006-06-18 05:43:12 +00001524/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1525/// file to be included from the lexer, then include it! This is a common
1526/// routine with functionality shared between #include, #include_next and
1527/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001528void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001529 const DirectoryLookup *LookupFrom,
1530 bool isImport) {
1531 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001532
Chris Lattner22eb9722006-06-18 05:43:12 +00001533 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001534 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001535
1536 // If the token kind is EOM, the error has already been diagnosed.
1537 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001538 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001539
1540 // Verify that there is nothing after the filename, other than EOM. Use the
1541 // preprocessor to lex this in case lexing the filename entered a macro.
1542 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001543
1544 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001545 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001546 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1547
Chris Lattner269c2322006-06-25 06:23:00 +00001548 // Find out whether the filename is <x> or "x".
1549 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001550
1551 // Remove the quotes.
1552 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1553
Chris Lattner22eb9722006-06-18 05:43:12 +00001554 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001555 const DirectoryLookup *CurDir;
1556 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001557 if (File == 0)
1558 return Diag(FilenameTok, diag::err_pp_file_not_found);
1559
1560 // Get information about this file.
1561 PerFileInfo &FileInfo = getFileInfo(File);
1562
1563 // If this is a #import directive, check that we have not already imported
1564 // this header.
1565 if (isImport) {
1566 // If this has already been imported, don't import it again.
1567 FileInfo.isImport = true;
1568
1569 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001570 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001571 } else {
1572 // Otherwise, if this is a #include of a file that was previously #import'd
1573 // or if this is the second #include of a #pragma once file, ignore it.
1574 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001575 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001576 }
Chris Lattner3665f162006-07-04 07:26:10 +00001577
1578 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1579 // if the macro that guards it is defined, we know the #include has no effect.
1580 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1581 ++NumMultiIncludeFileOptzn;
1582 return;
1583 }
1584
Chris Lattner22eb9722006-06-18 05:43:12 +00001585
1586 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001587 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001588 if (FileID == 0)
1589 return Diag(FilenameTok, diag::err_pp_file_not_found);
1590
1591 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001592 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001593
1594 // Increment the number of times this file has been included.
1595 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001596}
1597
1598/// HandleIncludeNextDirective - Implements #include_next.
1599///
Chris Lattnercb283342006-06-18 06:48:37 +00001600void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1601 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001602
1603 // #include_next is like #include, except that we start searching after
1604 // the current found directory. If we can't do this, issue a
1605 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001606 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001607 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001608 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001609 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001610 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001611 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001612 } else {
1613 // Start looking up in the next directory.
1614 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001615 }
1616
1617 return HandleIncludeDirective(IncludeNextTok, Lookup);
1618}
1619
1620/// HandleImportDirective - Implements #import.
1621///
Chris Lattnercb283342006-06-18 06:48:37 +00001622void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1623 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001624
1625 return HandleIncludeDirective(ImportTok, 0, true);
1626}
1627
Chris Lattnerb8761832006-06-24 21:31:03 +00001628//===----------------------------------------------------------------------===//
1629// Preprocessor Macro Directive Handling.
1630//===----------------------------------------------------------------------===//
1631
Chris Lattnercefc7682006-07-08 08:28:12 +00001632/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1633/// definition has just been read. Lex the rest of the arguments and the
1634/// closing ), updating MI with what we learn. Return true if an error occurs
1635/// parsing the arg list.
1636bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1637 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001638 while (1) {
1639 LexUnexpandedToken(Tok);
1640 switch (Tok.getKind()) {
1641 case tok::r_paren:
1642 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001643 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001644 // Otherwise we have #define FOO(A,)
1645 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1646 return true;
1647 case tok::ellipsis: // #define X(... -> C99 varargs
1648 // Warn if use of C99 feature in non-C99 mode.
1649 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1650
1651 // Lex the token after the identifier.
1652 LexUnexpandedToken(Tok);
1653 if (Tok.getKind() != tok::r_paren) {
1654 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1655 return true;
1656 }
1657 MI->setIsC99Varargs();
1658 return false;
1659 case tok::eom: // #define X(
1660 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1661 return true;
1662 default: // #define X(1
1663 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1664 return true;
1665 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001666 IdentifierInfo *II = Tok.getIdentifierInfo();
1667
1668 // If this is already used as an argument, it is used multiple times (e.g.
1669 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001670 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001671 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1672 return true;
1673 }
1674
1675 // Add the argument to the macro info.
1676 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001677
1678 // Lex the token after the identifier.
1679 LexUnexpandedToken(Tok);
1680
1681 switch (Tok.getKind()) {
1682 default: // #define X(A B
1683 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1684 return true;
1685 case tok::r_paren: // #define X(A)
1686 return false;
1687 case tok::comma: // #define X(A,
1688 break;
1689 case tok::ellipsis: // #define X(A... -> GCC extension
1690 // Diagnose extension.
1691 Diag(Tok, diag::ext_named_variadic_macro);
1692
1693 // Lex the token after the identifier.
1694 LexUnexpandedToken(Tok);
1695 if (Tok.getKind() != tok::r_paren) {
1696 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1697 return true;
1698 }
1699
1700 MI->setIsGNUVarargs();
1701 return false;
1702 }
1703 }
1704 }
1705}
1706
Chris Lattner22eb9722006-06-18 05:43:12 +00001707/// HandleDefineDirective - Implements #define. This consumes the entire macro
1708/// line then lets the caller lex the next real token.
1709///
Chris Lattnercb283342006-06-18 06:48:37 +00001710void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001711 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001712
Chris Lattner22eb9722006-06-18 05:43:12 +00001713 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001714 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001715
1716 // Error reading macro name? If so, diagnostic already issued.
1717 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001718 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001719
Chris Lattner457fc152006-07-29 06:30:25 +00001720 // If we are supposed to keep comments in #defines, reenable comment saving
1721 // mode.
1722 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1723
Chris Lattner50b497e2006-06-18 16:32:35 +00001724 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001725
1726 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001727 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001728
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001729 // If this is a function-like macro definition, parse the argument list,
1730 // marking each of the identifiers as being used as macro arguments. Also,
1731 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001732 if (Tok.getKind() == tok::eom) {
1733 // If there is no body to this macro, we have no special handling here.
1734 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001735 // This is a function-like macro definition. Read the argument list.
1736 MI->setIsFunctionLike();
1737 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001738 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001739 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001740 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001741 if (CurLexer->ParsingPreprocessorDirective)
1742 DiscardUntilEndOfDirective();
1743 return;
1744 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001745
Chris Lattner815a1f92006-07-08 20:48:04 +00001746 // Read the first token after the arg list for down below.
1747 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001748 } else if (!Tok.hasLeadingSpace()) {
1749 // C99 requires whitespace between the macro definition and the body. Emit
1750 // a diagnostic for something like "#define X+".
1751 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001752 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001753 } else {
1754 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1755 // one in some cases!
1756 }
1757 } else {
1758 // This is a normal token with leading space. Clear the leading space
1759 // marker on the first token to get proper expansion.
1760 Tok.ClearFlag(LexerToken::LeadingSpace);
1761 }
1762
Chris Lattner7e374832006-07-29 03:46:57 +00001763 // If this is a definition of a variadic C99 function-like macro, not using
1764 // the GNU named varargs extension, enabled __VA_ARGS__.
1765
1766 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1767 // This gets unpoisoned where it is allowed.
1768 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1769 if (MI->isC99Varargs())
1770 Ident__VA_ARGS__->setIsPoisoned(false);
1771
Chris Lattner22eb9722006-06-18 05:43:12 +00001772 // Read the rest of the macro body.
1773 while (Tok.getKind() != tok::eom) {
1774 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001775
1776 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001777 // parameters in function-like macro expansions.
1778 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001779 // Get the next token of the macro.
1780 LexUnexpandedToken(Tok);
1781 continue;
1782 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001783
Chris Lattner815a1f92006-07-08 20:48:04 +00001784 // Get the next token of the macro.
1785 LexUnexpandedToken(Tok);
1786
1787 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001788 if (!Tok.getIdentifierInfo() ||
Chris Lattnerf76e62e2006-07-29 07:14:41 +00001789 (MI->getArgumentNum(Tok.getIdentifierInfo()) == -1 &&
1790 Tok.getIdentifierInfo() != Ident__VA_ARGS__)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001791 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001792 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001793
1794 // Disable __VA_ARGS__ again.
1795 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001796 return;
1797 }
1798
1799 // Things look ok, add the param name token to the macro.
1800 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001801
Chris Lattner22eb9722006-06-18 05:43:12 +00001802 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001803 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001804 }
Chris Lattner7e374832006-07-29 03:46:57 +00001805
1806 // Disable __VA_ARGS__ again.
1807 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001808
Chris Lattnerbff18d52006-07-06 04:49:18 +00001809 // Check that there is no paste (##) operator at the begining or end of the
1810 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001811 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001812 if (NumTokens != 0) {
1813 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001814 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001815 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001816 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001817 }
1818 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001819 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001820 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001821 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001822 }
1823 }
1824
Chris Lattner13044d92006-07-03 05:16:44 +00001825 // If this is the primary source file, remember that this macro hasn't been
1826 // used yet.
1827 if (isInPrimaryFile())
1828 MI->setIsUsed(false);
1829
Chris Lattner22eb9722006-06-18 05:43:12 +00001830 // Finally, if this identifier already had a macro defined for it, verify that
1831 // the macro bodies are identical and free the old definition.
1832 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001833 if (!OtherMI->isUsed())
1834 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1835
Chris Lattner22eb9722006-06-18 05:43:12 +00001836 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001837 // must be the same. C99 6.10.3.2.
1838 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001839 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1840 MacroNameTok.getIdentifierInfo()->getName());
1841 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1842 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001843 delete OtherMI;
1844 }
1845
1846 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001847}
1848
1849
1850/// HandleUndefDirective - Implements #undef.
1851///
Chris Lattnercb283342006-06-18 06:48:37 +00001852void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001853 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001854
Chris Lattner22eb9722006-06-18 05:43:12 +00001855 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001856 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001857
1858 // Error reading macro name? If so, diagnostic already issued.
1859 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001860 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001861
1862 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001863 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001864
1865 // Okay, we finally have a valid identifier to undef.
1866 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1867
1868 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001869 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001870
Chris Lattner13044d92006-07-03 05:16:44 +00001871 if (!MI->isUsed())
1872 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001873
1874 // Free macro definition.
1875 delete MI;
1876 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001877}
1878
1879
Chris Lattnerb8761832006-06-24 21:31:03 +00001880//===----------------------------------------------------------------------===//
1881// Preprocessor Conditional Directive Handling.
1882//===----------------------------------------------------------------------===//
1883
Chris Lattner22eb9722006-06-18 05:43:12 +00001884/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001885/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1886/// if any tokens have been returned or pp-directives activated before this
1887/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001888///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001889void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1890 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001891 ++NumIf;
1892 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001893
Chris Lattner22eb9722006-06-18 05:43:12 +00001894 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001895 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001896
1897 // Error reading macro name? If so, diagnostic already issued.
1898 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001899 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001900
1901 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001902 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1903
1904 // If the start of a top-level #ifdef, inform MIOpt.
1905 if (!ReadAnyTokensBeforeDirective &&
1906 CurLexer->getConditionalStackDepth() == 0) {
1907 assert(isIfndef && "#ifdef shouldn't reach here");
1908 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1909 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001910
Chris Lattnera78a97e2006-07-03 05:42:18 +00001911 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1912
1913 // If there is a macro, mark it used.
1914 if (MI) MI->setIsUsed(true);
1915
Chris Lattner22eb9722006-06-18 05:43:12 +00001916 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001917 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001918 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001919 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001920 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001921 } else {
1922 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001923 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001924 /*Foundnonskip*/false,
1925 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001926 }
1927}
1928
1929/// HandleIfDirective - Implements the #if directive.
1930///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001931void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1932 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001933 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001934
Chris Lattner371ac8a2006-07-04 07:11:10 +00001935 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001936 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001937 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001938
1939 // Should we include the stuff contained by this directive?
1940 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001941 // If this condition is equivalent to #ifndef X, and if this is the first
1942 // directive seen, handle it for the multiple-include optimization.
1943 if (!ReadAnyTokensBeforeDirective &&
1944 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1945 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1946
Chris Lattner22eb9722006-06-18 05:43:12 +00001947 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001948 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001949 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001950 } else {
1951 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001952 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001953 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001954 }
1955}
1956
1957/// HandleEndifDirective - Implements the #endif directive.
1958///
Chris Lattnercb283342006-06-18 06:48:37 +00001959void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001960 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001961
Chris Lattner22eb9722006-06-18 05:43:12 +00001962 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001963 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001964
1965 PPConditionalInfo CondInfo;
1966 if (CurLexer->popConditionalLevel(CondInfo)) {
1967 // No conditionals on the stack: this is an #endif without an #if.
1968 return Diag(EndifToken, diag::err_pp_endif_without_if);
1969 }
1970
Chris Lattner371ac8a2006-07-04 07:11:10 +00001971 // If this the end of a top-level #endif, inform MIOpt.
1972 if (CurLexer->getConditionalStackDepth() == 0)
1973 CurLexer->MIOpt.ExitTopLevelConditional();
1974
Chris Lattner538d7f32006-07-20 04:31:52 +00001975 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001976 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001977}
1978
1979
Chris Lattnercb283342006-06-18 06:48:37 +00001980void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001981 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001982
Chris Lattner22eb9722006-06-18 05:43:12 +00001983 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001984 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001985
1986 PPConditionalInfo CI;
1987 if (CurLexer->popConditionalLevel(CI))
1988 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001989
1990 // If this is a top-level #else, inform the MIOpt.
1991 if (CurLexer->getConditionalStackDepth() == 0)
1992 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001993
1994 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001995 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001996
1997 // Finally, skip the rest of the contents of this block and return the first
1998 // token after it.
1999 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2000 /*FoundElse*/true);
2001}
2002
Chris Lattnercb283342006-06-18 06:48:37 +00002003void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002004 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002005
Chris Lattner22eb9722006-06-18 05:43:12 +00002006 // #elif directive in a non-skipping conditional... start skipping.
2007 // We don't care what the condition is, because we will always skip it (since
2008 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002009 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002010
2011 PPConditionalInfo CI;
2012 if (CurLexer->popConditionalLevel(CI))
2013 return Diag(ElifToken, diag::pp_err_elif_without_if);
2014
Chris Lattner371ac8a2006-07-04 07:11:10 +00002015 // If this is a top-level #elif, inform the MIOpt.
2016 if (CurLexer->getConditionalStackDepth() == 0)
2017 CurLexer->MIOpt.FoundTopLevelElse();
2018
Chris Lattner22eb9722006-06-18 05:43:12 +00002019 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002020 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002021
2022 // Finally, skip the rest of the contents of this block and return the first
2023 // token after it.
2024 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2025 /*FoundElse*/CI.FoundElse);
2026}
Chris Lattnerb8761832006-06-24 21:31:03 +00002027