blob: b0ce822d2869f6d72ee2e2a0d77c025f57c03562 [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) \
123 AddKeyword(#NAME+1, tok::kw##NAME, \
124 (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.
545 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000546}
547
Chris Lattnerc2395832006-07-09 00:57:04 +0000548
Chris Lattnerafe603f2006-07-11 04:02:46 +0000549/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
550/// lexed is a '('. If so, consume the token and return true, if not, this
551/// method should have no observable side-effect on the lexed tokens.
552bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000553 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000554 unsigned Val;
555 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000556 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000557 else
558 Val = CurMacroExpander->isNextTokenLParen();
559
560 if (Val == 2) {
561 // If we ran off the end of the lexer or macro expander, walk the include
562 // stack, looking for whatever will return the next token.
563 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
564 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
565 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000566 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000567 else
568 Val = Entry.TheMacroExpander->isNextTokenLParen();
569 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000570 }
571
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000572 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
573 // have found something that isn't a '(' or we found the end of the
574 // translation unit. In either case, return false.
575 if (Val != 1)
576 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000577
578 LexerToken Tok;
579 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000580 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
581 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000582}
Chris Lattner677757a2006-06-28 05:26:32 +0000583
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000584/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
585/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000586bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000587 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000588
589 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
590 if (MI->isBuiltinMacro()) {
591 ExpandBuiltinMacro(Identifier);
592 return false;
593 }
594
Chris Lattneree8760b2006-07-15 07:42:55 +0000595 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000596 /// for each macro argument, the list of tokens that were provided to the
597 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000598 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000599
600 // If this is a function-like macro, read the arguments.
601 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000602 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
603 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000604 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000605 return true;
606
Chris Lattner78186052006-07-09 00:45:31 +0000607 // Remember that we are now parsing the arguments to a macro invocation.
608 // Preprocessor directives used inside macro arguments are not portable, and
609 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000610 InMacroArgs = true;
611 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000612
613 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000614 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000615
616 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000617 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000618
619 ++NumFnMacroExpanded;
620 } else {
621 ++NumMacroExpanded;
622 }
Chris Lattner13044d92006-07-03 05:16:44 +0000623
624 // Notice that this macro has been used.
625 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000626
627 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000628
629 // If this macro expands to no tokens, don't bother to push it onto the
630 // expansion stack, only to take it right back off.
631 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000632 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000633 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000634
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000635 // Ignore this macro use, just return the next token in the current
636 // buffer.
637 bool HadLeadingSpace = Identifier.hasLeadingSpace();
638 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
639
640 Lex(Identifier);
641
642 // If the identifier isn't on some OTHER line, inherit the leading
643 // whitespace/first-on-a-line property of this token. This handles
644 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
645 // empty.
646 if (!Identifier.isAtStartOfLine()) {
647 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
648 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
649 }
650 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000651 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000652
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000653 } else if (MI->getNumTokens() == 1 &&
654 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000655 // Otherwise, if this macro expands into a single trivially-expanded
656 // token: expand it now. This handles common cases like
657 // "#define VAL 42".
658
659 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
660 // identifier to the expanded token.
661 bool isAtStartOfLine = Identifier.isAtStartOfLine();
662 bool hasLeadingSpace = Identifier.hasLeadingSpace();
663
664 // Remember where the token is instantiated.
665 SourceLocation InstantiateLoc = Identifier.getLocation();
666
667 // Replace the result token.
668 Identifier = MI->getReplacementToken(0);
669
670 // Restore the StartOfLine/LeadingSpace markers.
671 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
672 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
673
674 // Update the tokens location to include both its logical and physical
675 // locations.
676 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000677 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000678 Identifier.SetLocation(Loc);
679
Chris Lattner6e4bf522006-07-27 06:59:25 +0000680 // If this is #define X X, we must mark the result as unexpandible.
681 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
682 if (NewII->getMacroInfo() == MI)
683 Identifier.SetFlag(LexerToken::DisableExpand);
684
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000685 // Since this is not an identifier token, it can't be macro expanded, so
686 // we're done.
687 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000688 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000689 }
690
Chris Lattner78186052006-07-09 00:45:31 +0000691 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000692 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000693
694 // Now that the macro is at the top of the include stack, ask the
695 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000696 Lex(Identifier);
697 return false;
698}
699
Chris Lattneree8760b2006-07-15 07:42:55 +0000700/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000701/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000702/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000703MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
704 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000705 // The number of fixed arguments to parse.
706 unsigned NumFixedArgsLeft = MI->getNumArgs();
707 bool isVariadic = MI->isVariadic();
708
709 // If this is a C99-style varargs macro invocation, add an extra expected
Chris Lattner2ada5d32006-07-15 07:51:24 +0000710 // argument, which will catch all of the vararg args in one argument.
Chris Lattner78186052006-07-09 00:45:31 +0000711 if (MI->isC99Varargs())
712 ++NumFixedArgsLeft;
713
714 // Outer loop, while there are more arguments, keep reading them.
715 LexerToken Tok;
716 Tok.SetKind(tok::comma);
717 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000718
719 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000720 // argument is separated by an EOF token. Use a SmallVector so we can avoid
721 // heap allocations in the common case.
722 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000723
724 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000725 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000726 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
727 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000728
Chris Lattner78186052006-07-09 00:45:31 +0000729 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000730 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
731 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000732 LexUnexpandedToken(Tok);
733
734 if (Tok.getKind() == tok::eof) {
735 Diag(MacroName, diag::err_unterm_macro_invoc);
736 // Do not lose the EOF. Return it to the client.
737 MacroName = Tok;
738 return 0;
739 } else if (Tok.getKind() == tok::r_paren) {
740 // If we found the ) token, the macro arg list is done.
741 if (NumParens-- == 0)
742 break;
743 } else if (Tok.getKind() == tok::l_paren) {
744 ++NumParens;
745 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
746 // Comma ends this argument if there are more fixed arguments expected.
747 if (NumFixedArgsLeft)
748 break;
749
Chris Lattner2ada5d32006-07-15 07:51:24 +0000750 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000751 if (!isVariadic) {
752 // Emit the diagnostic at the macro name in case there is a missing ).
753 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000754 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000755 return 0;
756 }
757 // Otherwise, continue to add the tokens to this variable argument.
758 }
759
760 ArgTokens.push_back(Tok);
761 }
762
Chris Lattnera12dd152006-07-11 04:09:02 +0000763 // Empty arguments are standard in C99 and supported as an extension in
764 // other modes.
765 if (ArgTokens.empty() && !Features.C99)
766 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000767
Chris Lattner36b6e812006-07-21 06:38:30 +0000768 // Add a marker EOF token to the end of the token list for this argument.
769 LexerToken EOFTok;
770 EOFTok.StartToken();
771 EOFTok.SetKind(tok::eof);
772 EOFTok.SetLocation(Tok.getLocation());
773 EOFTok.SetLength(0);
774 ArgTokens.push_back(EOFTok);
775 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000776 --NumFixedArgsLeft;
777 };
778
779 // Okay, we either found the r_paren. Check to see if we parsed too few
780 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000781 unsigned MinArgsExpected = MI->getNumArgs();
782
783 // C99 expects us to pass at least one vararg arg (but as an extension, we
Chris Lattnerc2395832006-07-09 00:57:04 +0000784 // don't require this). GNU-style varargs already include the 'rest' name in
785 // the count.
786 MinArgsExpected += MI->isC99Varargs();
Chris Lattner78186052006-07-09 00:45:31 +0000787
Chris Lattner2ada5d32006-07-15 07:51:24 +0000788 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000789 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000790 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000791 // Varargs where the named vararg parameter is missing: ok as extension.
792 // #define A(x, ...)
793 // A("blah")
794 Diag(Tok, diag::ext_missing_varargs_arg);
795 } else if (MI->getNumArgs() == 1) {
796 // #define A(x)
797 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000798 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000799
800 // Empty arguments are standard in C99 and supported as an extension in
801 // other modes.
802 if (ArgTokens.empty() && !Features.C99)
803 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000804 } else {
805 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000806 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000807 return 0;
808 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000809
810 // Add a marker EOF token to the end of the token list for this argument.
811 SourceLocation EndLoc = Tok.getLocation();
812 Tok.StartToken();
813 Tok.SetKind(tok::eof);
814 Tok.SetLocation(EndLoc);
815 Tok.SetLength(0);
816 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000817 }
818
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000819 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size());
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000820}
821
Chris Lattnerc673f902006-06-30 06:10:41 +0000822/// ComputeDATE_TIME - Compute the current time, enter it into the specified
823/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
824/// the identifier tokens inserted.
825static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000826 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000827 time_t TT = time(0);
828 struct tm *TM = localtime(&TT);
829
830 static const char * const Months[] = {
831 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
832 };
833
834 char TmpBuffer[100];
835 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
836 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000837 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000838
839 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000840 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000841}
842
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000843/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
844/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000845void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000846 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000847 IdentifierInfo *II = Tok.getIdentifierInfo();
848 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000849
850 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
851 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000852 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000853 return Handle_Pragma(Tok);
854
Chris Lattner78186052006-07-09 00:45:31 +0000855 ++NumBuiltinMacroExpanded;
856
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000857 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000858
859 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000860 Tok.SetIdentifierInfo(0);
861 Tok.ClearFlag(LexerToken::NeedsCleaning);
862
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000863 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000864 // __LINE__ expands to a simple numeric value.
865 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
866 unsigned Length = strlen(TmpBuffer);
867 Tok.SetKind(tok::numeric_constant);
868 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000869 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000870 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000871 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000872 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000873 Diag(Tok, diag::ext_pp_base_file);
874 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
875 while (NextLoc.getFileID() != 0) {
876 Loc = NextLoc;
877 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
878 }
879 }
880
Chris Lattner0766e592006-07-03 01:07:01 +0000881 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
882 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000883 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner630b33c2006-07-01 22:46:53 +0000884 Tok.SetKind(tok::string_literal);
885 Tok.SetLength(FN.size());
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000886 Tok.SetLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000887 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000888 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000889 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000890 Tok.SetKind(tok::string_literal);
891 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
892 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000893 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000894 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000895 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000896 Tok.SetKind(tok::string_literal);
897 Tok.SetLength(strlen("\"hh:mm:ss\""));
898 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000899 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000900 Diag(Tok, diag::ext_pp_include_level);
901
902 // Compute the include depth of this token.
903 unsigned Depth = 0;
904 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
905 for (; Loc.getFileID() != 0; ++Depth)
906 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
907
908 // __INCLUDE_LEVEL__ expands to a simple numeric value.
909 sprintf(TmpBuffer, "%u", Depth);
910 unsigned Length = strlen(TmpBuffer);
911 Tok.SetKind(tok::numeric_constant);
912 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000913 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000914 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000915 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
916 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
917 Diag(Tok, diag::ext_pp_timestamp);
918
919 // Get the file that we are lexing out of. If we're currently lexing from
920 // a macro, dig into the include stack.
921 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000922 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000923
924 if (TheLexer)
925 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
926
927 // If this file is older than the file it depends on, emit a diagnostic.
928 const char *Result;
929 if (CurFile) {
930 time_t TT = CurFile->getModificationTime();
931 struct tm *TM = localtime(&TT);
932 Result = asctime(TM);
933 } else {
934 Result = "??? ??? ?? ??:??:?? ????\n";
935 }
936 TmpBuffer[0] = '"';
937 strcpy(TmpBuffer+1, Result);
938 unsigned Len = strlen(TmpBuffer);
939 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
940 Tok.SetKind(tok::string_literal);
941 Tok.SetLength(Len);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000942 Tok.SetLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000943 } else {
944 assert(0 && "Unknown identifier!");
945 }
946}
Chris Lattner677757a2006-06-28 05:26:32 +0000947
Chris Lattner13044d92006-07-03 05:16:44 +0000948namespace {
949struct UnusedIdentifierReporter : public IdentifierVisitor {
950 Preprocessor &PP;
951 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
952
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000953 void VisitIdentifier(IdentifierInfo &II) const {
954 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
955 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000956 }
957};
958}
959
Chris Lattner677757a2006-06-28 05:26:32 +0000960//===----------------------------------------------------------------------===//
961// Lexer Event Handling.
962//===----------------------------------------------------------------------===//
963
Chris Lattnercefc7682006-07-08 08:28:12 +0000964/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
965/// identifier information for the token and install it into the token.
966IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
967 const char *BufPtr) {
968 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
969 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
970
971 // Look up this token, see if it is a macro, or if it is a language keyword.
972 IdentifierInfo *II;
973 if (BufPtr && !Identifier.needsCleaning()) {
974 // No cleaning needed, just use the characters from the lexed buffer.
975 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
976 } else {
977 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
978 const char *TmpBuf = (char*)alloca(Identifier.getLength());
979 unsigned Size = getSpelling(Identifier, TmpBuf);
980 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
981 }
982 Identifier.SetIdentifierInfo(II);
983 return II;
984}
985
986
Chris Lattner677757a2006-06-28 05:26:32 +0000987/// HandleIdentifier - This callback is invoked when the lexer reads an
988/// identifier. This callback looks up the identifier in the map and/or
989/// potentially macro expands it or turns it into a named token (like 'for').
990void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000991 assert(Identifier.getIdentifierInfo() &&
992 "Can't handle identifiers without identifier info!");
993
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000994 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000995
996 // If this identifier was poisoned, and if it was not produced from a macro
997 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000998 if (II.isPoisoned() && CurLexer) {
999 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1000 Diag(Identifier, diag::err_pp_used_poisoned_id);
1001 else
1002 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1003 }
Chris Lattner677757a2006-06-28 05:26:32 +00001004
Chris Lattner78186052006-07-09 00:45:31 +00001005 // If this is a macro to be expanded, do it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001006 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner6e4bf522006-07-27 06:59:25 +00001007 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1008 if (MI->isEnabled()) {
1009 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1010 return;
1011 } else {
1012 // C99 6.10.3.4p2 says that a disabled macro may never again be
1013 // expanded, even if it's in a context where it could be expanded in the
1014 // future.
1015 Identifier.SetFlag(LexerToken::DisableExpand);
1016 }
1017 }
Chris Lattner677757a2006-06-28 05:26:32 +00001018
1019 // Change the kind of this identifier to the appropriate token kind, e.g.
1020 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001021 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001022
1023 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001024 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001025}
1026
Chris Lattner22eb9722006-06-18 05:43:12 +00001027/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1028/// the current file. This either returns the EOF token or pops a level off
1029/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001030bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001031 assert(!CurMacroExpander &&
1032 "Ending a file when currently in a macro!");
1033
Chris Lattner371ac8a2006-07-04 07:11:10 +00001034 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001035 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001036 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001037 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001038 // Okay, this has a controlling macro, remember in PerFileInfo.
1039 if (const FileEntry *FE =
1040 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1041 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001042 }
1043 }
1044
Chris Lattner22eb9722006-06-18 05:43:12 +00001045 // If this is a #include'd file, pop it off the include stack and continue
1046 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001047 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001048 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001049 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001050
1051 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001052 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001053 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1054
1055 // Get the file entry for the current file.
1056 if (const FileEntry *FE =
1057 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1058 FileType = getFileInfo(FE).DirInfo;
1059
Chris Lattner0c885f52006-06-21 06:50:18 +00001060 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001061 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001062 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001063
1064 // Client should lex another token.
1065 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001066 }
1067
Chris Lattnerd01e2912006-06-18 16:22:51 +00001068 Result.StartToken();
1069 CurLexer->BufferPtr = CurLexer->BufferEnd;
1070 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001071 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001072
1073 // We're done with the #included file.
1074 delete CurLexer;
1075 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001076
Chris Lattner03f83482006-07-10 06:16:26 +00001077 // This is the end of the top-level file. If the diag::pp_macro_not_used
1078 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1079 // have not been used.
1080 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1081 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001082
1083 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001084}
1085
1086/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001087/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001088bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001089 assert(CurMacroExpander && !CurLexer &&
1090 "Ending a macro when currently in a #include file!");
1091
Chris Lattner22eb9722006-06-18 05:43:12 +00001092 delete CurMacroExpander;
1093
Chris Lattner69772b02006-07-02 20:34:39 +00001094 // Handle this like a #include file being popped off the stack.
1095 CurMacroExpander = 0;
1096 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001097}
1098
1099
1100//===----------------------------------------------------------------------===//
1101// Utility Methods for Preprocessor Directive Handling.
1102//===----------------------------------------------------------------------===//
1103
1104/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1105/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001106void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001107 LexerToken Tmp;
1108 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001109 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001110 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001111}
1112
1113/// ReadMacroName - Lex and validate a macro name, which occurs after a
1114/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001115/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1116/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001117/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001118void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001119 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001120 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001121
1122 // Missing macro name?
1123 if (MacroNameTok.getKind() == tok::eom)
1124 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1125
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001126 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1127 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001128 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001129 // Fall through on error.
1130 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001131 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001132
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001133 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1134 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001135 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001136 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001137 } else if (isDefineUndef && II->getMacroInfo() &&
1138 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001139 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001140 if (isDefineUndef == 1)
1141 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1142 else
1143 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001144 } else {
1145 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001146 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001147 }
1148
Chris Lattner22eb9722006-06-18 05:43:12 +00001149 // Invalid macro name, read and discard the rest of the line. Then set the
1150 // token kind to tok::eom.
1151 MacroNameTok.SetKind(tok::eom);
1152 return DiscardUntilEndOfDirective();
1153}
1154
1155/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1156/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001157void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001158 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001159 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001160 // There should be no tokens after the directive, but we allow them as an
1161 // extension.
1162 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001163 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1164 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001165 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001166}
1167
1168
1169
1170/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1171/// decided that the subsequent tokens are in the #if'd out portion of the
1172/// file. Lex the rest of the file, until we see an #endif. If
1173/// FoundNonSkipPortion is true, then we have already emitted code for part of
1174/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1175/// is true, then #else directives are ok, if not, then we have already seen one
1176/// so a #else directive is a duplicate. When this returns, the caller can lex
1177/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001178void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001179 bool FoundNonSkipPortion,
1180 bool FoundElse) {
1181 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001182 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001183 "Lexing a macro, not a file?");
1184
1185 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1186 FoundNonSkipPortion, FoundElse);
1187
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001188 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1189 // disabling warnings, etc.
1190 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001191 LexerToken Tok;
1192 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001193 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001194
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001195 // If this is the end of the buffer, we have an error.
1196 if (Tok.getKind() == tok::eof) {
1197 // Emit errors for each unterminated conditional on the stack, including
1198 // the current one.
1199 while (!CurLexer->ConditionalStack.empty()) {
1200 Diag(CurLexer->ConditionalStack.back().IfLoc,
1201 diag::err_pp_unterminated_conditional);
1202 CurLexer->ConditionalStack.pop_back();
1203 }
1204
1205 // Just return and let the caller lex after this #include.
1206 break;
1207 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001208
1209 // If this token is not a preprocessor directive, just skip it.
1210 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1211 continue;
1212
1213 // We just parsed a # character at the start of a line, so we're in
1214 // directive mode. Tell the lexer this so any newlines we see will be
1215 // converted into an EOM token (this terminates the macro).
1216 CurLexer->ParsingPreprocessorDirective = true;
1217
1218 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001219 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001220
1221 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1222 // something bogus), skip it.
1223 if (Tok.getKind() != tok::identifier) {
1224 CurLexer->ParsingPreprocessorDirective = false;
1225 continue;
1226 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001227
Chris Lattner22eb9722006-06-18 05:43:12 +00001228 // If the first letter isn't i or e, it isn't intesting to us. We know that
1229 // this is safe in the face of spelling differences, because there is no way
1230 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001231 // allows us to avoid looking up the identifier info for #define/#undef and
1232 // other common directives.
1233 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1234 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001235 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1236 FirstChar != 'i' && FirstChar != 'e') {
1237 CurLexer->ParsingPreprocessorDirective = false;
1238 continue;
1239 }
1240
Chris Lattnere60165f2006-06-22 06:36:29 +00001241 // Get the identifier name without trigraphs or embedded newlines. Note
1242 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1243 // when skipping.
1244 // TODO: could do this with zero copies in the no-clean case by using
1245 // strncmp below.
1246 char Directive[20];
1247 unsigned IdLen;
1248 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1249 IdLen = Tok.getLength();
1250 memcpy(Directive, RawCharData, IdLen);
1251 Directive[IdLen] = 0;
1252 } else {
1253 std::string DirectiveStr = getSpelling(Tok);
1254 IdLen = DirectiveStr.size();
1255 if (IdLen >= 20) {
1256 CurLexer->ParsingPreprocessorDirective = false;
1257 continue;
1258 }
1259 memcpy(Directive, &DirectiveStr[0], IdLen);
1260 Directive[IdLen] = 0;
1261 }
1262
Chris Lattner22eb9722006-06-18 05:43:12 +00001263 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001264 if ((IdLen == 2) || // "if"
1265 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1266 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001267 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1268 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001269 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001270 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001271 /*foundnonskip*/false,
1272 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001273 }
1274 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001275 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001276 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001277 PPConditionalInfo CondInfo;
1278 CondInfo.WasSkipping = true; // Silence bogus warning.
1279 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1280 assert(!InCond && "Can't be skipping if not in a conditional!");
1281
1282 // If we popped the outermost skipping block, we're done skipping!
1283 if (!CondInfo.WasSkipping)
1284 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001285 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001286 // #else directive in a skipping conditional. If not in some other
1287 // skipping conditional, and if #else hasn't already been seen, enter it
1288 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001289 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001290 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1291
1292 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001293 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001294
1295 // Note that we've seen a #else in this conditional.
1296 CondInfo.FoundElse = true;
1297
1298 // If the conditional is at the top level, and the #if block wasn't
1299 // entered, enter the #else block now.
1300 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1301 CondInfo.FoundNonSkip = true;
1302 break;
1303 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001304 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001305 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1306
1307 bool ShouldEnter;
1308 // If this is in a skipping block or if we're already handled this #if
1309 // block, don't bother parsing the condition.
1310 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001311 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001312 ShouldEnter = false;
1313 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001314 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001315 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001316 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1317 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001318 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001319 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001320 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001321 }
1322
1323 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001324 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001325
1326 // If this condition is true, enter it!
1327 if (ShouldEnter) {
1328 CondInfo.FoundNonSkip = true;
1329 break;
1330 }
1331 }
1332 }
1333
1334 CurLexer->ParsingPreprocessorDirective = false;
1335 }
1336
1337 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1338 // of the file, just stop skipping and return to lexing whatever came after
1339 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001340 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001341}
1342
1343//===----------------------------------------------------------------------===//
1344// Preprocessor Directive Handling.
1345//===----------------------------------------------------------------------===//
1346
1347/// HandleDirective - This callback is invoked when the lexer sees a # token
1348/// at the start of a line. This consumes the directive, modifies the
1349/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1350/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001351void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001352 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001353
1354 // We just parsed a # character at the start of a line, so we're in directive
1355 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001356 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001357 CurLexer->ParsingPreprocessorDirective = true;
1358
1359 ++NumDirectives;
1360
Chris Lattner371ac8a2006-07-04 07:11:10 +00001361 // We are about to read a token. For the multiple-include optimization FA to
1362 // work, we have to remember if we had read any tokens *before* this
1363 // pp-directive.
1364 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1365
Chris Lattner78186052006-07-09 00:45:31 +00001366 // Read the next token, the directive flavor. This isn't expanded due to
1367 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001368 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001369
Chris Lattner78186052006-07-09 00:45:31 +00001370 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1371 // #define A(x) #x
1372 // A(abc
1373 // #warning blah
1374 // def)
1375 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001376 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001377 Diag(Result, diag::ext_embedded_directive);
1378
Chris Lattner22eb9722006-06-18 05:43:12 +00001379 switch (Result.getKind()) {
1380 default: break;
1381 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001382 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001383
1384#if 0
1385 case tok::numeric_constant:
1386 // FIXME: implement # 7 line numbers!
1387 break;
1388#endif
1389 case tok::kw_else:
1390 return HandleElseDirective(Result);
1391 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001392 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001393 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001394 // Get the identifier name without trigraphs or embedded newlines.
1395 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001396 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001397 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001398 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001399 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001400 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001401 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001402 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001403 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1404 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001405 break;
1406 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001407 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001408 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001409 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001410 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001411 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001412 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001413 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001414 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001415 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001416 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001417 break;
1418 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001419 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001420 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001421 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001422 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001423 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001424 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001425 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001426 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001427 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1428 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001429 break;
1430 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001431 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1432 return HandleIncludeDirective(Result); // Handle #include.
1433 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001434 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001435 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001436 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001437 break;
1438 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001439 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001440 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001441 }
1442 break;
1443 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001444 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1445 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001446 break;
1447 }
1448 break;
1449 }
1450
1451 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001452 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001453
1454 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001455 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001456
1457 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001458}
1459
Chris Lattner01d66cc2006-07-03 22:16:27 +00001460void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001461 bool isWarning) {
1462 // Read the rest of the line raw. We do this because we don't want macros
1463 // to be expanded and we don't require that the tokens be valid preprocessing
1464 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1465 // collapse multiple consequtive white space between tokens, but this isn't
1466 // specified by the standard.
1467 std::string Message = CurLexer->ReadToEndOfLine();
1468
1469 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001470 return Diag(Tok, DiagID, Message);
1471}
1472
1473/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1474///
1475void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001476 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001477 Diag(Tok, diag::ext_pp_ident_directive);
1478
Chris Lattner371ac8a2006-07-04 07:11:10 +00001479 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001480 LexerToken StrTok;
1481 Lex(StrTok);
1482
1483 // If the token kind isn't a string, it's a malformed directive.
1484 if (StrTok.getKind() != tok::string_literal)
1485 return Diag(StrTok, diag::err_pp_malformed_ident);
1486
1487 // Verify that there is nothing after the string, other than EOM.
1488 CheckEndOfDirective("#ident");
1489
1490 if (IdentHandler)
1491 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001492}
1493
Chris Lattnerb8761832006-06-24 21:31:03 +00001494//===----------------------------------------------------------------------===//
1495// Preprocessor Include Directive Handling.
1496//===----------------------------------------------------------------------===//
1497
Chris Lattner22eb9722006-06-18 05:43:12 +00001498/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1499/// file to be included from the lexer, then include it! This is a common
1500/// routine with functionality shared between #include, #include_next and
1501/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001502void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001503 const DirectoryLookup *LookupFrom,
1504 bool isImport) {
1505 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001506
Chris Lattner22eb9722006-06-18 05:43:12 +00001507 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001508 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001509
1510 // If the token kind is EOM, the error has already been diagnosed.
1511 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001512 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001513
1514 // Verify that there is nothing after the filename, other than EOM. Use the
1515 // preprocessor to lex this in case lexing the filename entered a macro.
1516 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001517
1518 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001519 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001520 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1521
Chris Lattner269c2322006-06-25 06:23:00 +00001522 // Find out whether the filename is <x> or "x".
1523 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001524
1525 // Remove the quotes.
1526 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1527
Chris Lattner22eb9722006-06-18 05:43:12 +00001528 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001529 const DirectoryLookup *CurDir;
1530 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001531 if (File == 0)
1532 return Diag(FilenameTok, diag::err_pp_file_not_found);
1533
1534 // Get information about this file.
1535 PerFileInfo &FileInfo = getFileInfo(File);
1536
1537 // If this is a #import directive, check that we have not already imported
1538 // this header.
1539 if (isImport) {
1540 // If this has already been imported, don't import it again.
1541 FileInfo.isImport = true;
1542
1543 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001544 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001545 } else {
1546 // Otherwise, if this is a #include of a file that was previously #import'd
1547 // or if this is the second #include of a #pragma once file, ignore it.
1548 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001549 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001550 }
Chris Lattner3665f162006-07-04 07:26:10 +00001551
1552 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1553 // if the macro that guards it is defined, we know the #include has no effect.
1554 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1555 ++NumMultiIncludeFileOptzn;
1556 return;
1557 }
1558
Chris Lattner22eb9722006-06-18 05:43:12 +00001559
1560 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001561 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001562 if (FileID == 0)
1563 return Diag(FilenameTok, diag::err_pp_file_not_found);
1564
1565 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001566 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001567
1568 // Increment the number of times this file has been included.
1569 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001570}
1571
1572/// HandleIncludeNextDirective - Implements #include_next.
1573///
Chris Lattnercb283342006-06-18 06:48:37 +00001574void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1575 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001576
1577 // #include_next is like #include, except that we start searching after
1578 // the current found directory. If we can't do this, issue a
1579 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001580 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001581 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001582 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001583 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001584 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001585 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001586 } else {
1587 // Start looking up in the next directory.
1588 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001589 }
1590
1591 return HandleIncludeDirective(IncludeNextTok, Lookup);
1592}
1593
1594/// HandleImportDirective - Implements #import.
1595///
Chris Lattnercb283342006-06-18 06:48:37 +00001596void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1597 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001598
1599 return HandleIncludeDirective(ImportTok, 0, true);
1600}
1601
Chris Lattnerb8761832006-06-24 21:31:03 +00001602//===----------------------------------------------------------------------===//
1603// Preprocessor Macro Directive Handling.
1604//===----------------------------------------------------------------------===//
1605
Chris Lattnercefc7682006-07-08 08:28:12 +00001606/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1607/// definition has just been read. Lex the rest of the arguments and the
1608/// closing ), updating MI with what we learn. Return true if an error occurs
1609/// parsing the arg list.
1610bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1611 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001612 while (1) {
1613 LexUnexpandedToken(Tok);
1614 switch (Tok.getKind()) {
1615 case tok::r_paren:
1616 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001617 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001618 // Otherwise we have #define FOO(A,)
1619 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1620 return true;
1621 case tok::ellipsis: // #define X(... -> C99 varargs
1622 // Warn if use of C99 feature in non-C99 mode.
1623 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1624
1625 // Lex the token after the identifier.
1626 LexUnexpandedToken(Tok);
1627 if (Tok.getKind() != tok::r_paren) {
1628 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1629 return true;
1630 }
1631 MI->setIsC99Varargs();
1632 return false;
1633 case tok::eom: // #define X(
1634 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1635 return true;
1636 default: // #define X(1
1637 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1638 return true;
1639 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001640 IdentifierInfo *II = Tok.getIdentifierInfo();
1641
1642 // If this is already used as an argument, it is used multiple times (e.g.
1643 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001644 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001645 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1646 return true;
1647 }
1648
1649 // Add the argument to the macro info.
1650 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001651
1652 // Lex the token after the identifier.
1653 LexUnexpandedToken(Tok);
1654
1655 switch (Tok.getKind()) {
1656 default: // #define X(A B
1657 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1658 return true;
1659 case tok::r_paren: // #define X(A)
1660 return false;
1661 case tok::comma: // #define X(A,
1662 break;
1663 case tok::ellipsis: // #define X(A... -> GCC extension
1664 // Diagnose extension.
1665 Diag(Tok, diag::ext_named_variadic_macro);
1666
1667 // Lex the token after the identifier.
1668 LexUnexpandedToken(Tok);
1669 if (Tok.getKind() != tok::r_paren) {
1670 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1671 return true;
1672 }
1673
1674 MI->setIsGNUVarargs();
1675 return false;
1676 }
1677 }
1678 }
1679}
1680
Chris Lattner22eb9722006-06-18 05:43:12 +00001681/// HandleDefineDirective - Implements #define. This consumes the entire macro
1682/// line then lets the caller lex the next real token.
1683///
Chris Lattnercb283342006-06-18 06:48:37 +00001684void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001685 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001686
Chris Lattner22eb9722006-06-18 05:43:12 +00001687 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001688 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001689
1690 // Error reading macro name? If so, diagnostic already issued.
1691 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001692 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001693
Chris Lattner50b497e2006-06-18 16:32:35 +00001694 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001695
1696 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001697 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001698
Chris Lattner78186052006-07-09 00:45:31 +00001699 // FIXME: Enable __VA_ARGS__.
1700
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001701 // If this is a function-like macro definition, parse the argument list,
1702 // marking each of the identifiers as being used as macro arguments. Also,
1703 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001704 if (Tok.getKind() == tok::eom) {
1705 // If there is no body to this macro, we have no special handling here.
1706 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001707 // This is a function-like macro definition. Read the argument list.
1708 MI->setIsFunctionLike();
1709 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001710 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001711 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001712 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001713 if (CurLexer->ParsingPreprocessorDirective)
1714 DiscardUntilEndOfDirective();
1715 return;
1716 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001717
Chris Lattner815a1f92006-07-08 20:48:04 +00001718 // Read the first token after the arg list for down below.
1719 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001720 } else if (!Tok.hasLeadingSpace()) {
1721 // C99 requires whitespace between the macro definition and the body. Emit
1722 // a diagnostic for something like "#define X+".
1723 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001724 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001725 } else {
1726 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1727 // one in some cases!
1728 }
1729 } else {
1730 // This is a normal token with leading space. Clear the leading space
1731 // marker on the first token to get proper expansion.
1732 Tok.ClearFlag(LexerToken::LeadingSpace);
1733 }
1734
1735 // Read the rest of the macro body.
1736 while (Tok.getKind() != tok::eom) {
1737 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001738
1739 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001740 // parameters in function-like macro expansions.
1741 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001742 // Get the next token of the macro.
1743 LexUnexpandedToken(Tok);
1744 continue;
1745 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001746
Chris Lattner815a1f92006-07-08 20:48:04 +00001747 // Get the next token of the macro.
1748 LexUnexpandedToken(Tok);
1749
1750 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001751 if (!Tok.getIdentifierInfo() ||
1752 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001753 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001754 delete MI;
1755 return;
1756 }
1757
1758 // Things look ok, add the param name token to the macro.
1759 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001760
Chris Lattner22eb9722006-06-18 05:43:12 +00001761 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001762 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001763 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001764
Chris Lattnerbff18d52006-07-06 04:49:18 +00001765 // Check that there is no paste (##) operator at the begining or end of the
1766 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001767 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001768 if (NumTokens != 0) {
1769 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001770 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001771 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001772 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001773 }
1774 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001775 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001776 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001777 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001778 }
1779 }
1780
Chris Lattner13044d92006-07-03 05:16:44 +00001781 // If this is the primary source file, remember that this macro hasn't been
1782 // used yet.
1783 if (isInPrimaryFile())
1784 MI->setIsUsed(false);
1785
Chris Lattner22eb9722006-06-18 05:43:12 +00001786 // Finally, if this identifier already had a macro defined for it, verify that
1787 // the macro bodies are identical and free the old definition.
1788 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001789 if (!OtherMI->isUsed())
1790 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1791
Chris Lattner22eb9722006-06-18 05:43:12 +00001792 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001793 // must be the same. C99 6.10.3.2.
1794 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001795 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1796 MacroNameTok.getIdentifierInfo()->getName());
1797 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1798 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001799 delete OtherMI;
1800 }
1801
1802 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001803}
1804
1805
1806/// HandleUndefDirective - Implements #undef.
1807///
Chris Lattnercb283342006-06-18 06:48:37 +00001808void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001809 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001810
Chris Lattner22eb9722006-06-18 05:43:12 +00001811 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001812 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001813
1814 // Error reading macro name? If so, diagnostic already issued.
1815 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001816 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001817
1818 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001819 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001820
1821 // Okay, we finally have a valid identifier to undef.
1822 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1823
1824 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001825 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001826
Chris Lattner13044d92006-07-03 05:16:44 +00001827 if (!MI->isUsed())
1828 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001829
1830 // Free macro definition.
1831 delete MI;
1832 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001833}
1834
1835
Chris Lattnerb8761832006-06-24 21:31:03 +00001836//===----------------------------------------------------------------------===//
1837// Preprocessor Conditional Directive Handling.
1838//===----------------------------------------------------------------------===//
1839
Chris Lattner22eb9722006-06-18 05:43:12 +00001840/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001841/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1842/// if any tokens have been returned or pp-directives activated before this
1843/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001844///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001845void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1846 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001847 ++NumIf;
1848 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001849
Chris Lattner22eb9722006-06-18 05:43:12 +00001850 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001851 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001852
1853 // Error reading macro name? If so, diagnostic already issued.
1854 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001855 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001856
1857 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001858 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1859
1860 // If the start of a top-level #ifdef, inform MIOpt.
1861 if (!ReadAnyTokensBeforeDirective &&
1862 CurLexer->getConditionalStackDepth() == 0) {
1863 assert(isIfndef && "#ifdef shouldn't reach here");
1864 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1865 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001866
Chris Lattnera78a97e2006-07-03 05:42:18 +00001867 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1868
1869 // If there is a macro, mark it used.
1870 if (MI) MI->setIsUsed(true);
1871
Chris Lattner22eb9722006-06-18 05:43:12 +00001872 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001873 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001874 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001875 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001876 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001877 } else {
1878 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001879 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001880 /*Foundnonskip*/false,
1881 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001882 }
1883}
1884
1885/// HandleIfDirective - Implements the #if directive.
1886///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001887void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1888 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001889 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001890
Chris Lattner371ac8a2006-07-04 07:11:10 +00001891 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001892 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001893 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001894
1895 // Should we include the stuff contained by this directive?
1896 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001897 // If this condition is equivalent to #ifndef X, and if this is the first
1898 // directive seen, handle it for the multiple-include optimization.
1899 if (!ReadAnyTokensBeforeDirective &&
1900 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1901 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1902
Chris Lattner22eb9722006-06-18 05:43:12 +00001903 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001904 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001905 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001906 } else {
1907 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001908 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001909 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001910 }
1911}
1912
1913/// HandleEndifDirective - Implements the #endif directive.
1914///
Chris Lattnercb283342006-06-18 06:48:37 +00001915void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001916 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001917
Chris Lattner22eb9722006-06-18 05:43:12 +00001918 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001919 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001920
1921 PPConditionalInfo CondInfo;
1922 if (CurLexer->popConditionalLevel(CondInfo)) {
1923 // No conditionals on the stack: this is an #endif without an #if.
1924 return Diag(EndifToken, diag::err_pp_endif_without_if);
1925 }
1926
Chris Lattner371ac8a2006-07-04 07:11:10 +00001927 // If this the end of a top-level #endif, inform MIOpt.
1928 if (CurLexer->getConditionalStackDepth() == 0)
1929 CurLexer->MIOpt.ExitTopLevelConditional();
1930
Chris Lattner538d7f32006-07-20 04:31:52 +00001931 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001932 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001933}
1934
1935
Chris Lattnercb283342006-06-18 06:48:37 +00001936void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001937 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001938
Chris Lattner22eb9722006-06-18 05:43:12 +00001939 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001940 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001941
1942 PPConditionalInfo CI;
1943 if (CurLexer->popConditionalLevel(CI))
1944 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001945
1946 // If this is a top-level #else, inform the MIOpt.
1947 if (CurLexer->getConditionalStackDepth() == 0)
1948 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001949
1950 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001951 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001952
1953 // Finally, skip the rest of the contents of this block and return the first
1954 // token after it.
1955 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1956 /*FoundElse*/true);
1957}
1958
Chris Lattnercb283342006-06-18 06:48:37 +00001959void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001960 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001961
Chris Lattner22eb9722006-06-18 05:43:12 +00001962 // #elif directive in a non-skipping conditional... start skipping.
1963 // We don't care what the condition is, because we will always skip it (since
1964 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001965 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001966
1967 PPConditionalInfo CI;
1968 if (CurLexer->popConditionalLevel(CI))
1969 return Diag(ElifToken, diag::pp_err_elif_without_if);
1970
Chris Lattner371ac8a2006-07-04 07:11:10 +00001971 // If this is a top-level #elif, inform the MIOpt.
1972 if (CurLexer->getConditionalStackDepth() == 0)
1973 CurLexer->MIOpt.FoundTopLevelElse();
1974
Chris Lattner22eb9722006-06-18 05:43:12 +00001975 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001976 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001977
1978 // Finally, skip the rest of the contents of this block and return the first
1979 // token after it.
1980 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1981 /*FoundElse*/CI.FoundElse);
1982}
Chris Lattnerb8761832006-06-24 21:31:03 +00001983