blob: 1a6a620dd562dc46f2c84dd06ab667c678abdc4f [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) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000974 assert(Identifier.getIdentifierInfo() &&
975 "Can't handle identifiers without identifier info!");
976
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000977 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000978
979 // If this identifier was poisoned, and if it was not produced from a macro
980 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000981 if (II.isPoisoned() && CurLexer) {
982 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
983 Diag(Identifier, diag::err_pp_used_poisoned_id);
984 else
985 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
986 }
Chris Lattner677757a2006-06-28 05:26:32 +0000987
Chris Lattner78186052006-07-09 00:45:31 +0000988 // If this is a macro to be expanded, do it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000989 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +0000990 if (MI->isEnabled() && !DisableMacroExpansion)
Chris Lattner78186052006-07-09 00:45:31 +0000991 if (!HandleMacroExpandedIdentifier(Identifier, MI))
992 return;
Chris Lattner677757a2006-06-28 05:26:32 +0000993
994 // Change the kind of this identifier to the appropriate token kind, e.g.
995 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000996 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000997
998 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000999 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001000}
1001
Chris Lattner22eb9722006-06-18 05:43:12 +00001002/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1003/// the current file. This either returns the EOF token or pops a level off
1004/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001005bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001006 assert(!CurMacroExpander &&
1007 "Ending a file when currently in a macro!");
1008
Chris Lattner371ac8a2006-07-04 07:11:10 +00001009 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001010 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001011 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001012 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001013 // Okay, this has a controlling macro, remember in PerFileInfo.
1014 if (const FileEntry *FE =
1015 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1016 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001017 }
1018 }
1019
Chris Lattner22eb9722006-06-18 05:43:12 +00001020 // If this is a #include'd file, pop it off the include stack and continue
1021 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001022 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001023 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001024 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001025
1026 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001027 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001028 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1029
1030 // Get the file entry for the current file.
1031 if (const FileEntry *FE =
1032 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1033 FileType = getFileInfo(FE).DirInfo;
1034
Chris Lattner0c885f52006-06-21 06:50:18 +00001035 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001036 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001037 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001038
1039 // Client should lex another token.
1040 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001041 }
1042
Chris Lattnerd01e2912006-06-18 16:22:51 +00001043 Result.StartToken();
1044 CurLexer->BufferPtr = CurLexer->BufferEnd;
1045 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001046 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001047
1048 // We're done with the #included file.
1049 delete CurLexer;
1050 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001051
Chris Lattner03f83482006-07-10 06:16:26 +00001052 // This is the end of the top-level file. If the diag::pp_macro_not_used
1053 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1054 // have not been used.
1055 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1056 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001057
1058 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001059}
1060
1061/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001062/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001063bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001064 assert(CurMacroExpander && !CurLexer &&
1065 "Ending a macro when currently in a #include file!");
1066
Chris Lattner22eb9722006-06-18 05:43:12 +00001067 delete CurMacroExpander;
1068
Chris Lattner69772b02006-07-02 20:34:39 +00001069 // Handle this like a #include file being popped off the stack.
1070 CurMacroExpander = 0;
1071 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001072}
1073
1074
1075//===----------------------------------------------------------------------===//
1076// Utility Methods for Preprocessor Directive Handling.
1077//===----------------------------------------------------------------------===//
1078
1079/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1080/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001081void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001082 LexerToken Tmp;
1083 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001084 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001085 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001086}
1087
1088/// ReadMacroName - Lex and validate a macro name, which occurs after a
1089/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001090/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1091/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001092/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001093void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001094 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001095 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001096
1097 // Missing macro name?
1098 if (MacroNameTok.getKind() == tok::eom)
1099 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1100
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001101 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1102 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001103 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001104 // Fall through on error.
1105 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001106 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001107
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001108 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1109 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001110 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001111 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001112 } else if (isDefineUndef && II->getMacroInfo() &&
1113 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001114 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001115 if (isDefineUndef == 1)
1116 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1117 else
1118 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001119 } else {
1120 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001121 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001122 }
1123
Chris Lattner22eb9722006-06-18 05:43:12 +00001124 // Invalid macro name, read and discard the rest of the line. Then set the
1125 // token kind to tok::eom.
1126 MacroNameTok.SetKind(tok::eom);
1127 return DiscardUntilEndOfDirective();
1128}
1129
1130/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1131/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001132void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001133 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001134 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 // There should be no tokens after the directive, but we allow them as an
1136 // extension.
1137 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001138 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1139 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001140 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001141}
1142
1143
1144
1145/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1146/// decided that the subsequent tokens are in the #if'd out portion of the
1147/// file. Lex the rest of the file, until we see an #endif. If
1148/// FoundNonSkipPortion is true, then we have already emitted code for part of
1149/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1150/// is true, then #else directives are ok, if not, then we have already seen one
1151/// so a #else directive is a duplicate. When this returns, the caller can lex
1152/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001153void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001154 bool FoundNonSkipPortion,
1155 bool FoundElse) {
1156 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001157 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001158 "Lexing a macro, not a file?");
1159
1160 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1161 FoundNonSkipPortion, FoundElse);
1162
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001163 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1164 // disabling warnings, etc.
1165 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001166 LexerToken Tok;
1167 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001168 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001169
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001170 // If this is the end of the buffer, we have an error.
1171 if (Tok.getKind() == tok::eof) {
1172 // Emit errors for each unterminated conditional on the stack, including
1173 // the current one.
1174 while (!CurLexer->ConditionalStack.empty()) {
1175 Diag(CurLexer->ConditionalStack.back().IfLoc,
1176 diag::err_pp_unterminated_conditional);
1177 CurLexer->ConditionalStack.pop_back();
1178 }
1179
1180 // Just return and let the caller lex after this #include.
1181 break;
1182 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001183
1184 // If this token is not a preprocessor directive, just skip it.
1185 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1186 continue;
1187
1188 // We just parsed a # character at the start of a line, so we're in
1189 // directive mode. Tell the lexer this so any newlines we see will be
1190 // converted into an EOM token (this terminates the macro).
1191 CurLexer->ParsingPreprocessorDirective = true;
1192
1193 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001194 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001195
1196 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1197 // something bogus), skip it.
1198 if (Tok.getKind() != tok::identifier) {
1199 CurLexer->ParsingPreprocessorDirective = false;
1200 continue;
1201 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001202
Chris Lattner22eb9722006-06-18 05:43:12 +00001203 // If the first letter isn't i or e, it isn't intesting to us. We know that
1204 // this is safe in the face of spelling differences, because there is no way
1205 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001206 // allows us to avoid looking up the identifier info for #define/#undef and
1207 // other common directives.
1208 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1209 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001210 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1211 FirstChar != 'i' && FirstChar != 'e') {
1212 CurLexer->ParsingPreprocessorDirective = false;
1213 continue;
1214 }
1215
Chris Lattnere60165f2006-06-22 06:36:29 +00001216 // Get the identifier name without trigraphs or embedded newlines. Note
1217 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1218 // when skipping.
1219 // TODO: could do this with zero copies in the no-clean case by using
1220 // strncmp below.
1221 char Directive[20];
1222 unsigned IdLen;
1223 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1224 IdLen = Tok.getLength();
1225 memcpy(Directive, RawCharData, IdLen);
1226 Directive[IdLen] = 0;
1227 } else {
1228 std::string DirectiveStr = getSpelling(Tok);
1229 IdLen = DirectiveStr.size();
1230 if (IdLen >= 20) {
1231 CurLexer->ParsingPreprocessorDirective = false;
1232 continue;
1233 }
1234 memcpy(Directive, &DirectiveStr[0], IdLen);
1235 Directive[IdLen] = 0;
1236 }
1237
Chris Lattner22eb9722006-06-18 05:43:12 +00001238 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001239 if ((IdLen == 2) || // "if"
1240 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1241 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001242 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1243 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001244 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001245 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001246 /*foundnonskip*/false,
1247 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001248 }
1249 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001250 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001251 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001252 PPConditionalInfo CondInfo;
1253 CondInfo.WasSkipping = true; // Silence bogus warning.
1254 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1255 assert(!InCond && "Can't be skipping if not in a conditional!");
1256
1257 // If we popped the outermost skipping block, we're done skipping!
1258 if (!CondInfo.WasSkipping)
1259 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001260 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001261 // #else directive in a skipping conditional. If not in some other
1262 // skipping conditional, and if #else hasn't already been seen, enter it
1263 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001264 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001265 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1266
1267 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001268 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001269
1270 // Note that we've seen a #else in this conditional.
1271 CondInfo.FoundElse = true;
1272
1273 // If the conditional is at the top level, and the #if block wasn't
1274 // entered, enter the #else block now.
1275 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1276 CondInfo.FoundNonSkip = true;
1277 break;
1278 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001279 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001280 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1281
1282 bool ShouldEnter;
1283 // If this is in a skipping block or if we're already handled this #if
1284 // block, don't bother parsing the condition.
1285 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001286 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001287 ShouldEnter = false;
1288 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001289 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001290 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001291 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1292 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001293 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001294 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001295 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 }
1297
1298 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001299 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001300
1301 // If this condition is true, enter it!
1302 if (ShouldEnter) {
1303 CondInfo.FoundNonSkip = true;
1304 break;
1305 }
1306 }
1307 }
1308
1309 CurLexer->ParsingPreprocessorDirective = false;
1310 }
1311
1312 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1313 // of the file, just stop skipping and return to lexing whatever came after
1314 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001315 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001316}
1317
1318//===----------------------------------------------------------------------===//
1319// Preprocessor Directive Handling.
1320//===----------------------------------------------------------------------===//
1321
1322/// HandleDirective - This callback is invoked when the lexer sees a # token
1323/// at the start of a line. This consumes the directive, modifies the
1324/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1325/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001326void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001327 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001328
1329 // We just parsed a # character at the start of a line, so we're in directive
1330 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001331 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001332 CurLexer->ParsingPreprocessorDirective = true;
1333
1334 ++NumDirectives;
1335
Chris Lattner371ac8a2006-07-04 07:11:10 +00001336 // We are about to read a token. For the multiple-include optimization FA to
1337 // work, we have to remember if we had read any tokens *before* this
1338 // pp-directive.
1339 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1340
Chris Lattner78186052006-07-09 00:45:31 +00001341 // Read the next token, the directive flavor. This isn't expanded due to
1342 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001343 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001344
Chris Lattner78186052006-07-09 00:45:31 +00001345 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1346 // #define A(x) #x
1347 // A(abc
1348 // #warning blah
1349 // def)
1350 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001351 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001352 Diag(Result, diag::ext_embedded_directive);
1353
Chris Lattner22eb9722006-06-18 05:43:12 +00001354 switch (Result.getKind()) {
1355 default: break;
1356 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001357 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001358
1359#if 0
1360 case tok::numeric_constant:
1361 // FIXME: implement # 7 line numbers!
1362 break;
1363#endif
1364 case tok::kw_else:
1365 return HandleElseDirective(Result);
1366 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001367 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001368 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001369 // Get the identifier name without trigraphs or embedded newlines.
1370 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001371 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001372 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001373 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001374 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001375 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001376 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001377 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001378 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1379 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 break;
1381 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001382 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001383 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001384 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001385 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001386 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001387 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001388 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001389 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001390 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001391 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001392 break;
1393 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001394 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001395 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001396 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001397 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001398 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001399 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001400 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001401 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001402 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1403 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001404 break;
1405 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001406 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1407 return HandleIncludeDirective(Result); // Handle #include.
1408 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001409 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001410 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001411 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001412 break;
1413 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001414 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001415 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001416 }
1417 break;
1418 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001419 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1420 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001421 break;
1422 }
1423 break;
1424 }
1425
1426 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001427 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001428
1429 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001430 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001431
1432 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001433}
1434
Chris Lattner01d66cc2006-07-03 22:16:27 +00001435void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001436 bool isWarning) {
1437 // Read the rest of the line raw. We do this because we don't want macros
1438 // to be expanded and we don't require that the tokens be valid preprocessing
1439 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1440 // collapse multiple consequtive white space between tokens, but this isn't
1441 // specified by the standard.
1442 std::string Message = CurLexer->ReadToEndOfLine();
1443
1444 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001445 return Diag(Tok, DiagID, Message);
1446}
1447
1448/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1449///
1450void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001451 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001452 Diag(Tok, diag::ext_pp_ident_directive);
1453
Chris Lattner371ac8a2006-07-04 07:11:10 +00001454 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001455 LexerToken StrTok;
1456 Lex(StrTok);
1457
1458 // If the token kind isn't a string, it's a malformed directive.
1459 if (StrTok.getKind() != tok::string_literal)
1460 return Diag(StrTok, diag::err_pp_malformed_ident);
1461
1462 // Verify that there is nothing after the string, other than EOM.
1463 CheckEndOfDirective("#ident");
1464
1465 if (IdentHandler)
1466 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001467}
1468
Chris Lattnerb8761832006-06-24 21:31:03 +00001469//===----------------------------------------------------------------------===//
1470// Preprocessor Include Directive Handling.
1471//===----------------------------------------------------------------------===//
1472
Chris Lattner22eb9722006-06-18 05:43:12 +00001473/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1474/// file to be included from the lexer, then include it! This is a common
1475/// routine with functionality shared between #include, #include_next and
1476/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001477void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001478 const DirectoryLookup *LookupFrom,
1479 bool isImport) {
1480 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001481
Chris Lattner22eb9722006-06-18 05:43:12 +00001482 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001483 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001484
1485 // If the token kind is EOM, the error has already been diagnosed.
1486 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001487 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001488
1489 // Verify that there is nothing after the filename, other than EOM. Use the
1490 // preprocessor to lex this in case lexing the filename entered a macro.
1491 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001492
1493 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001494 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001495 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1496
Chris Lattner269c2322006-06-25 06:23:00 +00001497 // Find out whether the filename is <x> or "x".
1498 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001499
1500 // Remove the quotes.
1501 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1502
Chris Lattner22eb9722006-06-18 05:43:12 +00001503 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001504 const DirectoryLookup *CurDir;
1505 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001506 if (File == 0)
1507 return Diag(FilenameTok, diag::err_pp_file_not_found);
1508
1509 // Get information about this file.
1510 PerFileInfo &FileInfo = getFileInfo(File);
1511
1512 // If this is a #import directive, check that we have not already imported
1513 // this header.
1514 if (isImport) {
1515 // If this has already been imported, don't import it again.
1516 FileInfo.isImport = true;
1517
1518 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001519 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001520 } else {
1521 // Otherwise, if this is a #include of a file that was previously #import'd
1522 // or if this is the second #include of a #pragma once file, ignore it.
1523 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001524 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001525 }
Chris Lattner3665f162006-07-04 07:26:10 +00001526
1527 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1528 // if the macro that guards it is defined, we know the #include has no effect.
1529 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1530 ++NumMultiIncludeFileOptzn;
1531 return;
1532 }
1533
Chris Lattner22eb9722006-06-18 05:43:12 +00001534
1535 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001536 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001537 if (FileID == 0)
1538 return Diag(FilenameTok, diag::err_pp_file_not_found);
1539
1540 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001541 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001542
1543 // Increment the number of times this file has been included.
1544 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001545}
1546
1547/// HandleIncludeNextDirective - Implements #include_next.
1548///
Chris Lattnercb283342006-06-18 06:48:37 +00001549void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1550 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001551
1552 // #include_next is like #include, except that we start searching after
1553 // the current found directory. If we can't do this, issue a
1554 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001555 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001556 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001557 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001558 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001559 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001560 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001561 } else {
1562 // Start looking up in the next directory.
1563 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001564 }
1565
1566 return HandleIncludeDirective(IncludeNextTok, Lookup);
1567}
1568
1569/// HandleImportDirective - Implements #import.
1570///
Chris Lattnercb283342006-06-18 06:48:37 +00001571void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1572 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001573
1574 return HandleIncludeDirective(ImportTok, 0, true);
1575}
1576
Chris Lattnerb8761832006-06-24 21:31:03 +00001577//===----------------------------------------------------------------------===//
1578// Preprocessor Macro Directive Handling.
1579//===----------------------------------------------------------------------===//
1580
Chris Lattnercefc7682006-07-08 08:28:12 +00001581/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1582/// definition has just been read. Lex the rest of the arguments and the
1583/// closing ), updating MI with what we learn. Return true if an error occurs
1584/// parsing the arg list.
1585bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1586 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001587 while (1) {
1588 LexUnexpandedToken(Tok);
1589 switch (Tok.getKind()) {
1590 case tok::r_paren:
1591 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001592 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001593 // Otherwise we have #define FOO(A,)
1594 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1595 return true;
1596 case tok::ellipsis: // #define X(... -> C99 varargs
1597 // Warn if use of C99 feature in non-C99 mode.
1598 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1599
1600 // Lex the token after the identifier.
1601 LexUnexpandedToken(Tok);
1602 if (Tok.getKind() != tok::r_paren) {
1603 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1604 return true;
1605 }
1606 MI->setIsC99Varargs();
1607 return false;
1608 case tok::eom: // #define X(
1609 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1610 return true;
1611 default: // #define X(1
1612 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1613 return true;
1614 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001615 IdentifierInfo *II = Tok.getIdentifierInfo();
1616
1617 // If this is already used as an argument, it is used multiple times (e.g.
1618 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001619 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001620 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1621 return true;
1622 }
1623
1624 // Add the argument to the macro info.
1625 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001626
1627 // Lex the token after the identifier.
1628 LexUnexpandedToken(Tok);
1629
1630 switch (Tok.getKind()) {
1631 default: // #define X(A B
1632 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1633 return true;
1634 case tok::r_paren: // #define X(A)
1635 return false;
1636 case tok::comma: // #define X(A,
1637 break;
1638 case tok::ellipsis: // #define X(A... -> GCC extension
1639 // Diagnose extension.
1640 Diag(Tok, diag::ext_named_variadic_macro);
1641
1642 // Lex the token after the identifier.
1643 LexUnexpandedToken(Tok);
1644 if (Tok.getKind() != tok::r_paren) {
1645 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1646 return true;
1647 }
1648
1649 MI->setIsGNUVarargs();
1650 return false;
1651 }
1652 }
1653 }
1654}
1655
Chris Lattner22eb9722006-06-18 05:43:12 +00001656/// HandleDefineDirective - Implements #define. This consumes the entire macro
1657/// line then lets the caller lex the next real token.
1658///
Chris Lattnercb283342006-06-18 06:48:37 +00001659void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001660 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001661
Chris Lattner22eb9722006-06-18 05:43:12 +00001662 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001663 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001664
1665 // Error reading macro name? If so, diagnostic already issued.
1666 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001667 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001668
Chris Lattner50b497e2006-06-18 16:32:35 +00001669 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001670
1671 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001672 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001673
Chris Lattner78186052006-07-09 00:45:31 +00001674 // FIXME: Enable __VA_ARGS__.
1675
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001676 // If this is a function-like macro definition, parse the argument list,
1677 // marking each of the identifiers as being used as macro arguments. Also,
1678 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001679 if (Tok.getKind() == tok::eom) {
1680 // If there is no body to this macro, we have no special handling here.
1681 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001682 // This is a function-like macro definition. Read the argument list.
1683 MI->setIsFunctionLike();
1684 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001685 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001686 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001687 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001688 if (CurLexer->ParsingPreprocessorDirective)
1689 DiscardUntilEndOfDirective();
1690 return;
1691 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001692
Chris Lattner815a1f92006-07-08 20:48:04 +00001693 // Read the first token after the arg list for down below.
1694 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001695 } else if (!Tok.hasLeadingSpace()) {
1696 // C99 requires whitespace between the macro definition and the body. Emit
1697 // a diagnostic for something like "#define X+".
1698 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001699 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001700 } else {
1701 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1702 // one in some cases!
1703 }
1704 } else {
1705 // This is a normal token with leading space. Clear the leading space
1706 // marker on the first token to get proper expansion.
1707 Tok.ClearFlag(LexerToken::LeadingSpace);
1708 }
1709
1710 // Read the rest of the macro body.
1711 while (Tok.getKind() != tok::eom) {
1712 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001713
1714 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001715 // parameters in function-like macro expansions.
1716 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001717 // Get the next token of the macro.
1718 LexUnexpandedToken(Tok);
1719 continue;
1720 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001721
Chris Lattner815a1f92006-07-08 20:48:04 +00001722 // Get the next token of the macro.
1723 LexUnexpandedToken(Tok);
1724
1725 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001726 if (!Tok.getIdentifierInfo() ||
1727 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001728 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001729 delete MI;
1730 return;
1731 }
1732
1733 // Things look ok, add the param name token to the macro.
1734 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001735
Chris Lattner22eb9722006-06-18 05:43:12 +00001736 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001737 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001738 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001739
Chris Lattnerbff18d52006-07-06 04:49:18 +00001740 // Check that there is no paste (##) operator at the begining or end of the
1741 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001742 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001743 if (NumTokens != 0) {
1744 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001745 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001746 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001747 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001748 }
1749 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001750 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001751 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001752 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001753 }
1754 }
1755
Chris Lattner13044d92006-07-03 05:16:44 +00001756 // If this is the primary source file, remember that this macro hasn't been
1757 // used yet.
1758 if (isInPrimaryFile())
1759 MI->setIsUsed(false);
1760
Chris Lattner22eb9722006-06-18 05:43:12 +00001761 // Finally, if this identifier already had a macro defined for it, verify that
1762 // the macro bodies are identical and free the old definition.
1763 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001764 if (!OtherMI->isUsed())
1765 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1766
Chris Lattner22eb9722006-06-18 05:43:12 +00001767 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001768 // must be the same. C99 6.10.3.2.
1769 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001770 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1771 MacroNameTok.getIdentifierInfo()->getName());
1772 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1773 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001774 delete OtherMI;
1775 }
1776
1777 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001778}
1779
1780
1781/// HandleUndefDirective - Implements #undef.
1782///
Chris Lattnercb283342006-06-18 06:48:37 +00001783void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001784 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001785
Chris Lattner22eb9722006-06-18 05:43:12 +00001786 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001787 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001788
1789 // Error reading macro name? If so, diagnostic already issued.
1790 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001791 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001792
1793 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001794 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001795
1796 // Okay, we finally have a valid identifier to undef.
1797 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1798
1799 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001800 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001801
Chris Lattner13044d92006-07-03 05:16:44 +00001802 if (!MI->isUsed())
1803 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001804
1805 // Free macro definition.
1806 delete MI;
1807 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001808}
1809
1810
Chris Lattnerb8761832006-06-24 21:31:03 +00001811//===----------------------------------------------------------------------===//
1812// Preprocessor Conditional Directive Handling.
1813//===----------------------------------------------------------------------===//
1814
Chris Lattner22eb9722006-06-18 05:43:12 +00001815/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001816/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1817/// if any tokens have been returned or pp-directives activated before this
1818/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001819///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001820void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1821 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001822 ++NumIf;
1823 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001824
Chris Lattner22eb9722006-06-18 05:43:12 +00001825 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001826 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001827
1828 // Error reading macro name? If so, diagnostic already issued.
1829 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001830 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001831
1832 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001833 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1834
1835 // If the start of a top-level #ifdef, inform MIOpt.
1836 if (!ReadAnyTokensBeforeDirective &&
1837 CurLexer->getConditionalStackDepth() == 0) {
1838 assert(isIfndef && "#ifdef shouldn't reach here");
1839 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1840 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001841
Chris Lattnera78a97e2006-07-03 05:42:18 +00001842 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1843
1844 // If there is a macro, mark it used.
1845 if (MI) MI->setIsUsed(true);
1846
Chris Lattner22eb9722006-06-18 05:43:12 +00001847 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001848 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001849 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001850 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001851 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001852 } else {
1853 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001854 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001855 /*Foundnonskip*/false,
1856 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001857 }
1858}
1859
1860/// HandleIfDirective - Implements the #if directive.
1861///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001862void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1863 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001864 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001865
Chris Lattner371ac8a2006-07-04 07:11:10 +00001866 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001867 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001868 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001869
1870 // Should we include the stuff contained by this directive?
1871 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001872 // If this condition is equivalent to #ifndef X, and if this is the first
1873 // directive seen, handle it for the multiple-include optimization.
1874 if (!ReadAnyTokensBeforeDirective &&
1875 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1876 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1877
Chris Lattner22eb9722006-06-18 05:43:12 +00001878 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001879 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001880 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001881 } else {
1882 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001883 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001884 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001885 }
1886}
1887
1888/// HandleEndifDirective - Implements the #endif directive.
1889///
Chris Lattnercb283342006-06-18 06:48:37 +00001890void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001891 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001892
Chris Lattner22eb9722006-06-18 05:43:12 +00001893 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001894 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001895
1896 PPConditionalInfo CondInfo;
1897 if (CurLexer->popConditionalLevel(CondInfo)) {
1898 // No conditionals on the stack: this is an #endif without an #if.
1899 return Diag(EndifToken, diag::err_pp_endif_without_if);
1900 }
1901
Chris Lattner371ac8a2006-07-04 07:11:10 +00001902 // If this the end of a top-level #endif, inform MIOpt.
1903 if (CurLexer->getConditionalStackDepth() == 0)
1904 CurLexer->MIOpt.ExitTopLevelConditional();
1905
Chris Lattner22eb9722006-06-18 05:43:12 +00001906 assert(!CondInfo.WasSkipping && !isSkipping() &&
1907 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001908}
1909
1910
Chris Lattnercb283342006-06-18 06:48:37 +00001911void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001912 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001913
Chris Lattner22eb9722006-06-18 05:43:12 +00001914 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001915 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001916
1917 PPConditionalInfo CI;
1918 if (CurLexer->popConditionalLevel(CI))
1919 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001920
1921 // If this is a top-level #else, inform the MIOpt.
1922 if (CurLexer->getConditionalStackDepth() == 0)
1923 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001924
1925 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001926 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001927
1928 // Finally, skip the rest of the contents of this block and return the first
1929 // token after it.
1930 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1931 /*FoundElse*/true);
1932}
1933
Chris Lattnercb283342006-06-18 06:48:37 +00001934void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001935 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001936
Chris Lattner22eb9722006-06-18 05:43:12 +00001937 // #elif directive in a non-skipping conditional... start skipping.
1938 // We don't care what the condition is, because we will always skip it (since
1939 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001940 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001941
1942 PPConditionalInfo CI;
1943 if (CurLexer->popConditionalLevel(CI))
1944 return Diag(ElifToken, diag::pp_err_elif_without_if);
1945
Chris Lattner371ac8a2006-07-04 07:11:10 +00001946 // If this is a top-level #elif, inform the MIOpt.
1947 if (CurLexer->getConditionalStackDepth() == 0)
1948 CurLexer->MIOpt.FoundTopLevelElse();
1949
Chris Lattner22eb9722006-06-18 05:43:12 +00001950 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001951 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001952
1953 // Finally, skip the rest of the contents of this block and return the first
1954 // token after it.
1955 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1956 /*FoundElse*/CI.FoundElse);
1957}
Chris Lattnerb8761832006-06-24 21:31:03 +00001958