blob: da8b9d15114c09d6dee76cf97b58de56839a6ddc [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 Lattner78186052006-07-09 00:45:31 +000060 InMacroFormalArgs = 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
279//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000280// Source File Location Methods.
281//===----------------------------------------------------------------------===//
282
283
284/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
285/// return null on failure. isAngled indicates whether the file reference is
286/// for system #include's or not (i.e. using <> instead of "").
287const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000288 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000289 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000290 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000291 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000292 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000293
294 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000295 // FIXME: Portability. This should be a sys::Path interface, this doesn't
296 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000297 if (Filename[0] == '/') {
298 // If this was an #include_next "/absolute/file", fail.
299 if (FromDir) return 0;
300
301 // Otherwise, just return the file.
302 return FileMgr.getFile(Filename);
303 }
304
305 // Step #0, unless disabled, check to see if the file is in the #includer's
306 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000307 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000308 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
309 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000310 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000311 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000312 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000313 if (const FileEntry *FE =
314 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000315 if (CurDirLookup)
316 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000317 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000318 CurDir = 0;
319
320 // This file is a system header or C++ unfriendly if the old file is.
321 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000322 return FE;
323 }
324 }
325 }
326
327 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000328 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000329
330 // If this is a #include_next request, start searching after the directory the
331 // file was found in.
332 if (FromDir)
333 i = FromDir-&SearchDirs[0];
334
335 // Check each directory in sequence to see if it contains this file.
336 for (; i != SearchDirs.size(); ++i) {
337 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000338 // FIXME: Portability. Adding file to dir should be in sys::Path.
339 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
340 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000341 CurDir = &SearchDirs[i];
342
343 // This file is a system header or C++ unfriendly if the dir is.
344 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000345 return FE;
346 }
347 }
348
349 // Otherwise, didn't find it.
350 return 0;
351}
352
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000353/// isInPrimaryFile - Return true if we're in the top-level file, not in a
354/// #include.
355bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000356 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000357 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000358
Chris Lattner13044d92006-07-03 05:16:44 +0000359 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000360 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000361 if (IncludeMacroStack[i].TheLexer &&
362 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
363 return IncludeMacroStack[i].TheLexer->isMainFile();
364 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000365}
366
367/// getCurrentLexer - Return the current file lexer being lexed from. Note
368/// that this ignores any potentially active macro expansions and _Pragma
369/// expansions going on at the time.
370Lexer *Preprocessor::getCurrentFileLexer() const {
371 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
372
373 // Look for a stacked lexer.
374 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000375 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000376 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
377 return L;
378 }
379 return 0;
380}
381
382
Chris Lattner22eb9722006-06-18 05:43:12 +0000383/// EnterSourceFile - Add a source file to the top of the include stack and
384/// start lexing tokens from it instead of the current buffer. Return true
385/// on failure.
386void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000387 const DirectoryLookup *CurDir,
388 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000389 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000390 ++NumEnteredSourceFiles;
391
Chris Lattner69772b02006-07-02 20:34:39 +0000392 if (MaxIncludeStackDepth < IncludeMacroStack.size())
393 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000394
Chris Lattner22eb9722006-06-18 05:43:12 +0000395 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000396 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000397 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000398 EnterSourceFileWithLexer(TheLexer, CurDir);
399}
Chris Lattner22eb9722006-06-18 05:43:12 +0000400
Chris Lattner69772b02006-07-02 20:34:39 +0000401/// EnterSourceFile - Add a source file to the top of the include stack and
402/// start lexing tokens from it instead of the current buffer.
403void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
404 const DirectoryLookup *CurDir) {
405
406 // Add the current lexer to the include stack.
407 if (CurLexer || CurMacroExpander)
408 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
409 CurMacroExpander));
410
411 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000412 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000413 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000414
415 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000416 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000417 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
418
419 // Get the file entry for the current file.
420 if (const FileEntry *FE =
421 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
422 FileType = getFileInfo(FE).DirInfo;
423
Chris Lattner1840e492006-07-02 22:30:01 +0000424 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000425 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000426 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000427}
428
Chris Lattner69772b02006-07-02 20:34:39 +0000429
430
Chris Lattner22eb9722006-06-18 05:43:12 +0000431/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000432/// tokens from it instead of the current buffer.
Chris Lattner78186052006-07-09 00:45:31 +0000433void Preprocessor::EnterMacro(LexerToken &Tok, MacroFormalArgs *Formals) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000434 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000435 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000436 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
437 CurMacroExpander));
438 CurLexer = 0;
439 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000440
Chris Lattner22eb9722006-06-18 05:43:12 +0000441 // Mark the macro as currently disabled, so that it is not recursively
442 // expanded.
443 MI.DisableMacro();
Chris Lattner78186052006-07-09 00:45:31 +0000444 CurMacroExpander = new MacroExpander(Tok, Formals, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000445}
446
Chris Lattner22eb9722006-06-18 05:43:12 +0000447//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000448// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000449//===----------------------------------------------------------------------===//
450
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000451/// RegisterBuiltinMacro - Register the specified identifier in the identifier
452/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000453IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000454 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000455 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000456
457 // Mark it as being a macro that is builtin.
458 MacroInfo *MI = new MacroInfo(SourceLocation());
459 MI->setIsBuiltinMacro();
460 Id->setMacroInfo(MI);
461 return Id;
462}
463
464
Chris Lattner677757a2006-06-28 05:26:32 +0000465/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
466/// identifier table.
467void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000468 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000469 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000470 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
471 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000472 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000473
474 // GCC Extensions.
475 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
476 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000477 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000478}
479
Chris Lattnerc2395832006-07-09 00:57:04 +0000480/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
481/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000482static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
483 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000484 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
485
486 // If the token isn't an identifier, it's always literally expanded.
487 if (II == 0) return true;
488
489 // If the identifier is a macro, and if that macro is enabled, it may be
490 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000491 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
492 // Fast expanding "#define X X" is ok, because X would be disabled.
493 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000494 return false;
495
496 // If this is an object-like macro invocation, it is safe to trivially expand
497 // it.
498 if (MI->isObjectLike()) return true;
499
500 // If this is a function-like macro invocation, it's safe to trivially expand
501 // as long as the identifier is not a macro argument.
502 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
503 I != E; ++I)
504 if (*I == II)
505 return false; // Identifier is a macro argument.
506 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000507}
508
509/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
510/// the specified lexer will return a tok::l_paren token, 0 if it is something
511/// else and 2 if there are no more tokens in the buffer controlled by the
512/// lexer.
513unsigned Preprocessor::isNextPPTokenLParen(Lexer *L) {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +0000514 assert(!L->LexingRawMode &&
515 "How can we expand a macro from a skipping buffer?");
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000516
517 // Set the lexer to 'skipping' mode. This will ensure that we can lex a token
518 // without emitting diagnostics, disables macro expansion, and will cause EOF
519 // to return an EOF token instead of popping the include stack.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +0000520 L->LexingRawMode = true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000521
522 // Save state that can be changed while lexing so that we can restore it.
523 const char *BufferPtr = L->BufferPtr;
524
525 LexerToken Tok;
526 Tok.StartToken();
527 L->LexTokenInternal(Tok);
528
529 // Restore state that may have changed.
530 L->BufferPtr = BufferPtr;
531
532 // Restore the lexer back to non-skipping mode.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +0000533 L->LexingRawMode = false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000534
535 if (Tok.getKind() == tok::eof)
536 return 2;
537 return Tok.getKind() == tok::l_paren;
538}
539
Chris Lattnerc2395832006-07-09 00:57:04 +0000540
Chris Lattnerafe603f2006-07-11 04:02:46 +0000541/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
542/// lexed is a '('. If so, consume the token and return true, if not, this
543/// method should have no observable side-effect on the lexed tokens.
544bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000545 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000546 unsigned Val;
547 if (CurLexer)
548 Val = isNextPPTokenLParen(CurLexer);
549 else
550 Val = CurMacroExpander->isNextTokenLParen();
551
552 if (Val == 2) {
553 // If we ran off the end of the lexer or macro expander, walk the include
554 // stack, looking for whatever will return the next token.
555 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
556 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
557 if (Entry.TheLexer)
558 Val = isNextPPTokenLParen(Entry.TheLexer);
559 else
560 Val = Entry.TheMacroExpander->isNextTokenLParen();
561 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000562 }
563
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000564 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
565 // have found something that isn't a '(' or we found the end of the
566 // translation unit. In either case, return false.
567 if (Val != 1)
568 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000569
570 LexerToken Tok;
571 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000572 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
573 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000574}
Chris Lattner677757a2006-06-28 05:26:32 +0000575
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000576/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
577/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000578bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000579 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000580
581 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
582 if (MI->isBuiltinMacro()) {
583 ExpandBuiltinMacro(Identifier);
584 return false;
585 }
586
587 /// FormalArgs - If this is a function-like macro expansion, this contains,
588 /// for each macro argument, the list of tokens that were provided to the
589 /// invocation.
590 MacroFormalArgs *FormalArgs = 0;
591
592 // If this is a function-like macro, read the arguments.
593 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000594 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
595 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000596 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000597 return true;
598
Chris Lattner78186052006-07-09 00:45:31 +0000599 // Remember that we are now parsing the arguments to a macro invocation.
600 // Preprocessor directives used inside macro arguments are not portable, and
601 // this enables the warning.
602 InMacroFormalArgs = true;
603 FormalArgs = ReadFunctionLikeMacroFormalArgs(Identifier, MI);
604
605 // Finished parsing args.
606 InMacroFormalArgs = false;
607
608 // If there was an error parsing the arguments, bail out.
609 if (FormalArgs == 0) return false;
610
611 ++NumFnMacroExpanded;
612 } else {
613 ++NumMacroExpanded;
614 }
Chris Lattner13044d92006-07-03 05:16:44 +0000615
616 // Notice that this macro has been used.
617 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000618
619 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000620
621 // If this macro expands to no tokens, don't bother to push it onto the
622 // expansion stack, only to take it right back off.
623 if (MI->getNumTokens() == 0) {
Chris Lattner78186052006-07-09 00:45:31 +0000624 // No need for formal arg info.
625 delete FormalArgs;
626
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000627 // Ignore this macro use, just return the next token in the current
628 // buffer.
629 bool HadLeadingSpace = Identifier.hasLeadingSpace();
630 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
631
632 Lex(Identifier);
633
634 // If the identifier isn't on some OTHER line, inherit the leading
635 // whitespace/first-on-a-line property of this token. This handles
636 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
637 // empty.
638 if (!Identifier.isAtStartOfLine()) {
639 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
640 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
641 }
642 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000643 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000644
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000645 } else if (MI->getNumTokens() == 1 &&
646 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000647 // Otherwise, if this macro expands into a single trivially-expanded
648 // token: expand it now. This handles common cases like
649 // "#define VAL 42".
650
651 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
652 // identifier to the expanded token.
653 bool isAtStartOfLine = Identifier.isAtStartOfLine();
654 bool hasLeadingSpace = Identifier.hasLeadingSpace();
655
656 // Remember where the token is instantiated.
657 SourceLocation InstantiateLoc = Identifier.getLocation();
658
659 // Replace the result token.
660 Identifier = MI->getReplacementToken(0);
661
662 // Restore the StartOfLine/LeadingSpace markers.
663 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
664 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
665
666 // Update the tokens location to include both its logical and physical
667 // locations.
668 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000669 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000670 Identifier.SetLocation(Loc);
671
672 // Since this is not an identifier token, it can't be macro expanded, so
673 // we're done.
674 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000675 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000676 }
677
Chris Lattner78186052006-07-09 00:45:31 +0000678 // Start expanding the macro.
679 EnterMacro(Identifier, FormalArgs);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000680
681 // Now that the macro is at the top of the include stack, ask the
682 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000683 Lex(Identifier);
684 return false;
685}
686
687/// ReadFunctionLikeMacroFormalArgs - After reading "MACRO(", this method is
688/// invoked to read all of the formal arguments specified for the macro
689/// invocation. This returns null on error.
690MacroFormalArgs *Preprocessor::
691ReadFunctionLikeMacroFormalArgs(LexerToken &MacroName, MacroInfo *MI) {
692 // Use an auto_ptr here so that the MacroFormalArgs object is deleted on
693 // all error paths.
694 std::auto_ptr<MacroFormalArgs> Args(new MacroFormalArgs(MI));
695
696 // The number of fixed arguments to parse.
697 unsigned NumFixedArgsLeft = MI->getNumArgs();
698 bool isVariadic = MI->isVariadic();
699
700 // If this is a C99-style varargs macro invocation, add an extra expected
701 // argument, which will catch all of the varargs formals in one argument.
702 if (MI->isC99Varargs())
703 ++NumFixedArgsLeft;
704
705 // Outer loop, while there are more arguments, keep reading them.
706 LexerToken Tok;
707 Tok.SetKind(tok::comma);
708 --NumFixedArgsLeft; // Start reading the first arg.
709
710 while (Tok.getKind() == tok::comma) {
711 // ArgTokens - Build up a list of tokens that make up this argument.
712 std::vector<LexerToken> ArgTokens;
713 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
714 unsigned NumParens = 0;
715
716 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000717 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
718 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000719 LexUnexpandedToken(Tok);
720
721 if (Tok.getKind() == tok::eof) {
722 Diag(MacroName, diag::err_unterm_macro_invoc);
723 // Do not lose the EOF. Return it to the client.
724 MacroName = Tok;
725 return 0;
726 } else if (Tok.getKind() == tok::r_paren) {
727 // If we found the ) token, the macro arg list is done.
728 if (NumParens-- == 0)
729 break;
730 } else if (Tok.getKind() == tok::l_paren) {
731 ++NumParens;
732 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
733 // Comma ends this argument if there are more fixed arguments expected.
734 if (NumFixedArgsLeft)
735 break;
736
737 // If this is not a variadic macro, too many formals were specified.
738 if (!isVariadic) {
739 // Emit the diagnostic at the macro name in case there is a missing ).
740 // Emitting it at the , could be far away from the macro name.
741 Diag(MacroName, diag::err_too_many_formals_in_macro_invoc);
742 return 0;
743 }
744 // Otherwise, continue to add the tokens to this variable argument.
745 }
746
747 ArgTokens.push_back(Tok);
748 }
749
Chris Lattnera12dd152006-07-11 04:09:02 +0000750 // Empty arguments are standard in C99 and supported as an extension in
751 // other modes.
752 if (ArgTokens.empty() && !Features.C99)
753 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000754
Chris Lattner78186052006-07-09 00:45:31 +0000755 // Remember the tokens that make up this argument. This destroys ArgTokens.
756 Args->addArgument(ArgTokens);
757 --NumFixedArgsLeft;
758 };
759
760 // Okay, we either found the r_paren. Check to see if we parsed too few
761 // arguments.
762 unsigned NumFormals = Args->getNumArguments();
763 unsigned MinArgsExpected = MI->getNumArgs();
764
765 // C99 expects us to pass at least one vararg arg (but as an extension, we
Chris Lattnerc2395832006-07-09 00:57:04 +0000766 // don't require this). GNU-style varargs already include the 'rest' name in
767 // the count.
768 MinArgsExpected += MI->isC99Varargs();
Chris Lattner78186052006-07-09 00:45:31 +0000769
770 if (NumFormals < MinArgsExpected) {
771 // There are several cases where too few arguments is ok, handle them now.
772 if (NumFormals+1 == MinArgsExpected && MI->isVariadic()) {
773 // Varargs where the named vararg parameter is missing: ok as extension.
774 // #define A(x, ...)
775 // A("blah")
776 Diag(Tok, diag::ext_missing_varargs_arg);
777 } else if (MI->getNumArgs() == 1) {
778 // #define A(x)
779 // A()
Chris Lattnerafe603f2006-07-11 04:02:46 +0000780 // is ok because it is an empty argument. Add it explicitly.
Chris Lattner78186052006-07-09 00:45:31 +0000781 std::vector<LexerToken> ArgTokens;
782 Args->addArgument(ArgTokens);
Chris Lattnera12dd152006-07-11 04:09:02 +0000783
784 // Empty arguments are standard in C99 and supported as an extension in
785 // other modes.
786 if (ArgTokens.empty() && !Features.C99)
787 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000788 } else {
789 // Otherwise, emit the error.
790 Diag(Tok, diag::err_too_few_formals_in_macro_invoc);
791 return 0;
792 }
793 }
794
795 return Args.release();
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000796}
797
Chris Lattnerc673f902006-06-30 06:10:41 +0000798/// ComputeDATE_TIME - Compute the current time, enter it into the specified
799/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
800/// the identifier tokens inserted.
801static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
802 ScratchBuffer *ScratchBuf) {
803 time_t TT = time(0);
804 struct tm *TM = localtime(&TT);
805
806 static const char * const Months[] = {
807 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
808 };
809
810 char TmpBuffer[100];
811 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
812 TM->tm_year+1900);
813 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
814
815 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
816 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
817}
818
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000819/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
820/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000821void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000822 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000823 IdentifierInfo *II = Tok.getIdentifierInfo();
824 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000825
826 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
827 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000828 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000829 return Handle_Pragma(Tok);
830
Chris Lattner78186052006-07-09 00:45:31 +0000831 ++NumBuiltinMacroExpanded;
832
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000833 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000834
835 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000836 Tok.SetIdentifierInfo(0);
837 Tok.ClearFlag(LexerToken::NeedsCleaning);
838
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000839 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000840 // __LINE__ expands to a simple numeric value.
841 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
842 unsigned Length = strlen(TmpBuffer);
843 Tok.SetKind(tok::numeric_constant);
844 Tok.SetLength(Length);
845 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000846 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000847 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000848 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000849 Diag(Tok, diag::ext_pp_base_file);
850 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
851 while (NextLoc.getFileID() != 0) {
852 Loc = NextLoc;
853 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
854 }
855 }
856
Chris Lattner0766e592006-07-03 01:07:01 +0000857 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
858 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000859 FN = Lexer::Stringify(FN);
Chris Lattner630b33c2006-07-01 22:46:53 +0000860 Tok.SetKind(tok::string_literal);
861 Tok.SetLength(FN.size());
862 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000863 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000864 if (!DATELoc.isValid())
865 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
866 Tok.SetKind(tok::string_literal);
867 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
868 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000869 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000870 if (!TIMELoc.isValid())
871 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
872 Tok.SetKind(tok::string_literal);
873 Tok.SetLength(strlen("\"hh:mm:ss\""));
874 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000875 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000876 Diag(Tok, diag::ext_pp_include_level);
877
878 // Compute the include depth of this token.
879 unsigned Depth = 0;
880 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
881 for (; Loc.getFileID() != 0; ++Depth)
882 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
883
884 // __INCLUDE_LEVEL__ expands to a simple numeric value.
885 sprintf(TmpBuffer, "%u", Depth);
886 unsigned Length = strlen(TmpBuffer);
887 Tok.SetKind(tok::numeric_constant);
888 Tok.SetLength(Length);
889 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000890 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000891 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
892 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
893 Diag(Tok, diag::ext_pp_timestamp);
894
895 // Get the file that we are lexing out of. If we're currently lexing from
896 // a macro, dig into the include stack.
897 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000898 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000899
900 if (TheLexer)
901 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
902
903 // If this file is older than the file it depends on, emit a diagnostic.
904 const char *Result;
905 if (CurFile) {
906 time_t TT = CurFile->getModificationTime();
907 struct tm *TM = localtime(&TT);
908 Result = asctime(TM);
909 } else {
910 Result = "??? ??? ?? ??:??:?? ????\n";
911 }
912 TmpBuffer[0] = '"';
913 strcpy(TmpBuffer+1, Result);
914 unsigned Len = strlen(TmpBuffer);
915 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
916 Tok.SetKind(tok::string_literal);
917 Tok.SetLength(Len);
918 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000919 } else {
920 assert(0 && "Unknown identifier!");
921 }
922}
Chris Lattner677757a2006-06-28 05:26:32 +0000923
Chris Lattner13044d92006-07-03 05:16:44 +0000924namespace {
925struct UnusedIdentifierReporter : public IdentifierVisitor {
926 Preprocessor &PP;
927 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
928
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000929 void VisitIdentifier(IdentifierInfo &II) const {
930 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
931 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000932 }
933};
934}
935
Chris Lattner677757a2006-06-28 05:26:32 +0000936//===----------------------------------------------------------------------===//
937// Lexer Event Handling.
938//===----------------------------------------------------------------------===//
939
Chris Lattnercefc7682006-07-08 08:28:12 +0000940/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
941/// identifier information for the token and install it into the token.
942IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
943 const char *BufPtr) {
944 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
945 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
946
947 // Look up this token, see if it is a macro, or if it is a language keyword.
948 IdentifierInfo *II;
949 if (BufPtr && !Identifier.needsCleaning()) {
950 // No cleaning needed, just use the characters from the lexed buffer.
951 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
952 } else {
953 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
954 const char *TmpBuf = (char*)alloca(Identifier.getLength());
955 unsigned Size = getSpelling(Identifier, TmpBuf);
956 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
957 }
958 Identifier.SetIdentifierInfo(II);
959 return II;
960}
961
962
Chris Lattner677757a2006-06-28 05:26:32 +0000963/// HandleIdentifier - This callback is invoked when the lexer reads an
964/// identifier. This callback looks up the identifier in the map and/or
965/// potentially macro expands it or turns it into a named token (like 'for').
966void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
967 if (Identifier.getIdentifierInfo() == 0) {
968 // If we are skipping tokens (because we are in a #if 0 block), there will
969 // be no identifier info, just return the token.
970 assert(isSkipping() && "Token isn't an identifier?");
971 return;
972 }
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000973 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000974
975 // If this identifier was poisoned, and if it was not produced from a macro
976 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000977 if (II.isPoisoned() && CurLexer) {
978 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
979 Diag(Identifier, diag::err_pp_used_poisoned_id);
980 else
981 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
982 }
Chris Lattner677757a2006-06-28 05:26:32 +0000983
Chris Lattner78186052006-07-09 00:45:31 +0000984 // If this is a macro to be expanded, do it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000985 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +0000986 if (MI->isEnabled() && !DisableMacroExpansion)
Chris Lattner78186052006-07-09 00:45:31 +0000987 if (!HandleMacroExpandedIdentifier(Identifier, MI))
988 return;
Chris Lattner677757a2006-06-28 05:26:32 +0000989
990 // Change the kind of this identifier to the appropriate token kind, e.g.
991 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000992 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000993
994 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000995 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000996}
997
Chris Lattner22eb9722006-06-18 05:43:12 +0000998/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
999/// the current file. This either returns the EOF token or pops a level off
1000/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +00001001void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001002 assert(!CurMacroExpander &&
1003 "Ending a file when currently in a macro!");
1004
1005 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
1006 // this is an error condition. Just return the EOF token up to
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001007 // SkipExcludedConditionalBlock. The code that enabled skipping will issue
1008 // errors for the unterminated #if's on the conditional stack if it is
1009 // interested.
Chris Lattner22eb9722006-06-18 05:43:12 +00001010 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +00001011 Result.StartToken();
1012 CurLexer->BufferPtr = CurLexer->BufferEnd;
1013 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001014 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +00001015 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001016 }
1017
Chris Lattner371ac8a2006-07-04 07:11:10 +00001018 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001019 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001020 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001021 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001022 // Okay, this has a controlling macro, remember in PerFileInfo.
1023 if (const FileEntry *FE =
1024 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1025 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001026 }
1027 }
1028
Chris Lattner22eb9722006-06-18 05:43:12 +00001029 // If this is a #include'd file, pop it off the include stack and continue
1030 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001031 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001032 // We're done with the #included file.
1033 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +00001034 CurLexer = IncludeMacroStack.back().TheLexer;
1035 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
1036 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
1037 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +00001038
1039 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001040 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001041 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1042
1043 // Get the file entry for the current file.
1044 if (const FileEntry *FE =
1045 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1046 FileType = getFileInfo(FE).DirInfo;
1047
Chris Lattner0c885f52006-06-21 06:50:18 +00001048 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001049 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001050 }
Chris Lattner0c885f52006-06-21 06:50:18 +00001051
Chris Lattner22eb9722006-06-18 05:43:12 +00001052 return Lex(Result);
1053 }
1054
Chris Lattnerd01e2912006-06-18 16:22:51 +00001055 Result.StartToken();
1056 CurLexer->BufferPtr = CurLexer->BufferEnd;
1057 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001058 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001059
1060 // We're done with the #included file.
1061 delete CurLexer;
1062 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001063
Chris Lattner03f83482006-07-10 06:16:26 +00001064 // This is the end of the top-level file. If the diag::pp_macro_not_used
1065 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1066 // have not been used.
1067 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1068 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +00001069}
1070
1071/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnerafe603f2006-07-11 04:02:46 +00001072/// the current macro expansion.
Chris Lattnercb283342006-06-18 06:48:37 +00001073void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001074 assert(CurMacroExpander && !CurLexer &&
1075 "Ending a macro when currently in a #include file!");
1076
1077 // Mark macro not ignored now that it is no longer being expanded.
1078 CurMacroExpander->getMacro().EnableMacro();
1079 delete CurMacroExpander;
1080
Chris Lattner69772b02006-07-02 20:34:39 +00001081 // Handle this like a #include file being popped off the stack.
1082 CurMacroExpander = 0;
1083 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001084}
1085
1086
1087//===----------------------------------------------------------------------===//
1088// Utility Methods for Preprocessor Directive Handling.
1089//===----------------------------------------------------------------------===//
1090
1091/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1092/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001093void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001094 LexerToken Tmp;
1095 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001096 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001098}
1099
1100/// ReadMacroName - Lex and validate a macro name, which occurs after a
1101/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001102/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1103/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001104/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001105void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001106 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001107 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001108
1109 // Missing macro name?
1110 if (MacroNameTok.getKind() == tok::eom)
1111 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1112
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001113 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1114 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001115 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001116 // Fall through on error.
1117 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001118 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001119
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001120 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1121 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001122 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001123 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001124 } else if (isDefineUndef && II->getMacroInfo() &&
1125 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001126 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001127 if (isDefineUndef == 1)
1128 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1129 else
1130 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001131 } else {
1132 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001133 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001134 }
1135
Chris Lattner22eb9722006-06-18 05:43:12 +00001136 // Invalid macro name, read and discard the rest of the line. Then set the
1137 // token kind to tok::eom.
1138 MacroNameTok.SetKind(tok::eom);
1139 return DiscardUntilEndOfDirective();
1140}
1141
1142/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1143/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001144void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001145 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001146 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001147 // There should be no tokens after the directive, but we allow them as an
1148 // extension.
1149 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001150 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1151 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001153}
1154
1155
1156
1157/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1158/// decided that the subsequent tokens are in the #if'd out portion of the
1159/// file. Lex the rest of the file, until we see an #endif. If
1160/// FoundNonSkipPortion is true, then we have already emitted code for part of
1161/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1162/// is true, then #else directives are ok, if not, then we have already seen one
1163/// so a #else directive is a duplicate. When this returns, the caller can lex
1164/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001165void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001166 bool FoundNonSkipPortion,
1167 bool FoundElse) {
1168 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001169 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001170 "Lexing a macro, not a file?");
1171
1172 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1173 FoundNonSkipPortion, FoundElse);
1174
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001175 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1176 // disabling warnings, etc.
1177 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001178 LexerToken Tok;
1179 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001180 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001181
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001182 // If this is the end of the buffer, we have an error.
1183 if (Tok.getKind() == tok::eof) {
1184 // Emit errors for each unterminated conditional on the stack, including
1185 // the current one.
1186 while (!CurLexer->ConditionalStack.empty()) {
1187 Diag(CurLexer->ConditionalStack.back().IfLoc,
1188 diag::err_pp_unterminated_conditional);
1189 CurLexer->ConditionalStack.pop_back();
1190 }
1191
1192 // Just return and let the caller lex after this #include.
1193 break;
1194 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001195
1196 // If this token is not a preprocessor directive, just skip it.
1197 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1198 continue;
1199
1200 // We just parsed a # character at the start of a line, so we're in
1201 // directive mode. Tell the lexer this so any newlines we see will be
1202 // converted into an EOM token (this terminates the macro).
1203 CurLexer->ParsingPreprocessorDirective = true;
1204
1205 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001206 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001207
1208 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1209 // something bogus), skip it.
1210 if (Tok.getKind() != tok::identifier) {
1211 CurLexer->ParsingPreprocessorDirective = false;
1212 continue;
1213 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001214
Chris Lattner22eb9722006-06-18 05:43:12 +00001215 // If the first letter isn't i or e, it isn't intesting to us. We know that
1216 // this is safe in the face of spelling differences, because there is no way
1217 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001218 // allows us to avoid looking up the identifier info for #define/#undef and
1219 // other common directives.
1220 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1221 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001222 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1223 FirstChar != 'i' && FirstChar != 'e') {
1224 CurLexer->ParsingPreprocessorDirective = false;
1225 continue;
1226 }
1227
Chris Lattnere60165f2006-06-22 06:36:29 +00001228 // Get the identifier name without trigraphs or embedded newlines. Note
1229 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1230 // when skipping.
1231 // TODO: could do this with zero copies in the no-clean case by using
1232 // strncmp below.
1233 char Directive[20];
1234 unsigned IdLen;
1235 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1236 IdLen = Tok.getLength();
1237 memcpy(Directive, RawCharData, IdLen);
1238 Directive[IdLen] = 0;
1239 } else {
1240 std::string DirectiveStr = getSpelling(Tok);
1241 IdLen = DirectiveStr.size();
1242 if (IdLen >= 20) {
1243 CurLexer->ParsingPreprocessorDirective = false;
1244 continue;
1245 }
1246 memcpy(Directive, &DirectiveStr[0], IdLen);
1247 Directive[IdLen] = 0;
1248 }
1249
Chris Lattner22eb9722006-06-18 05:43:12 +00001250 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001251 if ((IdLen == 2) || // "if"
1252 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1253 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001254 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1255 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001256 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001257 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001258 /*foundnonskip*/false,
1259 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001260 }
1261 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001262 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001263 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001264 PPConditionalInfo CondInfo;
1265 CondInfo.WasSkipping = true; // Silence bogus warning.
1266 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1267 assert(!InCond && "Can't be skipping if not in a conditional!");
1268
1269 // If we popped the outermost skipping block, we're done skipping!
1270 if (!CondInfo.WasSkipping)
1271 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001272 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001273 // #else directive in a skipping conditional. If not in some other
1274 // skipping conditional, and if #else hasn't already been seen, enter it
1275 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001276 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001277 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1278
1279 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001280 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001281
1282 // Note that we've seen a #else in this conditional.
1283 CondInfo.FoundElse = true;
1284
1285 // If the conditional is at the top level, and the #if block wasn't
1286 // entered, enter the #else block now.
1287 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1288 CondInfo.FoundNonSkip = true;
1289 break;
1290 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001291 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001292 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1293
1294 bool ShouldEnter;
1295 // If this is in a skipping block or if we're already handled this #if
1296 // block, don't bother parsing the condition.
1297 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001298 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001299 ShouldEnter = false;
1300 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001301 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001302 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001303 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1304 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001305 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001306 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001307 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001308 }
1309
1310 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001311 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001312
1313 // If this condition is true, enter it!
1314 if (ShouldEnter) {
1315 CondInfo.FoundNonSkip = true;
1316 break;
1317 }
1318 }
1319 }
1320
1321 CurLexer->ParsingPreprocessorDirective = false;
1322 }
1323
1324 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1325 // of the file, just stop skipping and return to lexing whatever came after
1326 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001327 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001328}
1329
1330//===----------------------------------------------------------------------===//
1331// Preprocessor Directive Handling.
1332//===----------------------------------------------------------------------===//
1333
1334/// HandleDirective - This callback is invoked when the lexer sees a # token
1335/// at the start of a line. This consumes the directive, modifies the
1336/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1337/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001338void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001339 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001340
1341 // We just parsed a # character at the start of a line, so we're in directive
1342 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001343 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001344 CurLexer->ParsingPreprocessorDirective = true;
1345
1346 ++NumDirectives;
1347
Chris Lattner371ac8a2006-07-04 07:11:10 +00001348 // We are about to read a token. For the multiple-include optimization FA to
1349 // work, we have to remember if we had read any tokens *before* this
1350 // pp-directive.
1351 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1352
Chris Lattner78186052006-07-09 00:45:31 +00001353 // Read the next token, the directive flavor. This isn't expanded due to
1354 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001355 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001356
Chris Lattner78186052006-07-09 00:45:31 +00001357 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1358 // #define A(x) #x
1359 // A(abc
1360 // #warning blah
1361 // def)
1362 // If so, the user is relying on non-portable behavior, emit a diagnostic.
1363 if (InMacroFormalArgs)
1364 Diag(Result, diag::ext_embedded_directive);
1365
Chris Lattner22eb9722006-06-18 05:43:12 +00001366 switch (Result.getKind()) {
1367 default: break;
1368 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001369 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001370
1371#if 0
1372 case tok::numeric_constant:
1373 // FIXME: implement # 7 line numbers!
1374 break;
1375#endif
1376 case tok::kw_else:
1377 return HandleElseDirective(Result);
1378 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001379 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001381 // Get the identifier name without trigraphs or embedded newlines.
1382 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001383 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001384 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001385 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001386 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001387 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001388 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001389 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001390 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1391 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001392 break;
1393 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001394 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001395 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001396 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001397 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001398 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001399 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001400 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001401 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001402 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001403 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001404 break;
1405 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001406 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001407 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001408 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001409 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001410 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001411 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001412 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001413 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001414 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1415 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001416 break;
1417 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001418 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1419 return HandleIncludeDirective(Result); // Handle #include.
1420 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001421 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001422 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001423 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001424 break;
1425 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001426 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001427 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001428 }
1429 break;
1430 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001431 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1432 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001433 break;
1434 }
1435 break;
1436 }
1437
1438 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001439 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001440
1441 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001442 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001443
1444 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001445}
1446
Chris Lattner01d66cc2006-07-03 22:16:27 +00001447void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001448 bool isWarning) {
1449 // Read the rest of the line raw. We do this because we don't want macros
1450 // to be expanded and we don't require that the tokens be valid preprocessing
1451 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1452 // collapse multiple consequtive white space between tokens, but this isn't
1453 // specified by the standard.
1454 std::string Message = CurLexer->ReadToEndOfLine();
1455
1456 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001457 return Diag(Tok, DiagID, Message);
1458}
1459
1460/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1461///
1462void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001463 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001464 Diag(Tok, diag::ext_pp_ident_directive);
1465
Chris Lattner371ac8a2006-07-04 07:11:10 +00001466 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001467 LexerToken StrTok;
1468 Lex(StrTok);
1469
1470 // If the token kind isn't a string, it's a malformed directive.
1471 if (StrTok.getKind() != tok::string_literal)
1472 return Diag(StrTok, diag::err_pp_malformed_ident);
1473
1474 // Verify that there is nothing after the string, other than EOM.
1475 CheckEndOfDirective("#ident");
1476
1477 if (IdentHandler)
1478 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001479}
1480
Chris Lattnerb8761832006-06-24 21:31:03 +00001481//===----------------------------------------------------------------------===//
1482// Preprocessor Include Directive Handling.
1483//===----------------------------------------------------------------------===//
1484
Chris Lattner22eb9722006-06-18 05:43:12 +00001485/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1486/// file to be included from the lexer, then include it! This is a common
1487/// routine with functionality shared between #include, #include_next and
1488/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001489void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001490 const DirectoryLookup *LookupFrom,
1491 bool isImport) {
1492 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001493
Chris Lattner22eb9722006-06-18 05:43:12 +00001494 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001495 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001496
1497 // If the token kind is EOM, the error has already been diagnosed.
1498 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001499 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001500
1501 // Verify that there is nothing after the filename, other than EOM. Use the
1502 // preprocessor to lex this in case lexing the filename entered a macro.
1503 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001504
1505 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001506 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001507 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1508
Chris Lattner269c2322006-06-25 06:23:00 +00001509 // Find out whether the filename is <x> or "x".
1510 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001511
1512 // Remove the quotes.
1513 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1514
Chris Lattner22eb9722006-06-18 05:43:12 +00001515 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001516 const DirectoryLookup *CurDir;
1517 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001518 if (File == 0)
1519 return Diag(FilenameTok, diag::err_pp_file_not_found);
1520
1521 // Get information about this file.
1522 PerFileInfo &FileInfo = getFileInfo(File);
1523
1524 // If this is a #import directive, check that we have not already imported
1525 // this header.
1526 if (isImport) {
1527 // If this has already been imported, don't import it again.
1528 FileInfo.isImport = true;
1529
1530 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001531 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001532 } else {
1533 // Otherwise, if this is a #include of a file that was previously #import'd
1534 // or if this is the second #include of a #pragma once file, ignore it.
1535 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001536 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001537 }
Chris Lattner3665f162006-07-04 07:26:10 +00001538
1539 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1540 // if the macro that guards it is defined, we know the #include has no effect.
1541 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1542 ++NumMultiIncludeFileOptzn;
1543 return;
1544 }
1545
Chris Lattner22eb9722006-06-18 05:43:12 +00001546
1547 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001548 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001549 if (FileID == 0)
1550 return Diag(FilenameTok, diag::err_pp_file_not_found);
1551
1552 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001553 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001554
1555 // Increment the number of times this file has been included.
1556 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001557}
1558
1559/// HandleIncludeNextDirective - Implements #include_next.
1560///
Chris Lattnercb283342006-06-18 06:48:37 +00001561void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1562 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001563
1564 // #include_next is like #include, except that we start searching after
1565 // the current found directory. If we can't do this, issue a
1566 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001567 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001568 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001569 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001570 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001571 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001572 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001573 } else {
1574 // Start looking up in the next directory.
1575 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001576 }
1577
1578 return HandleIncludeDirective(IncludeNextTok, Lookup);
1579}
1580
1581/// HandleImportDirective - Implements #import.
1582///
Chris Lattnercb283342006-06-18 06:48:37 +00001583void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1584 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001585
1586 return HandleIncludeDirective(ImportTok, 0, true);
1587}
1588
Chris Lattnerb8761832006-06-24 21:31:03 +00001589//===----------------------------------------------------------------------===//
1590// Preprocessor Macro Directive Handling.
1591//===----------------------------------------------------------------------===//
1592
Chris Lattnercefc7682006-07-08 08:28:12 +00001593/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1594/// definition has just been read. Lex the rest of the arguments and the
1595/// closing ), updating MI with what we learn. Return true if an error occurs
1596/// parsing the arg list.
1597bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1598 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001599 while (1) {
1600 LexUnexpandedToken(Tok);
1601 switch (Tok.getKind()) {
1602 case tok::r_paren:
1603 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001604 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001605 // Otherwise we have #define FOO(A,)
1606 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1607 return true;
1608 case tok::ellipsis: // #define X(... -> C99 varargs
1609 // Warn if use of C99 feature in non-C99 mode.
1610 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1611
1612 // Lex the token after the identifier.
1613 LexUnexpandedToken(Tok);
1614 if (Tok.getKind() != tok::r_paren) {
1615 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1616 return true;
1617 }
1618 MI->setIsC99Varargs();
1619 return false;
1620 case tok::eom: // #define X(
1621 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1622 return true;
1623 default: // #define X(1
1624 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1625 return true;
1626 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001627 IdentifierInfo *II = Tok.getIdentifierInfo();
1628
1629 // If this is already used as an argument, it is used multiple times (e.g.
1630 // #define X(A,A.
1631 if (II->isMacroArg()) { // C99 6.10.3p6
1632 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1633 return true;
1634 }
1635
1636 // Add the argument to the macro info.
1637 MI->addArgument(II);
1638 // Remember it is an argument now.
1639 II->setIsMacroArg(true);
Chris Lattnercefc7682006-07-08 08:28:12 +00001640
1641 // Lex the token after the identifier.
1642 LexUnexpandedToken(Tok);
1643
1644 switch (Tok.getKind()) {
1645 default: // #define X(A B
1646 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1647 return true;
1648 case tok::r_paren: // #define X(A)
1649 return false;
1650 case tok::comma: // #define X(A,
1651 break;
1652 case tok::ellipsis: // #define X(A... -> GCC extension
1653 // Diagnose extension.
1654 Diag(Tok, diag::ext_named_variadic_macro);
1655
1656 // Lex the token after the identifier.
1657 LexUnexpandedToken(Tok);
1658 if (Tok.getKind() != tok::r_paren) {
1659 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1660 return true;
1661 }
1662
1663 MI->setIsGNUVarargs();
1664 return false;
1665 }
1666 }
1667 }
1668}
1669
Chris Lattner22eb9722006-06-18 05:43:12 +00001670/// HandleDefineDirective - Implements #define. This consumes the entire macro
1671/// line then lets the caller lex the next real token.
1672///
Chris Lattnercb283342006-06-18 06:48:37 +00001673void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001674 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001675
Chris Lattner22eb9722006-06-18 05:43:12 +00001676 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001677 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001678
1679 // Error reading macro name? If so, diagnostic already issued.
1680 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001681 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001682
Chris Lattner50b497e2006-06-18 16:32:35 +00001683 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001684
1685 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001686 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001687
Chris Lattner78186052006-07-09 00:45:31 +00001688 // FIXME: Enable __VA_ARGS__.
1689
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001690 // If this is a function-like macro definition, parse the argument list,
1691 // marking each of the identifiers as being used as macro arguments. Also,
1692 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001693 if (Tok.getKind() == tok::eom) {
1694 // If there is no body to this macro, we have no special handling here.
1695 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001696 // This is a function-like macro definition. Read the argument list.
1697 MI->setIsFunctionLike();
1698 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001699 // Clear the "isMacroArg" flags from all the macro arguments parsed.
1700 MI->SetIdentifierIsMacroArgFlags(false);
1701 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001702 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001703 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001704 if (CurLexer->ParsingPreprocessorDirective)
1705 DiscardUntilEndOfDirective();
1706 return;
1707 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001708
Chris Lattner815a1f92006-07-08 20:48:04 +00001709 // Read the first token after the arg list for down below.
1710 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001711 } else if (!Tok.hasLeadingSpace()) {
1712 // C99 requires whitespace between the macro definition and the body. Emit
1713 // a diagnostic for something like "#define X+".
1714 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001715 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001716 } else {
1717 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1718 // one in some cases!
1719 }
1720 } else {
1721 // This is a normal token with leading space. Clear the leading space
1722 // marker on the first token to get proper expansion.
1723 Tok.ClearFlag(LexerToken::LeadingSpace);
1724 }
1725
1726 // Read the rest of the macro body.
1727 while (Tok.getKind() != tok::eom) {
1728 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001729
1730 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001731 // parameters in function-like macro expansions.
1732 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001733 // Get the next token of the macro.
1734 LexUnexpandedToken(Tok);
1735 continue;
1736 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001737
Chris Lattner815a1f92006-07-08 20:48:04 +00001738 // Get the next token of the macro.
1739 LexUnexpandedToken(Tok);
1740
1741 // Not a macro arg identifier?
1742 if (!Tok.getIdentifierInfo() || !Tok.getIdentifierInfo()->isMacroArg()) {
1743 Diag(Tok, diag::err_pp_stringize_not_parameter);
1744 // Clear the "isMacroArg" flags from all the macro arguments.
1745 MI->SetIdentifierIsMacroArgFlags(false);
1746 delete MI;
1747 return;
1748 }
1749
1750 // Things look ok, add the param name token to the macro.
1751 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001752
Chris Lattner22eb9722006-06-18 05:43:12 +00001753 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001754 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001755 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001756
Chris Lattner78186052006-07-09 00:45:31 +00001757 // Clear the "isMacroArg" flags from all the macro arguments.
1758 MI->SetIdentifierIsMacroArgFlags(false);
1759
Chris Lattnerbff18d52006-07-06 04:49:18 +00001760 // Check that there is no paste (##) operator at the begining or end of the
1761 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001762 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001763 if (NumTokens != 0) {
1764 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001765 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001766 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001767 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001768 }
1769 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001770 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001771 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001772 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001773 }
1774 }
1775
Chris Lattner13044d92006-07-03 05:16:44 +00001776 // If this is the primary source file, remember that this macro hasn't been
1777 // used yet.
1778 if (isInPrimaryFile())
1779 MI->setIsUsed(false);
1780
Chris Lattner22eb9722006-06-18 05:43:12 +00001781 // Finally, if this identifier already had a macro defined for it, verify that
1782 // the macro bodies are identical and free the old definition.
1783 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001784 if (!OtherMI->isUsed())
1785 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1786
Chris Lattner22eb9722006-06-18 05:43:12 +00001787 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001788 // must be the same. C99 6.10.3.2.
1789 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001790 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1791 MacroNameTok.getIdentifierInfo()->getName());
1792 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1793 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001794 delete OtherMI;
1795 }
1796
1797 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001798}
1799
1800
1801/// HandleUndefDirective - Implements #undef.
1802///
Chris Lattnercb283342006-06-18 06:48:37 +00001803void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001804 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001805
Chris Lattner22eb9722006-06-18 05:43:12 +00001806 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001807 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001808
1809 // Error reading macro name? If so, diagnostic already issued.
1810 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001811 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001812
1813 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001814 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001815
1816 // Okay, we finally have a valid identifier to undef.
1817 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1818
1819 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001820 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001821
Chris Lattner13044d92006-07-03 05:16:44 +00001822 if (!MI->isUsed())
1823 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001824
1825 // Free macro definition.
1826 delete MI;
1827 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001828}
1829
1830
Chris Lattnerb8761832006-06-24 21:31:03 +00001831//===----------------------------------------------------------------------===//
1832// Preprocessor Conditional Directive Handling.
1833//===----------------------------------------------------------------------===//
1834
Chris Lattner22eb9722006-06-18 05:43:12 +00001835/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001836/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1837/// if any tokens have been returned or pp-directives activated before this
1838/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001839///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001840void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1841 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001842 ++NumIf;
1843 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001844
Chris Lattner22eb9722006-06-18 05:43:12 +00001845 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001846 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001847
1848 // Error reading macro name? If so, diagnostic already issued.
1849 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001850 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001851
1852 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001853 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1854
1855 // If the start of a top-level #ifdef, inform MIOpt.
1856 if (!ReadAnyTokensBeforeDirective &&
1857 CurLexer->getConditionalStackDepth() == 0) {
1858 assert(isIfndef && "#ifdef shouldn't reach here");
1859 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1860 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001861
Chris Lattnera78a97e2006-07-03 05:42:18 +00001862 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1863
1864 // If there is a macro, mark it used.
1865 if (MI) MI->setIsUsed(true);
1866
Chris Lattner22eb9722006-06-18 05:43:12 +00001867 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001868 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001869 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001870 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001871 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001872 } else {
1873 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001874 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001875 /*Foundnonskip*/false,
1876 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001877 }
1878}
1879
1880/// HandleIfDirective - Implements the #if directive.
1881///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001882void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1883 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001884 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001885
Chris Lattner371ac8a2006-07-04 07:11:10 +00001886 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001887 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001888 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001889
1890 // Should we include the stuff contained by this directive?
1891 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001892 // If this condition is equivalent to #ifndef X, and if this is the first
1893 // directive seen, handle it for the multiple-include optimization.
1894 if (!ReadAnyTokensBeforeDirective &&
1895 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1896 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1897
Chris Lattner22eb9722006-06-18 05:43:12 +00001898 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001899 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001900 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001901 } else {
1902 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001903 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001904 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001905 }
1906}
1907
1908/// HandleEndifDirective - Implements the #endif directive.
1909///
Chris Lattnercb283342006-06-18 06:48:37 +00001910void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001911 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001912
Chris Lattner22eb9722006-06-18 05:43:12 +00001913 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001914 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001915
1916 PPConditionalInfo CondInfo;
1917 if (CurLexer->popConditionalLevel(CondInfo)) {
1918 // No conditionals on the stack: this is an #endif without an #if.
1919 return Diag(EndifToken, diag::err_pp_endif_without_if);
1920 }
1921
Chris Lattner371ac8a2006-07-04 07:11:10 +00001922 // If this the end of a top-level #endif, inform MIOpt.
1923 if (CurLexer->getConditionalStackDepth() == 0)
1924 CurLexer->MIOpt.ExitTopLevelConditional();
1925
Chris Lattner22eb9722006-06-18 05:43:12 +00001926 assert(!CondInfo.WasSkipping && !isSkipping() &&
1927 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001928}
1929
1930
Chris Lattnercb283342006-06-18 06:48:37 +00001931void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001932 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001933
Chris Lattner22eb9722006-06-18 05:43:12 +00001934 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001935 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001936
1937 PPConditionalInfo CI;
1938 if (CurLexer->popConditionalLevel(CI))
1939 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001940
1941 // If this is a top-level #else, inform the MIOpt.
1942 if (CurLexer->getConditionalStackDepth() == 0)
1943 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001944
1945 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001946 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001947
1948 // Finally, skip the rest of the contents of this block and return the first
1949 // token after it.
1950 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1951 /*FoundElse*/true);
1952}
1953
Chris Lattnercb283342006-06-18 06:48:37 +00001954void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001955 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001956
Chris Lattner22eb9722006-06-18 05:43:12 +00001957 // #elif directive in a non-skipping conditional... start skipping.
1958 // We don't care what the condition is, because we will always skip it (since
1959 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001960 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001961
1962 PPConditionalInfo CI;
1963 if (CurLexer->popConditionalLevel(CI))
1964 return Diag(ElifToken, diag::pp_err_elif_without_if);
1965
Chris Lattner371ac8a2006-07-04 07:11:10 +00001966 // If this is a top-level #elif, inform the MIOpt.
1967 if (CurLexer->getConditionalStackDepth() == 0)
1968 CurLexer->MIOpt.FoundTopLevelElse();
1969
Chris Lattner22eb9722006-06-18 05:43:12 +00001970 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001971 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001972
1973 // Finally, skip the rest of the contents of this block and return the first
1974 // token after it.
1975 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1976 /*FoundElse*/CI.FoundElse);
1977}
Chris Lattnerb8761832006-06-24 21:31:03 +00001978