blob: fab5c69b6d57a4b918100759f117756ce5395b5f [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"
36#include <iostream>
37using namespace llvm;
38using namespace clang;
39
40//===----------------------------------------------------------------------===//
41
42Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
43 FileManager &FM, SourceManager &SM)
44 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
45 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000046 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000047 ScratchBuf = new ScratchBuffer(SourceMgr);
48
Chris Lattner22eb9722006-06-18 05:43:12 +000049 // Clear stats.
50 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
51 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000052 NumEnteredSourceFiles = 0;
53 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
54 NumFastMacroExpanded = 0;
Chris Lattner3665f162006-07-04 07:26:10 +000055 MaxIncludeStackDepth = 0; NumMultiIncludeFileOptzn = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000056 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000057
Chris Lattner22eb9722006-06-18 05:43:12 +000058 // Macro expansion is enabled.
59 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000060 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000061
62 // There is no file-change handler yet.
63 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000064 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000065
Chris Lattner8ff71992006-07-06 05:17:39 +000066 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
67 // This gets unpoisoned where it is allowed.
68 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
69
Chris Lattnerb8761832006-06-24 21:31:03 +000070 // Initialize the pragma handlers.
71 PragmaHandlers = new PragmaNamespace(0);
72 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000073
74 // Initialize builtin macros like __LINE__ and friends.
75 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000076}
77
78Preprocessor::~Preprocessor() {
79 // Free any active lexers.
80 delete CurLexer;
81
Chris Lattner69772b02006-07-02 20:34:39 +000082 while (!IncludeMacroStack.empty()) {
83 delete IncludeMacroStack.back().TheLexer;
84 delete IncludeMacroStack.back().TheMacroExpander;
85 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000086 }
Chris Lattnerb8761832006-06-24 21:31:03 +000087
88 // Release pragma information.
89 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000090
91 // Delete the scratch buffer info.
92 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000093}
94
95/// getFileInfo - Return the PerFileInfo structure for the specified
96/// FileEntry.
97Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
98 if (FE->getUID() >= FileInfo.size())
99 FileInfo.resize(FE->getUID()+1);
100 return FileInfo[FE->getUID()];
101}
102
103
104/// AddKeywords - Add all keywords to the symbol table.
105///
106void Preprocessor::AddKeywords() {
107 enum {
108 C90Shift = 0,
109 EXTC90 = 1 << C90Shift,
110 NOTC90 = 2 << C90Shift,
111 C99Shift = 2,
112 EXTC99 = 1 << C99Shift,
113 NOTC99 = 2 << C99Shift,
114 CPPShift = 4,
115 EXTCPP = 1 << CPPShift,
116 NOTCPP = 2 << CPPShift,
117 Mask = 3
118 };
119
120 // Add keywords and tokens for the current language.
121#define KEYWORD(NAME, FLAGS) \
122 AddKeyword(#NAME+1, tok::kw##NAME, \
123 (FLAGS >> C90Shift) & Mask, \
124 (FLAGS >> C99Shift) & Mask, \
125 (FLAGS >> CPPShift) & Mask);
126#define ALIAS(NAME, TOK) \
127 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
128#include "clang/Basic/TokenKinds.def"
129}
130
131/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
132/// the specified LexerToken's location, translating the token's start
133/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000134void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000135 const std::string &Msg) {
136 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
137 // warnings or extensions.
138 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000139 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000140
Chris Lattnercb283342006-06-18 06:48:37 +0000141 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000142}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000143
144void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
145 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
146 << getSpelling(Tok) << "'";
147
148 if (!DumpFlags) return;
149 std::cerr << "\t";
150 if (Tok.isAtStartOfLine())
151 std::cerr << " [StartOfLine]";
152 if (Tok.hasLeadingSpace())
153 std::cerr << " [LeadingSpace]";
154 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000155 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000156 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
157 << "']";
158 }
159}
160
161void Preprocessor::DumpMacro(const MacroInfo &MI) const {
162 std::cerr << "MACRO: ";
163 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
164 DumpToken(MI.getReplacementToken(i));
165 std::cerr << " ";
166 }
167 std::cerr << "\n";
168}
169
Chris Lattner22eb9722006-06-18 05:43:12 +0000170void Preprocessor::PrintStats() {
171 std::cerr << "\n*** Preprocessor Stats:\n";
172 std::cerr << FileInfo.size() << " files tracked.\n";
173 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
174 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
175 NumOnceOnlyFiles += FileInfo[i].isImport;
176 if (MaxNumIncludes < FileInfo[i].NumIncludes)
177 MaxNumIncludes = FileInfo[i].NumIncludes;
178 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
179 }
180 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
181 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
182 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
183
184 std::cerr << NumDirectives << " directives found:\n";
185 std::cerr << " " << NumDefined << " #define.\n";
186 std::cerr << " " << NumUndefined << " #undef.\n";
187 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
Chris Lattner3665f162006-07-04 07:26:10 +0000188 std::cerr << " " << NumMultiIncludeFileOptzn << " #includes skipped due to"
189 << " the multi-include optimization.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000190 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
191 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
192 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
193 std::cerr << " " << NumElse << " #else/#elif.\n";
194 std::cerr << " " << NumEndif << " #endif.\n";
195 std::cerr << " " << NumPragma << " #pragma.\n";
196 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
197
Chris Lattner78186052006-07-09 00:45:31 +0000198 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
199 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000200 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000201}
202
203//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000204// Token Spelling
205//===----------------------------------------------------------------------===//
206
207
208/// getSpelling() - Return the 'spelling' of this token. The spelling of a
209/// token are the characters used to represent the token in the source file
210/// after trigraph expansion and escaped-newline folding. In particular, this
211/// wants to get the true, uncanonicalized, spelling of things like digraphs
212/// UCNs, etc.
213std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
214 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
215
216 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000217 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218 if (!Tok.needsCleaning())
219 return std::string(TokStart, TokStart+Tok.getLength());
220
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 std::string Result;
222 Result.reserve(Tok.getLength());
223
Chris Lattneref9eae12006-07-04 22:33:12 +0000224 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
226 Ptr != End; ) {
227 unsigned CharSize;
228 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
229 Ptr += CharSize;
230 }
231 assert(Result.size() != unsigned(Tok.getLength()) &&
232 "NeedsCleaning flag set on something that didn't need cleaning!");
233 return Result;
234}
235
236/// getSpelling - This method is used to get the spelling of a token into a
237/// preallocated buffer, instead of as an std::string. The caller is required
238/// to allocate enough space for the token, which is guaranteed to be at least
239/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000240///
241/// Note that this method may do two possible things: it may either fill in
242/// the buffer specified with characters, or it may *change the input pointer*
243/// to point to a constant buffer with the data already in it (avoiding a
244/// copy). The caller is not allowed to modify the returned buffer pointer
245/// if an internal buffer is returned.
246unsigned Preprocessor::getSpelling(const LexerToken &Tok,
247 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000248 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
249
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000250 // If this token is an identifier, just return the string from the identifier
251 // table, which is very quick.
252 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
253 Buffer = II->getName();
254 return Tok.getLength();
255 }
256
257 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000258 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000259
260 // If this token contains nothing interesting, return it directly.
261 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000262 Buffer = TokStart;
263 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000264 }
265 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000266 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000267 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
268 Ptr != End; ) {
269 unsigned CharSize;
270 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
271 Ptr += CharSize;
272 }
273 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
274 "NeedsCleaning flag set on something that didn't need cleaning!");
275
276 return OutBuf-Buffer;
277}
278
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000279
280/// CreateString - Plop the specified string into a scratch buffer and return a
281/// location for it. If specified, the source location provides a source
282/// location for the token.
283SourceLocation Preprocessor::
284CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
285 if (SLoc.isValid())
286 return ScratchBuf->getToken(Buf, Len, SLoc);
287 return ScratchBuf->getToken(Buf, Len);
288}
289
290
Chris Lattnerd01e2912006-06-18 16:22:51 +0000291//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000292// Source File Location Methods.
293//===----------------------------------------------------------------------===//
294
295
296/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
297/// return null on failure. isAngled indicates whether the file reference is
298/// for system #include's or not (i.e. using <> instead of "").
299const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000300 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000301 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000302 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000303 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000304 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000305
306 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000307 // FIXME: Portability. This should be a sys::Path interface, this doesn't
308 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000309 if (Filename[0] == '/') {
310 // If this was an #include_next "/absolute/file", fail.
311 if (FromDir) return 0;
312
313 // Otherwise, just return the file.
314 return FileMgr.getFile(Filename);
315 }
316
317 // Step #0, unless disabled, check to see if the file is in the #includer's
318 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000319 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000320 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
321 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000322 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000323 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000324 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000325 if (const FileEntry *FE =
326 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000327 if (CurDirLookup)
328 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000329 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000330 CurDir = 0;
331
332 // This file is a system header or C++ unfriendly if the old file is.
333 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000334 return FE;
335 }
336 }
337 }
338
339 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000340 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000341
342 // If this is a #include_next request, start searching after the directory the
343 // file was found in.
344 if (FromDir)
345 i = FromDir-&SearchDirs[0];
346
347 // Check each directory in sequence to see if it contains this file.
348 for (; i != SearchDirs.size(); ++i) {
349 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000350 // FIXME: Portability. Adding file to dir should be in sys::Path.
351 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
352 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000353 CurDir = &SearchDirs[i];
354
355 // This file is a system header or C++ unfriendly if the dir is.
356 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000357 return FE;
358 }
359 }
360
361 // Otherwise, didn't find it.
362 return 0;
363}
364
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000365/// isInPrimaryFile - Return true if we're in the top-level file, not in a
366/// #include.
367bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000368 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000369 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000370
Chris Lattner13044d92006-07-03 05:16:44 +0000371 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000372 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000373 if (IncludeMacroStack[i].TheLexer &&
374 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
375 return IncludeMacroStack[i].TheLexer->isMainFile();
376 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000377}
378
379/// getCurrentLexer - Return the current file lexer being lexed from. Note
380/// that this ignores any potentially active macro expansions and _Pragma
381/// expansions going on at the time.
382Lexer *Preprocessor::getCurrentFileLexer() const {
383 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
384
385 // Look for a stacked lexer.
386 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000387 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000388 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
389 return L;
390 }
391 return 0;
392}
393
394
Chris Lattner22eb9722006-06-18 05:43:12 +0000395/// EnterSourceFile - Add a source file to the top of the include stack and
396/// start lexing tokens from it instead of the current buffer. Return true
397/// on failure.
398void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000399 const DirectoryLookup *CurDir,
400 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000401 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000402 ++NumEnteredSourceFiles;
403
Chris Lattner69772b02006-07-02 20:34:39 +0000404 if (MaxIncludeStackDepth < IncludeMacroStack.size())
405 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000406
Chris Lattner22eb9722006-06-18 05:43:12 +0000407 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000408 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000409 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000410 EnterSourceFileWithLexer(TheLexer, CurDir);
411}
Chris Lattner22eb9722006-06-18 05:43:12 +0000412
Chris Lattner69772b02006-07-02 20:34:39 +0000413/// EnterSourceFile - Add a source file to the top of the include stack and
414/// start lexing tokens from it instead of the current buffer.
415void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
416 const DirectoryLookup *CurDir) {
417
418 // Add the current lexer to the include stack.
419 if (CurLexer || CurMacroExpander)
420 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
421 CurMacroExpander));
422
423 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000424 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000425 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000426
427 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000428 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000429 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
430
431 // Get the file entry for the current file.
432 if (const FileEntry *FE =
433 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
434 FileType = getFileInfo(FE).DirInfo;
435
Chris Lattner1840e492006-07-02 22:30:01 +0000436 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000437 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000438 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000439}
440
Chris Lattner69772b02006-07-02 20:34:39 +0000441
442
Chris Lattner22eb9722006-06-18 05:43:12 +0000443/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000444/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000445void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000446 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000447 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000448 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
449 CurMacroExpander));
450 CurLexer = 0;
451 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000452
Chris Lattneree8760b2006-07-15 07:42:55 +0000453 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000454}
455
Chris Lattner7667d0d2006-07-16 18:16:58 +0000456/// EnterTokenStream - Add a "macro" context to the top of the include stack,
457/// which will cause the lexer to start returning the specified tokens. Note
458/// that these tokens will be re-macro-expanded when/if expansion is enabled.
459/// This method assumes that the specified stream of tokens has a permanent
460/// owner somewhere, so they do not need to be copied.
461void Preprocessor::EnterTokenStream(const std::vector<LexerToken> &Stream) {
462 // Save our current state.
463 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
464 CurMacroExpander));
465 CurLexer = 0;
466 CurDirLookup = 0;
467
468 // Create a macro expander to expand from the specified token stream.
469 CurMacroExpander = new MacroExpander(Stream, *this);
470}
471
472/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
473/// lexer stack. This should only be used in situations where the current
474/// state of the top-of-stack lexer is known.
475void Preprocessor::RemoveTopOfLexerStack() {
476 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
477 delete CurLexer;
478 delete CurMacroExpander;
479 CurLexer = IncludeMacroStack.back().TheLexer;
480 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
481 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
482 IncludeMacroStack.pop_back();
483}
484
Chris Lattner22eb9722006-06-18 05:43:12 +0000485//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000486// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000487//===----------------------------------------------------------------------===//
488
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000489/// RegisterBuiltinMacro - Register the specified identifier in the identifier
490/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000491IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000492 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000493 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000494
495 // Mark it as being a macro that is builtin.
496 MacroInfo *MI = new MacroInfo(SourceLocation());
497 MI->setIsBuiltinMacro();
498 Id->setMacroInfo(MI);
499 return Id;
500}
501
502
Chris Lattner677757a2006-06-28 05:26:32 +0000503/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
504/// identifier table.
505void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000506 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000507 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000508 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
509 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000510 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000511
512 // GCC Extensions.
513 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
514 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000515 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000516}
517
Chris Lattnerc2395832006-07-09 00:57:04 +0000518/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
519/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000520static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
521 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000522 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
523
524 // If the token isn't an identifier, it's always literally expanded.
525 if (II == 0) return true;
526
527 // If the identifier is a macro, and if that macro is enabled, it may be
528 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000529 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
530 // Fast expanding "#define X X" is ok, because X would be disabled.
531 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000532 return false;
533
534 // If this is an object-like macro invocation, it is safe to trivially expand
535 // it.
536 if (MI->isObjectLike()) return true;
537
538 // If this is a function-like macro invocation, it's safe to trivially expand
539 // as long as the identifier is not a macro argument.
540 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
541 I != E; ++I)
542 if (*I == II)
543 return false; // Identifier is a macro argument.
544 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000545}
546
Chris Lattnerc2395832006-07-09 00:57:04 +0000547
Chris Lattnerafe603f2006-07-11 04:02:46 +0000548/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
549/// lexed is a '('. If so, consume the token and return true, if not, this
550/// method should have no observable side-effect on the lexed tokens.
551bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000552 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000553 unsigned Val;
554 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000555 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000556 else
557 Val = CurMacroExpander->isNextTokenLParen();
558
559 if (Val == 2) {
560 // If we ran off the end of the lexer or macro expander, walk the include
561 // stack, looking for whatever will return the next token.
562 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
563 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
564 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000565 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000566 else
567 Val = Entry.TheMacroExpander->isNextTokenLParen();
568 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000569 }
570
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000571 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
572 // have found something that isn't a '(' or we found the end of the
573 // translation unit. In either case, return false.
574 if (Val != 1)
575 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000576
577 LexerToken Tok;
578 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000579 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
580 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000581}
Chris Lattner677757a2006-06-28 05:26:32 +0000582
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000583/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
584/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000585bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000586 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000587
588 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
589 if (MI->isBuiltinMacro()) {
590 ExpandBuiltinMacro(Identifier);
591 return false;
592 }
593
Chris Lattneree8760b2006-07-15 07:42:55 +0000594 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000595 /// for each macro argument, the list of tokens that were provided to the
596 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000597 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000598
599 // If this is a function-like macro, read the arguments.
600 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000601 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
602 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000603 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000604 return true;
605
Chris Lattner78186052006-07-09 00:45:31 +0000606 // Remember that we are now parsing the arguments to a macro invocation.
607 // Preprocessor directives used inside macro arguments are not portable, and
608 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000609 InMacroArgs = true;
610 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000611
612 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000613 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000614
615 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000616 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000617
618 ++NumFnMacroExpanded;
619 } else {
620 ++NumMacroExpanded;
621 }
Chris Lattner13044d92006-07-03 05:16:44 +0000622
623 // Notice that this macro has been used.
624 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000625
626 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000627
628 // If this macro expands to no tokens, don't bother to push it onto the
629 // expansion stack, only to take it right back off.
630 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000631 // No need for arg info.
Chris Lattneree8760b2006-07-15 07:42:55 +0000632 delete Args;
Chris Lattner78186052006-07-09 00:45:31 +0000633
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000634 // Ignore this macro use, just return the next token in the current
635 // buffer.
636 bool HadLeadingSpace = Identifier.hasLeadingSpace();
637 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
638
639 Lex(Identifier);
640
641 // If the identifier isn't on some OTHER line, inherit the leading
642 // whitespace/first-on-a-line property of this token. This handles
643 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
644 // empty.
645 if (!Identifier.isAtStartOfLine()) {
646 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
647 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
648 }
649 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000650 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000651
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000652 } else if (MI->getNumTokens() == 1 &&
653 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000654 // Otherwise, if this macro expands into a single trivially-expanded
655 // token: expand it now. This handles common cases like
656 // "#define VAL 42".
657
658 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
659 // identifier to the expanded token.
660 bool isAtStartOfLine = Identifier.isAtStartOfLine();
661 bool hasLeadingSpace = Identifier.hasLeadingSpace();
662
663 // Remember where the token is instantiated.
664 SourceLocation InstantiateLoc = Identifier.getLocation();
665
666 // Replace the result token.
667 Identifier = MI->getReplacementToken(0);
668
669 // Restore the StartOfLine/LeadingSpace markers.
670 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
671 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
672
673 // Update the tokens location to include both its logical and physical
674 // locations.
675 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000676 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000677 Identifier.SetLocation(Loc);
678
679 // Since this is not an identifier token, it can't be macro expanded, so
680 // we're done.
681 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000682 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000683 }
684
Chris Lattner78186052006-07-09 00:45:31 +0000685 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000686 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000687
688 // Now that the macro is at the top of the include stack, ask the
689 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000690 Lex(Identifier);
691 return false;
692}
693
Chris Lattneree8760b2006-07-15 07:42:55 +0000694/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000695/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000696/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000697MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
698 MacroInfo *MI) {
699 // Use an auto_ptr here so that the MacroArgs object is deleted on
Chris Lattner78186052006-07-09 00:45:31 +0000700 // all error paths.
Chris Lattneree8760b2006-07-15 07:42:55 +0000701 std::auto_ptr<MacroArgs> Args(new MacroArgs(MI));
Chris Lattner78186052006-07-09 00:45:31 +0000702
703 // The number of fixed arguments to parse.
704 unsigned NumFixedArgsLeft = MI->getNumArgs();
705 bool isVariadic = MI->isVariadic();
706
707 // If this is a C99-style varargs macro invocation, add an extra expected
Chris Lattner2ada5d32006-07-15 07:51:24 +0000708 // argument, which will catch all of the vararg args in one argument.
Chris Lattner78186052006-07-09 00:45:31 +0000709 if (MI->isC99Varargs())
710 ++NumFixedArgsLeft;
711
712 // Outer loop, while there are more arguments, keep reading them.
713 LexerToken Tok;
714 Tok.SetKind(tok::comma);
715 --NumFixedArgsLeft; // Start reading the first arg.
716
717 while (Tok.getKind() == tok::comma) {
718 // ArgTokens - Build up a list of tokens that make up this argument.
719 std::vector<LexerToken> ArgTokens;
720 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
721 unsigned NumParens = 0;
722
723 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000724 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
725 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000726 LexUnexpandedToken(Tok);
727
728 if (Tok.getKind() == tok::eof) {
729 Diag(MacroName, diag::err_unterm_macro_invoc);
730 // Do not lose the EOF. Return it to the client.
731 MacroName = Tok;
732 return 0;
733 } else if (Tok.getKind() == tok::r_paren) {
734 // If we found the ) token, the macro arg list is done.
735 if (NumParens-- == 0)
736 break;
737 } else if (Tok.getKind() == tok::l_paren) {
738 ++NumParens;
739 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
740 // Comma ends this argument if there are more fixed arguments expected.
741 if (NumFixedArgsLeft)
742 break;
743
Chris Lattner2ada5d32006-07-15 07:51:24 +0000744 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000745 if (!isVariadic) {
746 // Emit the diagnostic at the macro name in case there is a missing ).
747 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000748 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000749 return 0;
750 }
751 // Otherwise, continue to add the tokens to this variable argument.
752 }
753
754 ArgTokens.push_back(Tok);
755 }
756
Chris Lattnera12dd152006-07-11 04:09:02 +0000757 // Empty arguments are standard in C99 and supported as an extension in
758 // other modes.
759 if (ArgTokens.empty() && !Features.C99)
760 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000761
Chris Lattner78186052006-07-09 00:45:31 +0000762 // Remember the tokens that make up this argument. This destroys ArgTokens.
Chris Lattneree8760b2006-07-15 07:42:55 +0000763 Args->addArgument(ArgTokens, Tok.getLocation());
Chris Lattner78186052006-07-09 00:45:31 +0000764 --NumFixedArgsLeft;
765 };
766
767 // Okay, we either found the r_paren. Check to see if we parsed too few
768 // arguments.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000769 unsigned NumActuals = Args->getNumArguments();
Chris Lattner78186052006-07-09 00:45:31 +0000770 unsigned MinArgsExpected = MI->getNumArgs();
771
772 // C99 expects us to pass at least one vararg arg (but as an extension, we
Chris Lattnerc2395832006-07-09 00:57:04 +0000773 // don't require this). GNU-style varargs already include the 'rest' name in
774 // the count.
775 MinArgsExpected += MI->isC99Varargs();
Chris Lattner78186052006-07-09 00:45:31 +0000776
Chris Lattner2ada5d32006-07-15 07:51:24 +0000777 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000778 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000779 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000780 // Varargs where the named vararg parameter is missing: ok as extension.
781 // #define A(x, ...)
782 // A("blah")
783 Diag(Tok, diag::ext_missing_varargs_arg);
784 } else if (MI->getNumArgs() == 1) {
785 // #define A(x)
786 // A()
Chris Lattnerafe603f2006-07-11 04:02:46 +0000787 // is ok because it is an empty argument. Add it explicitly.
Chris Lattner78186052006-07-09 00:45:31 +0000788 std::vector<LexerToken> ArgTokens;
Chris Lattneree8760b2006-07-15 07:42:55 +0000789 Args->addArgument(ArgTokens, Tok.getLocation());
Chris Lattnera12dd152006-07-11 04:09:02 +0000790
791 // Empty arguments are standard in C99 and supported as an extension in
792 // other modes.
793 if (ArgTokens.empty() && !Features.C99)
794 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000795 } else {
796 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000797 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000798 return 0;
799 }
800 }
801
802 return Args.release();
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000803}
804
Chris Lattnerc673f902006-06-30 06:10:41 +0000805/// ComputeDATE_TIME - Compute the current time, enter it into the specified
806/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
807/// the identifier tokens inserted.
808static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000809 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000810 time_t TT = time(0);
811 struct tm *TM = localtime(&TT);
812
813 static const char * const Months[] = {
814 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
815 };
816
817 char TmpBuffer[100];
818 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
819 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000820 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000821
822 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000823 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000824}
825
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000826/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
827/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000828void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000829 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000830 IdentifierInfo *II = Tok.getIdentifierInfo();
831 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000832
833 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
834 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000835 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000836 return Handle_Pragma(Tok);
837
Chris Lattner78186052006-07-09 00:45:31 +0000838 ++NumBuiltinMacroExpanded;
839
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000840 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000841
842 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000843 Tok.SetIdentifierInfo(0);
844 Tok.ClearFlag(LexerToken::NeedsCleaning);
845
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000846 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000847 // __LINE__ expands to a simple numeric value.
848 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
849 unsigned Length = strlen(TmpBuffer);
850 Tok.SetKind(tok::numeric_constant);
851 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000852 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000853 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000854 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000855 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000856 Diag(Tok, diag::ext_pp_base_file);
857 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
858 while (NextLoc.getFileID() != 0) {
859 Loc = NextLoc;
860 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
861 }
862 }
863
Chris Lattner0766e592006-07-03 01:07:01 +0000864 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
865 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000866 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner630b33c2006-07-01 22:46:53 +0000867 Tok.SetKind(tok::string_literal);
868 Tok.SetLength(FN.size());
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000869 Tok.SetLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000870 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000871 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000872 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000873 Tok.SetKind(tok::string_literal);
874 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
875 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000876 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000877 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000878 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000879 Tok.SetKind(tok::string_literal);
880 Tok.SetLength(strlen("\"hh:mm:ss\""));
881 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000882 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000883 Diag(Tok, diag::ext_pp_include_level);
884
885 // Compute the include depth of this token.
886 unsigned Depth = 0;
887 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
888 for (; Loc.getFileID() != 0; ++Depth)
889 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
890
891 // __INCLUDE_LEVEL__ expands to a simple numeric value.
892 sprintf(TmpBuffer, "%u", Depth);
893 unsigned Length = strlen(TmpBuffer);
894 Tok.SetKind(tok::numeric_constant);
895 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000896 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000897 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000898 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
899 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
900 Diag(Tok, diag::ext_pp_timestamp);
901
902 // Get the file that we are lexing out of. If we're currently lexing from
903 // a macro, dig into the include stack.
904 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000905 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000906
907 if (TheLexer)
908 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
909
910 // If this file is older than the file it depends on, emit a diagnostic.
911 const char *Result;
912 if (CurFile) {
913 time_t TT = CurFile->getModificationTime();
914 struct tm *TM = localtime(&TT);
915 Result = asctime(TM);
916 } else {
917 Result = "??? ??? ?? ??:??:?? ????\n";
918 }
919 TmpBuffer[0] = '"';
920 strcpy(TmpBuffer+1, Result);
921 unsigned Len = strlen(TmpBuffer);
922 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
923 Tok.SetKind(tok::string_literal);
924 Tok.SetLength(Len);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000925 Tok.SetLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000926 } else {
927 assert(0 && "Unknown identifier!");
928 }
929}
Chris Lattner677757a2006-06-28 05:26:32 +0000930
Chris Lattner13044d92006-07-03 05:16:44 +0000931namespace {
932struct UnusedIdentifierReporter : public IdentifierVisitor {
933 Preprocessor &PP;
934 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
935
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000936 void VisitIdentifier(IdentifierInfo &II) const {
937 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
938 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000939 }
940};
941}
942
Chris Lattner677757a2006-06-28 05:26:32 +0000943//===----------------------------------------------------------------------===//
944// Lexer Event Handling.
945//===----------------------------------------------------------------------===//
946
Chris Lattnercefc7682006-07-08 08:28:12 +0000947/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
948/// identifier information for the token and install it into the token.
949IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
950 const char *BufPtr) {
951 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
952 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
953
954 // Look up this token, see if it is a macro, or if it is a language keyword.
955 IdentifierInfo *II;
956 if (BufPtr && !Identifier.needsCleaning()) {
957 // No cleaning needed, just use the characters from the lexed buffer.
958 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
959 } else {
960 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
961 const char *TmpBuf = (char*)alloca(Identifier.getLength());
962 unsigned Size = getSpelling(Identifier, TmpBuf);
963 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
964 }
965 Identifier.SetIdentifierInfo(II);
966 return II;
967}
968
969
Chris Lattner677757a2006-06-28 05:26:32 +0000970/// HandleIdentifier - This callback is invoked when the lexer reads an
971/// identifier. This callback looks up the identifier in the map and/or
972/// potentially macro expands it or turns it into a named token (like 'for').
973void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
974 if (Identifier.getIdentifierInfo() == 0) {
975 // If we are skipping tokens (because we are in a #if 0 block), there will
976 // be no identifier info, just return the token.
977 assert(isSkipping() && "Token isn't an identifier?");
978 return;
979 }
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000980 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000981
982 // If this identifier was poisoned, and if it was not produced from a macro
983 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000984 if (II.isPoisoned() && CurLexer) {
985 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
986 Diag(Identifier, diag::err_pp_used_poisoned_id);
987 else
988 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
989 }
Chris Lattner677757a2006-06-28 05:26:32 +0000990
Chris Lattner78186052006-07-09 00:45:31 +0000991 // If this is a macro to be expanded, do it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000992 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +0000993 if (MI->isEnabled() && !DisableMacroExpansion)
Chris Lattner78186052006-07-09 00:45:31 +0000994 if (!HandleMacroExpandedIdentifier(Identifier, MI))
995 return;
Chris Lattner677757a2006-06-28 05:26:32 +0000996
997 // Change the kind of this identifier to the appropriate token kind, e.g.
998 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000999 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001000
1001 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001002 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001003}
1004
Chris Lattner22eb9722006-06-18 05:43:12 +00001005/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1006/// the current file. This either returns the EOF token or pops a level off
1007/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +00001008void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001009 assert(!CurMacroExpander &&
1010 "Ending a file when currently in a macro!");
1011
1012 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
1013 // this is an error condition. Just return the EOF token up to
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001014 // SkipExcludedConditionalBlock. The code that enabled skipping will issue
1015 // errors for the unterminated #if's on the conditional stack if it is
1016 // interested.
Chris Lattner22eb9722006-06-18 05:43:12 +00001017 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +00001018 Result.StartToken();
1019 CurLexer->BufferPtr = CurLexer->BufferEnd;
1020 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001021 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +00001022 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001023 }
1024
Chris Lattner371ac8a2006-07-04 07:11:10 +00001025 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001026 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001027 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001028 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001029 // Okay, this has a controlling macro, remember in PerFileInfo.
1030 if (const FileEntry *FE =
1031 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1032 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001033 }
1034 }
1035
Chris Lattner22eb9722006-06-18 05:43:12 +00001036 // If this is a #include'd file, pop it off the include stack and continue
1037 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001038 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001039 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001040 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001041
1042 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001043 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001044 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1045
1046 // Get the file entry for the current file.
1047 if (const FileEntry *FE =
1048 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1049 FileType = getFileInfo(FE).DirInfo;
1050
Chris Lattner0c885f52006-06-21 06:50:18 +00001051 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001052 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001053 }
Chris Lattner0c885f52006-06-21 06:50:18 +00001054
Chris Lattner22eb9722006-06-18 05:43:12 +00001055 return Lex(Result);
1056 }
1057
Chris Lattnerd01e2912006-06-18 16:22:51 +00001058 Result.StartToken();
1059 CurLexer->BufferPtr = CurLexer->BufferEnd;
1060 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001061 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001062
1063 // We're done with the #included file.
1064 delete CurLexer;
1065 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001066
Chris Lattner03f83482006-07-10 06:16:26 +00001067 // This is the end of the top-level file. If the diag::pp_macro_not_used
1068 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1069 // have not been used.
1070 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1071 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +00001072}
1073
1074/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001075/// the current macro expansion or token stream expansion.
Chris Lattnercb283342006-06-18 06:48:37 +00001076void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001077 assert(CurMacroExpander && !CurLexer &&
1078 "Ending a macro when currently in a #include file!");
1079
Chris Lattner22eb9722006-06-18 05:43:12 +00001080 delete CurMacroExpander;
1081
Chris Lattner69772b02006-07-02 20:34:39 +00001082 // Handle this like a #include file being popped off the stack.
1083 CurMacroExpander = 0;
1084 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001085}
1086
1087
1088//===----------------------------------------------------------------------===//
1089// Utility Methods for Preprocessor Directive Handling.
1090//===----------------------------------------------------------------------===//
1091
1092/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1093/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001094void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001095 LexerToken Tmp;
1096 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001097 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001098 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001099}
1100
1101/// ReadMacroName - Lex and validate a macro name, which occurs after a
1102/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001103/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1104/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001105/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001106void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001107 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001108 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001109
1110 // Missing macro name?
1111 if (MacroNameTok.getKind() == tok::eom)
1112 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1113
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001114 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1115 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001116 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001117 // Fall through on error.
1118 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001119 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001120
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001121 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1122 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001123 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001124 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001125 } else if (isDefineUndef && II->getMacroInfo() &&
1126 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001127 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001128 if (isDefineUndef == 1)
1129 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1130 else
1131 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001132 } else {
1133 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001134 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 }
1136
Chris Lattner22eb9722006-06-18 05:43:12 +00001137 // Invalid macro name, read and discard the rest of the line. Then set the
1138 // token kind to tok::eom.
1139 MacroNameTok.SetKind(tok::eom);
1140 return DiscardUntilEndOfDirective();
1141}
1142
1143/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1144/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001145void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001146 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001147 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001148 // There should be no tokens after the directive, but we allow them as an
1149 // extension.
1150 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001151 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1152 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001153 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001154}
1155
1156
1157
1158/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1159/// decided that the subsequent tokens are in the #if'd out portion of the
1160/// file. Lex the rest of the file, until we see an #endif. If
1161/// FoundNonSkipPortion is true, then we have already emitted code for part of
1162/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1163/// is true, then #else directives are ok, if not, then we have already seen one
1164/// so a #else directive is a duplicate. When this returns, the caller can lex
1165/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001166void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001167 bool FoundNonSkipPortion,
1168 bool FoundElse) {
1169 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001170 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001171 "Lexing a macro, not a file?");
1172
1173 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1174 FoundNonSkipPortion, FoundElse);
1175
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001176 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1177 // disabling warnings, etc.
1178 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001179 LexerToken Tok;
1180 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001181 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001182
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001183 // If this is the end of the buffer, we have an error.
1184 if (Tok.getKind() == tok::eof) {
1185 // Emit errors for each unterminated conditional on the stack, including
1186 // the current one.
1187 while (!CurLexer->ConditionalStack.empty()) {
1188 Diag(CurLexer->ConditionalStack.back().IfLoc,
1189 diag::err_pp_unterminated_conditional);
1190 CurLexer->ConditionalStack.pop_back();
1191 }
1192
1193 // Just return and let the caller lex after this #include.
1194 break;
1195 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001196
1197 // If this token is not a preprocessor directive, just skip it.
1198 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1199 continue;
1200
1201 // We just parsed a # character at the start of a line, so we're in
1202 // directive mode. Tell the lexer this so any newlines we see will be
1203 // converted into an EOM token (this terminates the macro).
1204 CurLexer->ParsingPreprocessorDirective = true;
1205
1206 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001207 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001208
1209 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1210 // something bogus), skip it.
1211 if (Tok.getKind() != tok::identifier) {
1212 CurLexer->ParsingPreprocessorDirective = false;
1213 continue;
1214 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001215
Chris Lattner22eb9722006-06-18 05:43:12 +00001216 // If the first letter isn't i or e, it isn't intesting to us. We know that
1217 // this is safe in the face of spelling differences, because there is no way
1218 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001219 // allows us to avoid looking up the identifier info for #define/#undef and
1220 // other common directives.
1221 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1222 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001223 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1224 FirstChar != 'i' && FirstChar != 'e') {
1225 CurLexer->ParsingPreprocessorDirective = false;
1226 continue;
1227 }
1228
Chris Lattnere60165f2006-06-22 06:36:29 +00001229 // Get the identifier name without trigraphs or embedded newlines. Note
1230 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1231 // when skipping.
1232 // TODO: could do this with zero copies in the no-clean case by using
1233 // strncmp below.
1234 char Directive[20];
1235 unsigned IdLen;
1236 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1237 IdLen = Tok.getLength();
1238 memcpy(Directive, RawCharData, IdLen);
1239 Directive[IdLen] = 0;
1240 } else {
1241 std::string DirectiveStr = getSpelling(Tok);
1242 IdLen = DirectiveStr.size();
1243 if (IdLen >= 20) {
1244 CurLexer->ParsingPreprocessorDirective = false;
1245 continue;
1246 }
1247 memcpy(Directive, &DirectiveStr[0], IdLen);
1248 Directive[IdLen] = 0;
1249 }
1250
Chris Lattner22eb9722006-06-18 05:43:12 +00001251 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001252 if ((IdLen == 2) || // "if"
1253 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1254 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001255 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1256 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001257 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001258 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001259 /*foundnonskip*/false,
1260 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001261 }
1262 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001263 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001264 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001265 PPConditionalInfo CondInfo;
1266 CondInfo.WasSkipping = true; // Silence bogus warning.
1267 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1268 assert(!InCond && "Can't be skipping if not in a conditional!");
1269
1270 // If we popped the outermost skipping block, we're done skipping!
1271 if (!CondInfo.WasSkipping)
1272 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001273 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001274 // #else directive in a skipping conditional. If not in some other
1275 // skipping conditional, and if #else hasn't already been seen, enter it
1276 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001277 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001278 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1279
1280 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001281 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001282
1283 // Note that we've seen a #else in this conditional.
1284 CondInfo.FoundElse = true;
1285
1286 // If the conditional is at the top level, and the #if block wasn't
1287 // entered, enter the #else block now.
1288 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1289 CondInfo.FoundNonSkip = true;
1290 break;
1291 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001292 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001293 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1294
1295 bool ShouldEnter;
1296 // If this is in a skipping block or if we're already handled this #if
1297 // block, don't bother parsing the condition.
1298 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001299 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001300 ShouldEnter = false;
1301 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001302 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001303 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001304 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1305 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001306 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001307 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001308 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001309 }
1310
1311 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001312 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001313
1314 // If this condition is true, enter it!
1315 if (ShouldEnter) {
1316 CondInfo.FoundNonSkip = true;
1317 break;
1318 }
1319 }
1320 }
1321
1322 CurLexer->ParsingPreprocessorDirective = false;
1323 }
1324
1325 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1326 // of the file, just stop skipping and return to lexing whatever came after
1327 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001328 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001329}
1330
1331//===----------------------------------------------------------------------===//
1332// Preprocessor Directive Handling.
1333//===----------------------------------------------------------------------===//
1334
1335/// HandleDirective - This callback is invoked when the lexer sees a # token
1336/// at the start of a line. This consumes the directive, modifies the
1337/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1338/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001339void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001340 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001341
1342 // We just parsed a # character at the start of a line, so we're in directive
1343 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001344 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 CurLexer->ParsingPreprocessorDirective = true;
1346
1347 ++NumDirectives;
1348
Chris Lattner371ac8a2006-07-04 07:11:10 +00001349 // We are about to read a token. For the multiple-include optimization FA to
1350 // work, we have to remember if we had read any tokens *before* this
1351 // pp-directive.
1352 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1353
Chris Lattner78186052006-07-09 00:45:31 +00001354 // Read the next token, the directive flavor. This isn't expanded due to
1355 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001356 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001357
Chris Lattner78186052006-07-09 00:45:31 +00001358 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1359 // #define A(x) #x
1360 // A(abc
1361 // #warning blah
1362 // def)
1363 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001364 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001365 Diag(Result, diag::ext_embedded_directive);
1366
Chris Lattner22eb9722006-06-18 05:43:12 +00001367 switch (Result.getKind()) {
1368 default: break;
1369 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001370 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001371
1372#if 0
1373 case tok::numeric_constant:
1374 // FIXME: implement # 7 line numbers!
1375 break;
1376#endif
1377 case tok::kw_else:
1378 return HandleElseDirective(Result);
1379 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001380 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001381 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001382 // Get the identifier name without trigraphs or embedded newlines.
1383 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001384 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001385 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001386 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001387 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001388 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001389 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001390 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001391 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1392 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001393 break;
1394 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001395 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001396 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001397 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001398 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001399 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001400 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001401 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001402 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001403 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001404 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001405 break;
1406 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001407 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001408 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001409 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001410 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001411 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001412 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001413 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001414 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001415 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1416 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001417 break;
1418 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001419 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1420 return HandleIncludeDirective(Result); // Handle #include.
1421 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001422 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001423 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001424 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 break;
1426 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001427 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001428 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001429 }
1430 break;
1431 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001432 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1433 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001434 break;
1435 }
1436 break;
1437 }
1438
1439 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001440 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001441
1442 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001443 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001444
1445 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001446}
1447
Chris Lattner01d66cc2006-07-03 22:16:27 +00001448void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001449 bool isWarning) {
1450 // Read the rest of the line raw. We do this because we don't want macros
1451 // to be expanded and we don't require that the tokens be valid preprocessing
1452 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1453 // collapse multiple consequtive white space between tokens, but this isn't
1454 // specified by the standard.
1455 std::string Message = CurLexer->ReadToEndOfLine();
1456
1457 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001458 return Diag(Tok, DiagID, Message);
1459}
1460
1461/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1462///
1463void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001464 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001465 Diag(Tok, diag::ext_pp_ident_directive);
1466
Chris Lattner371ac8a2006-07-04 07:11:10 +00001467 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001468 LexerToken StrTok;
1469 Lex(StrTok);
1470
1471 // If the token kind isn't a string, it's a malformed directive.
1472 if (StrTok.getKind() != tok::string_literal)
1473 return Diag(StrTok, diag::err_pp_malformed_ident);
1474
1475 // Verify that there is nothing after the string, other than EOM.
1476 CheckEndOfDirective("#ident");
1477
1478 if (IdentHandler)
1479 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001480}
1481
Chris Lattnerb8761832006-06-24 21:31:03 +00001482//===----------------------------------------------------------------------===//
1483// Preprocessor Include Directive Handling.
1484//===----------------------------------------------------------------------===//
1485
Chris Lattner22eb9722006-06-18 05:43:12 +00001486/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1487/// file to be included from the lexer, then include it! This is a common
1488/// routine with functionality shared between #include, #include_next and
1489/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001490void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001491 const DirectoryLookup *LookupFrom,
1492 bool isImport) {
1493 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001494
Chris Lattner22eb9722006-06-18 05:43:12 +00001495 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001496 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001497
1498 // If the token kind is EOM, the error has already been diagnosed.
1499 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001500 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001501
1502 // Verify that there is nothing after the filename, other than EOM. Use the
1503 // preprocessor to lex this in case lexing the filename entered a macro.
1504 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001505
1506 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001507 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001508 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1509
Chris Lattner269c2322006-06-25 06:23:00 +00001510 // Find out whether the filename is <x> or "x".
1511 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001512
1513 // Remove the quotes.
1514 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1515
Chris Lattner22eb9722006-06-18 05:43:12 +00001516 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001517 const DirectoryLookup *CurDir;
1518 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001519 if (File == 0)
1520 return Diag(FilenameTok, diag::err_pp_file_not_found);
1521
1522 // Get information about this file.
1523 PerFileInfo &FileInfo = getFileInfo(File);
1524
1525 // If this is a #import directive, check that we have not already imported
1526 // this header.
1527 if (isImport) {
1528 // If this has already been imported, don't import it again.
1529 FileInfo.isImport = true;
1530
1531 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001532 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001533 } else {
1534 // Otherwise, if this is a #include of a file that was previously #import'd
1535 // or if this is the second #include of a #pragma once file, ignore it.
1536 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001537 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001538 }
Chris Lattner3665f162006-07-04 07:26:10 +00001539
1540 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1541 // if the macro that guards it is defined, we know the #include has no effect.
1542 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1543 ++NumMultiIncludeFileOptzn;
1544 return;
1545 }
1546
Chris Lattner22eb9722006-06-18 05:43:12 +00001547
1548 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001549 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001550 if (FileID == 0)
1551 return Diag(FilenameTok, diag::err_pp_file_not_found);
1552
1553 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001554 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001555
1556 // Increment the number of times this file has been included.
1557 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001558}
1559
1560/// HandleIncludeNextDirective - Implements #include_next.
1561///
Chris Lattnercb283342006-06-18 06:48:37 +00001562void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1563 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001564
1565 // #include_next is like #include, except that we start searching after
1566 // the current found directory. If we can't do this, issue a
1567 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001568 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001569 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001571 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001572 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001573 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001574 } else {
1575 // Start looking up in the next directory.
1576 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001577 }
1578
1579 return HandleIncludeDirective(IncludeNextTok, Lookup);
1580}
1581
1582/// HandleImportDirective - Implements #import.
1583///
Chris Lattnercb283342006-06-18 06:48:37 +00001584void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1585 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001586
1587 return HandleIncludeDirective(ImportTok, 0, true);
1588}
1589
Chris Lattnerb8761832006-06-24 21:31:03 +00001590//===----------------------------------------------------------------------===//
1591// Preprocessor Macro Directive Handling.
1592//===----------------------------------------------------------------------===//
1593
Chris Lattnercefc7682006-07-08 08:28:12 +00001594/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1595/// definition has just been read. Lex the rest of the arguments and the
1596/// closing ), updating MI with what we learn. Return true if an error occurs
1597/// parsing the arg list.
1598bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1599 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001600 while (1) {
1601 LexUnexpandedToken(Tok);
1602 switch (Tok.getKind()) {
1603 case tok::r_paren:
1604 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001605 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001606 // Otherwise we have #define FOO(A,)
1607 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1608 return true;
1609 case tok::ellipsis: // #define X(... -> C99 varargs
1610 // Warn if use of C99 feature in non-C99 mode.
1611 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1612
1613 // Lex the token after the identifier.
1614 LexUnexpandedToken(Tok);
1615 if (Tok.getKind() != tok::r_paren) {
1616 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1617 return true;
1618 }
1619 MI->setIsC99Varargs();
1620 return false;
1621 case tok::eom: // #define X(
1622 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1623 return true;
1624 default: // #define X(1
1625 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1626 return true;
1627 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001628 IdentifierInfo *II = Tok.getIdentifierInfo();
1629
1630 // If this is already used as an argument, it is used multiple times (e.g.
1631 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001632 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001633 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1634 return true;
1635 }
1636
1637 // Add the argument to the macro info.
1638 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001639
1640 // Lex the token after the identifier.
1641 LexUnexpandedToken(Tok);
1642
1643 switch (Tok.getKind()) {
1644 default: // #define X(A B
1645 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1646 return true;
1647 case tok::r_paren: // #define X(A)
1648 return false;
1649 case tok::comma: // #define X(A,
1650 break;
1651 case tok::ellipsis: // #define X(A... -> GCC extension
1652 // Diagnose extension.
1653 Diag(Tok, diag::ext_named_variadic_macro);
1654
1655 // Lex the token after the identifier.
1656 LexUnexpandedToken(Tok);
1657 if (Tok.getKind() != tok::r_paren) {
1658 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1659 return true;
1660 }
1661
1662 MI->setIsGNUVarargs();
1663 return false;
1664 }
1665 }
1666 }
1667}
1668
Chris Lattner22eb9722006-06-18 05:43:12 +00001669/// HandleDefineDirective - Implements #define. This consumes the entire macro
1670/// line then lets the caller lex the next real token.
1671///
Chris Lattnercb283342006-06-18 06:48:37 +00001672void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001673 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001674
Chris Lattner22eb9722006-06-18 05:43:12 +00001675 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001676 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001677
1678 // Error reading macro name? If so, diagnostic already issued.
1679 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001680 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001681
Chris Lattner50b497e2006-06-18 16:32:35 +00001682 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001683
1684 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001685 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001686
Chris Lattner78186052006-07-09 00:45:31 +00001687 // FIXME: Enable __VA_ARGS__.
1688
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001689 // If this is a function-like macro definition, parse the argument list,
1690 // marking each of the identifiers as being used as macro arguments. Also,
1691 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001692 if (Tok.getKind() == tok::eom) {
1693 // If there is no body to this macro, we have no special handling here.
1694 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001695 // This is a function-like macro definition. Read the argument list.
1696 MI->setIsFunctionLike();
1697 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001698 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001699 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001700 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001701 if (CurLexer->ParsingPreprocessorDirective)
1702 DiscardUntilEndOfDirective();
1703 return;
1704 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001705
Chris Lattner815a1f92006-07-08 20:48:04 +00001706 // Read the first token after the arg list for down below.
1707 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001708 } else if (!Tok.hasLeadingSpace()) {
1709 // C99 requires whitespace between the macro definition and the body. Emit
1710 // a diagnostic for something like "#define X+".
1711 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001712 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001713 } else {
1714 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1715 // one in some cases!
1716 }
1717 } else {
1718 // This is a normal token with leading space. Clear the leading space
1719 // marker on the first token to get proper expansion.
1720 Tok.ClearFlag(LexerToken::LeadingSpace);
1721 }
1722
1723 // Read the rest of the macro body.
1724 while (Tok.getKind() != tok::eom) {
1725 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001726
1727 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001728 // parameters in function-like macro expansions.
1729 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001730 // Get the next token of the macro.
1731 LexUnexpandedToken(Tok);
1732 continue;
1733 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001734
Chris Lattner815a1f92006-07-08 20:48:04 +00001735 // Get the next token of the macro.
1736 LexUnexpandedToken(Tok);
1737
1738 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001739 if (!Tok.getIdentifierInfo() ||
1740 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001741 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001742 delete MI;
1743 return;
1744 }
1745
1746 // Things look ok, add the param name token to the macro.
1747 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001748
Chris Lattner22eb9722006-06-18 05:43:12 +00001749 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001750 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001751 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001752
Chris Lattnerbff18d52006-07-06 04:49:18 +00001753 // Check that there is no paste (##) operator at the begining or end of the
1754 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001755 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001756 if (NumTokens != 0) {
1757 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001758 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001759 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001760 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001761 }
1762 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001763 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001764 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001765 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001766 }
1767 }
1768
Chris Lattner13044d92006-07-03 05:16:44 +00001769 // If this is the primary source file, remember that this macro hasn't been
1770 // used yet.
1771 if (isInPrimaryFile())
1772 MI->setIsUsed(false);
1773
Chris Lattner22eb9722006-06-18 05:43:12 +00001774 // Finally, if this identifier already had a macro defined for it, verify that
1775 // the macro bodies are identical and free the old definition.
1776 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001777 if (!OtherMI->isUsed())
1778 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1779
Chris Lattner22eb9722006-06-18 05:43:12 +00001780 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001781 // must be the same. C99 6.10.3.2.
1782 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001783 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1784 MacroNameTok.getIdentifierInfo()->getName());
1785 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1786 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001787 delete OtherMI;
1788 }
1789
1790 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001791}
1792
1793
1794/// HandleUndefDirective - Implements #undef.
1795///
Chris Lattnercb283342006-06-18 06:48:37 +00001796void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001797 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001798
Chris Lattner22eb9722006-06-18 05:43:12 +00001799 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001800 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001801
1802 // Error reading macro name? If so, diagnostic already issued.
1803 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001804 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001805
1806 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001807 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001808
1809 // Okay, we finally have a valid identifier to undef.
1810 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1811
1812 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001813 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001814
Chris Lattner13044d92006-07-03 05:16:44 +00001815 if (!MI->isUsed())
1816 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001817
1818 // Free macro definition.
1819 delete MI;
1820 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001821}
1822
1823
Chris Lattnerb8761832006-06-24 21:31:03 +00001824//===----------------------------------------------------------------------===//
1825// Preprocessor Conditional Directive Handling.
1826//===----------------------------------------------------------------------===//
1827
Chris Lattner22eb9722006-06-18 05:43:12 +00001828/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001829/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1830/// if any tokens have been returned or pp-directives activated before this
1831/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001832///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001833void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1834 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001835 ++NumIf;
1836 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001837
Chris Lattner22eb9722006-06-18 05:43:12 +00001838 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001839 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001840
1841 // Error reading macro name? If so, diagnostic already issued.
1842 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001843 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001844
1845 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001846 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1847
1848 // If the start of a top-level #ifdef, inform MIOpt.
1849 if (!ReadAnyTokensBeforeDirective &&
1850 CurLexer->getConditionalStackDepth() == 0) {
1851 assert(isIfndef && "#ifdef shouldn't reach here");
1852 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1853 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001854
Chris Lattnera78a97e2006-07-03 05:42:18 +00001855 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1856
1857 // If there is a macro, mark it used.
1858 if (MI) MI->setIsUsed(true);
1859
Chris Lattner22eb9722006-06-18 05:43:12 +00001860 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001861 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001862 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001863 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001864 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001865 } else {
1866 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001867 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001868 /*Foundnonskip*/false,
1869 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001870 }
1871}
1872
1873/// HandleIfDirective - Implements the #if directive.
1874///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001875void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1876 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001877 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001878
Chris Lattner371ac8a2006-07-04 07:11:10 +00001879 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001880 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001881 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001882
1883 // Should we include the stuff contained by this directive?
1884 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001885 // If this condition is equivalent to #ifndef X, and if this is the first
1886 // directive seen, handle it for the multiple-include optimization.
1887 if (!ReadAnyTokensBeforeDirective &&
1888 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1889 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1890
Chris Lattner22eb9722006-06-18 05:43:12 +00001891 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001892 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001893 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001894 } else {
1895 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001896 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001897 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001898 }
1899}
1900
1901/// HandleEndifDirective - Implements the #endif directive.
1902///
Chris Lattnercb283342006-06-18 06:48:37 +00001903void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001904 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001905
Chris Lattner22eb9722006-06-18 05:43:12 +00001906 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001907 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001908
1909 PPConditionalInfo CondInfo;
1910 if (CurLexer->popConditionalLevel(CondInfo)) {
1911 // No conditionals on the stack: this is an #endif without an #if.
1912 return Diag(EndifToken, diag::err_pp_endif_without_if);
1913 }
1914
Chris Lattner371ac8a2006-07-04 07:11:10 +00001915 // If this the end of a top-level #endif, inform MIOpt.
1916 if (CurLexer->getConditionalStackDepth() == 0)
1917 CurLexer->MIOpt.ExitTopLevelConditional();
1918
Chris Lattner22eb9722006-06-18 05:43:12 +00001919 assert(!CondInfo.WasSkipping && !isSkipping() &&
1920 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001921}
1922
1923
Chris Lattnercb283342006-06-18 06:48:37 +00001924void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001925 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001926
Chris Lattner22eb9722006-06-18 05:43:12 +00001927 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001928 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001929
1930 PPConditionalInfo CI;
1931 if (CurLexer->popConditionalLevel(CI))
1932 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001933
1934 // If this is a top-level #else, inform the MIOpt.
1935 if (CurLexer->getConditionalStackDepth() == 0)
1936 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001937
1938 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001939 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001940
1941 // Finally, skip the rest of the contents of this block and return the first
1942 // token after it.
1943 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1944 /*FoundElse*/true);
1945}
1946
Chris Lattnercb283342006-06-18 06:48:37 +00001947void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001948 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001949
Chris Lattner22eb9722006-06-18 05:43:12 +00001950 // #elif directive in a non-skipping conditional... start skipping.
1951 // We don't care what the condition is, because we will always skip it (since
1952 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001953 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001954
1955 PPConditionalInfo CI;
1956 if (CurLexer->popConditionalLevel(CI))
1957 return Diag(ElifToken, diag::pp_err_elif_without_if);
1958
Chris Lattner371ac8a2006-07-04 07:11:10 +00001959 // If this is a top-level #elif, inform the MIOpt.
1960 if (CurLexer->getConditionalStackDepth() == 0)
1961 CurLexer->MIOpt.FoundTopLevelElse();
1962
Chris Lattner22eb9722006-06-18 05:43:12 +00001963 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001964 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001965
1966 // Finally, skip the rest of the contents of this block and return the first
1967 // token after it.
1968 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1969 /*FoundElse*/CI.FoundElse);
1970}
Chris Lattnerb8761832006-06-24 21:31:03 +00001971