blob: 6aa6fe273f38bfbbd013e4a3627d70cbc058f8b2 [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//
14// TODO: GCC Diagnostics emitted by the lexer:
15//
16// ERROR : __VA_ARGS__ can only appear in the expansion of a C99 variadic macro
17//
18// Options to support:
19// -H - Print the name of each header file used.
20// -C -CC - Do not discard comments for cpp.
Chris Lattner22eb9722006-06-18 05:43:12 +000021// -d[MDNI] - Dump various things.
22// -fworking-directory - #line's with preprocessor's working dir.
23// -fpreprocessed
24// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
25// -W*
26// -w
27//
28// Messages to emit:
29// "Multiple include guards may be useful for:\n"
30//
31// TODO: Implement the include guard optimization.
32//
33//===----------------------------------------------------------------------===//
34
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000037#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000038#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000039#include "clang/Basic/Diagnostic.h"
40#include "clang/Basic/FileManager.h"
41#include "clang/Basic/SourceManager.h"
42#include <iostream>
43using namespace llvm;
44using namespace clang;
45
46//===----------------------------------------------------------------------===//
47
48Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
49 FileManager &FM, SourceManager &SM)
50 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
51 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000052 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000053 ScratchBuf = new ScratchBuffer(SourceMgr);
54
Chris Lattner22eb9722006-06-18 05:43:12 +000055 // Clear stats.
56 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
57 NumIf = NumElse = NumEndif = 0;
58 NumEnteredSourceFiles = NumMacroExpanded = NumFastMacroExpanded = 0;
Chris Lattner3665f162006-07-04 07:26:10 +000059 MaxIncludeStackDepth = 0; NumMultiIncludeFileOptzn = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000061
Chris Lattner22eb9722006-06-18 05:43:12 +000062 // Macro expansion is enabled.
63 DisableMacroExpansion = false;
64 SkippingContents = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000065
66 // There is no file-change handler yet.
67 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000068 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000069
Chris Lattner8ff71992006-07-06 05:17:39 +000070 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
71 // This gets unpoisoned where it is allowed.
72 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
73
Chris Lattnerb8761832006-06-24 21:31:03 +000074 // Initialize the pragma handlers.
75 PragmaHandlers = new PragmaNamespace(0);
76 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000077
78 // Initialize builtin macros like __LINE__ and friends.
79 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000080}
81
82Preprocessor::~Preprocessor() {
83 // Free any active lexers.
84 delete CurLexer;
85
Chris Lattner69772b02006-07-02 20:34:39 +000086 while (!IncludeMacroStack.empty()) {
87 delete IncludeMacroStack.back().TheLexer;
88 delete IncludeMacroStack.back().TheMacroExpander;
89 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000090 }
Chris Lattnerb8761832006-06-24 21:31:03 +000091
92 // Release pragma information.
93 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000094
95 // Delete the scratch buffer info.
96 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000097}
98
99/// getFileInfo - Return the PerFileInfo structure for the specified
100/// FileEntry.
101Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
102 if (FE->getUID() >= FileInfo.size())
103 FileInfo.resize(FE->getUID()+1);
104 return FileInfo[FE->getUID()];
105}
106
107
108/// AddKeywords - Add all keywords to the symbol table.
109///
110void Preprocessor::AddKeywords() {
111 enum {
112 C90Shift = 0,
113 EXTC90 = 1 << C90Shift,
114 NOTC90 = 2 << C90Shift,
115 C99Shift = 2,
116 EXTC99 = 1 << C99Shift,
117 NOTC99 = 2 << C99Shift,
118 CPPShift = 4,
119 EXTCPP = 1 << CPPShift,
120 NOTCPP = 2 << CPPShift,
121 Mask = 3
122 };
123
124 // Add keywords and tokens for the current language.
125#define KEYWORD(NAME, FLAGS) \
126 AddKeyword(#NAME+1, tok::kw##NAME, \
127 (FLAGS >> C90Shift) & Mask, \
128 (FLAGS >> C99Shift) & Mask, \
129 (FLAGS >> CPPShift) & Mask);
130#define ALIAS(NAME, TOK) \
131 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
132#include "clang/Basic/TokenKinds.def"
133}
134
135/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
136/// the specified LexerToken's location, translating the token's start
137/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000138void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000139 const std::string &Msg) {
140 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
141 // warnings or extensions.
142 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000143 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000144
Chris Lattnercb283342006-06-18 06:48:37 +0000145 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000146}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000147
148void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
149 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
150 << getSpelling(Tok) << "'";
151
152 if (!DumpFlags) return;
153 std::cerr << "\t";
154 if (Tok.isAtStartOfLine())
155 std::cerr << " [StartOfLine]";
156 if (Tok.hasLeadingSpace())
157 std::cerr << " [LeadingSpace]";
158 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000159 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000160 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
161 << "']";
162 }
163}
164
165void Preprocessor::DumpMacro(const MacroInfo &MI) const {
166 std::cerr << "MACRO: ";
167 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
168 DumpToken(MI.getReplacementToken(i));
169 std::cerr << " ";
170 }
171 std::cerr << "\n";
172}
173
Chris Lattner22eb9722006-06-18 05:43:12 +0000174void Preprocessor::PrintStats() {
175 std::cerr << "\n*** Preprocessor Stats:\n";
176 std::cerr << FileInfo.size() << " files tracked.\n";
177 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
178 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
179 NumOnceOnlyFiles += FileInfo[i].isImport;
180 if (MaxNumIncludes < FileInfo[i].NumIncludes)
181 MaxNumIncludes = FileInfo[i].NumIncludes;
182 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
183 }
184 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
185 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
186 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
187
188 std::cerr << NumDirectives << " directives found:\n";
189 std::cerr << " " << NumDefined << " #define.\n";
190 std::cerr << " " << NumUndefined << " #undef.\n";
191 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
Chris Lattner3665f162006-07-04 07:26:10 +0000192 std::cerr << " " << NumMultiIncludeFileOptzn << " #includes skipped due to"
193 << " the multi-include optimization.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000194 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
195 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
196 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
197 std::cerr << " " << NumElse << " #else/#elif.\n";
198 std::cerr << " " << NumEndif << " #endif.\n";
199 std::cerr << " " << NumPragma << " #pragma.\n";
200 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
201
202 std::cerr << NumMacroExpanded << " macros expanded, "
203 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000204}
205
206//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000207// Token Spelling
208//===----------------------------------------------------------------------===//
209
210
211/// getSpelling() - Return the 'spelling' of this token. The spelling of a
212/// token are the characters used to represent the token in the source file
213/// after trigraph expansion and escaped-newline folding. In particular, this
214/// wants to get the true, uncanonicalized, spelling of things like digraphs
215/// UCNs, etc.
216std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
217 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
218
219 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000220 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 if (!Tok.needsCleaning())
222 return std::string(TokStart, TokStart+Tok.getLength());
223
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224 std::string Result;
225 Result.reserve(Tok.getLength());
226
Chris Lattneref9eae12006-07-04 22:33:12 +0000227 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000228 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
229 Ptr != End; ) {
230 unsigned CharSize;
231 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
232 Ptr += CharSize;
233 }
234 assert(Result.size() != unsigned(Tok.getLength()) &&
235 "NeedsCleaning flag set on something that didn't need cleaning!");
236 return Result;
237}
238
239/// getSpelling - This method is used to get the spelling of a token into a
240/// preallocated buffer, instead of as an std::string. The caller is required
241/// to allocate enough space for the token, which is guaranteed to be at least
242/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000243///
244/// Note that this method may do two possible things: it may either fill in
245/// the buffer specified with characters, or it may *change the input pointer*
246/// to point to a constant buffer with the data already in it (avoiding a
247/// copy). The caller is not allowed to modify the returned buffer pointer
248/// if an internal buffer is returned.
249unsigned Preprocessor::getSpelling(const LexerToken &Tok,
250 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000251 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
252
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000253 // If this token is an identifier, just return the string from the identifier
254 // table, which is very quick.
255 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
256 Buffer = II->getName();
257 return Tok.getLength();
258 }
259
260 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000261 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000262
263 // If this token contains nothing interesting, return it directly.
264 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000265 Buffer = TokStart;
266 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000267 }
268 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000269 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000270 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
271 Ptr != End; ) {
272 unsigned CharSize;
273 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
274 Ptr += CharSize;
275 }
276 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
277 "NeedsCleaning flag set on something that didn't need cleaning!");
278
279 return OutBuf-Buffer;
280}
281
282//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000283// Source File Location Methods.
284//===----------------------------------------------------------------------===//
285
286
287/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
288/// return null on failure. isAngled indicates whether the file reference is
289/// for system #include's or not (i.e. using <> instead of "").
290const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000291 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000292 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000293 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000294 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000295 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000296
297 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000298 // FIXME: Portability. This should be a sys::Path interface, this doesn't
299 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000300 if (Filename[0] == '/') {
301 // If this was an #include_next "/absolute/file", fail.
302 if (FromDir) return 0;
303
304 // Otherwise, just return the file.
305 return FileMgr.getFile(Filename);
306 }
307
308 // Step #0, unless disabled, check to see if the file is in the #includer's
309 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000310 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000311 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
312 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000313 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000314 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000315 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000316 if (const FileEntry *FE =
317 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000318 if (CurDirLookup)
319 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000320 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000321 CurDir = 0;
322
323 // This file is a system header or C++ unfriendly if the old file is.
324 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000325 return FE;
326 }
327 }
328 }
329
330 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000331 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000332
333 // If this is a #include_next request, start searching after the directory the
334 // file was found in.
335 if (FromDir)
336 i = FromDir-&SearchDirs[0];
337
338 // Check each directory in sequence to see if it contains this file.
339 for (; i != SearchDirs.size(); ++i) {
340 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000341 // FIXME: Portability. Adding file to dir should be in sys::Path.
342 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
343 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000344 CurDir = &SearchDirs[i];
345
346 // This file is a system header or C++ unfriendly if the dir is.
347 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000348 return FE;
349 }
350 }
351
352 // Otherwise, didn't find it.
353 return 0;
354}
355
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000356/// isInPrimaryFile - Return true if we're in the top-level file, not in a
357/// #include.
358bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000359 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000360 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000361
Chris Lattner13044d92006-07-03 05:16:44 +0000362 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000363 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000364 if (IncludeMacroStack[i].TheLexer &&
365 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
366 return IncludeMacroStack[i].TheLexer->isMainFile();
367 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000368}
369
370/// getCurrentLexer - Return the current file lexer being lexed from. Note
371/// that this ignores any potentially active macro expansions and _Pragma
372/// expansions going on at the time.
373Lexer *Preprocessor::getCurrentFileLexer() const {
374 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
375
376 // Look for a stacked lexer.
377 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000378 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000379 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
380 return L;
381 }
382 return 0;
383}
384
385
Chris Lattner22eb9722006-06-18 05:43:12 +0000386/// EnterSourceFile - Add a source file to the top of the include stack and
387/// start lexing tokens from it instead of the current buffer. Return true
388/// on failure.
389void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000390 const DirectoryLookup *CurDir,
391 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000392 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000393 ++NumEnteredSourceFiles;
394
Chris Lattner69772b02006-07-02 20:34:39 +0000395 if (MaxIncludeStackDepth < IncludeMacroStack.size())
396 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000397
Chris Lattner22eb9722006-06-18 05:43:12 +0000398 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000399 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000400 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000401 EnterSourceFileWithLexer(TheLexer, CurDir);
402}
Chris Lattner22eb9722006-06-18 05:43:12 +0000403
Chris Lattner69772b02006-07-02 20:34:39 +0000404/// EnterSourceFile - Add a source file to the top of the include stack and
405/// start lexing tokens from it instead of the current buffer.
406void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
407 const DirectoryLookup *CurDir) {
408
409 // Add the current lexer to the include stack.
410 if (CurLexer || CurMacroExpander)
411 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
412 CurMacroExpander));
413
414 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000415 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000416 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000417
418 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000419 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000420 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
421
422 // Get the file entry for the current file.
423 if (const FileEntry *FE =
424 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
425 FileType = getFileInfo(FE).DirInfo;
426
Chris Lattner1840e492006-07-02 22:30:01 +0000427 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000428 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000429 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000430}
431
Chris Lattner69772b02006-07-02 20:34:39 +0000432
433
Chris Lattner22eb9722006-06-18 05:43:12 +0000434/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000435/// tokens from it instead of the current buffer.
436void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000437 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000438 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000439 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
440 CurMacroExpander));
441 CurLexer = 0;
442 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000443
444 // TODO: Figure out arguments.
445
446 // Mark the macro as currently disabled, so that it is not recursively
447 // expanded.
448 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000449 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000450}
451
Chris Lattner22eb9722006-06-18 05:43:12 +0000452//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000453// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000454//===----------------------------------------------------------------------===//
455
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000456/// RegisterBuiltinMacro - Register the specified identifier in the identifier
457/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000458IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000459 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000460 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000461
462 // Mark it as being a macro that is builtin.
463 MacroInfo *MI = new MacroInfo(SourceLocation());
464 MI->setIsBuiltinMacro();
465 Id->setMacroInfo(MI);
466 return Id;
467}
468
469
Chris Lattner677757a2006-06-28 05:26:32 +0000470/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
471/// identifier table.
472void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000473 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000474 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000475 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
476 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000477 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000478
479 // GCC Extensions.
480 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
481 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000482 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000483}
484
Chris Lattner677757a2006-06-28 05:26:32 +0000485
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000486/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
487/// expanded as a macro, handle it and return the next token as 'Identifier'.
488void Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
489 MacroInfo *MI) {
490 ++NumMacroExpanded;
Chris Lattner13044d92006-07-03 05:16:44 +0000491
492 // Notice that this macro has been used.
493 MI->setIsUsed(true);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000494
495 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
496 if (MI->isBuiltinMacro())
Chris Lattner69772b02006-07-02 20:34:39 +0000497 return ExpandBuiltinMacro(Identifier);
498
499 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000500 // FIXME: Fn-Like Macros: Read/Validate the argument list here!
Chris Lattner69772b02006-07-02 20:34:39 +0000501
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000502
503 // If this macro expands to no tokens, don't bother to push it onto the
504 // expansion stack, only to take it right back off.
505 if (MI->getNumTokens() == 0) {
506 // Ignore this macro use, just return the next token in the current
507 // buffer.
508 bool HadLeadingSpace = Identifier.hasLeadingSpace();
509 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
510
511 Lex(Identifier);
512
513 // If the identifier isn't on some OTHER line, inherit the leading
514 // whitespace/first-on-a-line property of this token. This handles
515 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
516 // empty.
517 if (!Identifier.isAtStartOfLine()) {
518 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
519 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
520 }
521 ++NumFastMacroExpanded;
522 return;
523
524 } else if (MI->getNumTokens() == 1 &&
525 // Don't handle identifiers if they need recursive expansion.
526 (MI->getReplacementToken(0).getIdentifierInfo() == 0 ||
527 !MI->getReplacementToken(0).getIdentifierInfo()->getMacroInfo())){
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000528 // FIXME: Fn-Like Macros: Function-style macros only if no arguments?
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000529
530 // Otherwise, if this macro expands into a single trivially-expanded
531 // token: expand it now. This handles common cases like
532 // "#define VAL 42".
533
534 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
535 // identifier to the expanded token.
536 bool isAtStartOfLine = Identifier.isAtStartOfLine();
537 bool hasLeadingSpace = Identifier.hasLeadingSpace();
538
539 // Remember where the token is instantiated.
540 SourceLocation InstantiateLoc = Identifier.getLocation();
541
542 // Replace the result token.
543 Identifier = MI->getReplacementToken(0);
544
545 // Restore the StartOfLine/LeadingSpace markers.
546 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
547 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
548
549 // Update the tokens location to include both its logical and physical
550 // locations.
551 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000552 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000553 Identifier.SetLocation(Loc);
554
555 // Since this is not an identifier token, it can't be macro expanded, so
556 // we're done.
557 ++NumFastMacroExpanded;
558 return;
559 }
560
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000561 // Start expanding the macro (FIXME: Fn-Like Macros: pass arguments).
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000562 EnterMacro(Identifier);
563
564 // Now that the macro is at the top of the include stack, ask the
565 // preprocessor to read the next token from it.
566 return Lex(Identifier);
567}
568
Chris Lattnerc673f902006-06-30 06:10:41 +0000569/// ComputeDATE_TIME - Compute the current time, enter it into the specified
570/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
571/// the identifier tokens inserted.
572static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
573 ScratchBuffer *ScratchBuf) {
574 time_t TT = time(0);
575 struct tm *TM = localtime(&TT);
576
577 static const char * const Months[] = {
578 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
579 };
580
581 char TmpBuffer[100];
582 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
583 TM->tm_year+1900);
584 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
585
586 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
587 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
588}
589
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000590/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
591/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000592void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000593 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000594 IdentifierInfo *II = Tok.getIdentifierInfo();
595 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000596
597 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
598 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000599 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000600 return Handle_Pragma(Tok);
601
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000602 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000603
604 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000605 Tok.SetIdentifierInfo(0);
606 Tok.ClearFlag(LexerToken::NeedsCleaning);
607
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000608 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000609 // __LINE__ expands to a simple numeric value.
610 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
611 unsigned Length = strlen(TmpBuffer);
612 Tok.SetKind(tok::numeric_constant);
613 Tok.SetLength(Length);
614 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000615 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000616 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000617 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000618 Diag(Tok, diag::ext_pp_base_file);
619 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
620 while (NextLoc.getFileID() != 0) {
621 Loc = NextLoc;
622 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
623 }
624 }
625
Chris Lattner0766e592006-07-03 01:07:01 +0000626 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
627 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000628 FN = Lexer::Stringify(FN);
Chris Lattner630b33c2006-07-01 22:46:53 +0000629 Tok.SetKind(tok::string_literal);
630 Tok.SetLength(FN.size());
631 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000632 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000633 if (!DATELoc.isValid())
634 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
635 Tok.SetKind(tok::string_literal);
636 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
637 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000638 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000639 if (!TIMELoc.isValid())
640 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
641 Tok.SetKind(tok::string_literal);
642 Tok.SetLength(strlen("\"hh:mm:ss\""));
643 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000644 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000645 Diag(Tok, diag::ext_pp_include_level);
646
647 // Compute the include depth of this token.
648 unsigned Depth = 0;
649 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
650 for (; Loc.getFileID() != 0; ++Depth)
651 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
652
653 // __INCLUDE_LEVEL__ expands to a simple numeric value.
654 sprintf(TmpBuffer, "%u", Depth);
655 unsigned Length = strlen(TmpBuffer);
656 Tok.SetKind(tok::numeric_constant);
657 Tok.SetLength(Length);
658 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000659 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000660 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
661 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
662 Diag(Tok, diag::ext_pp_timestamp);
663
664 // Get the file that we are lexing out of. If we're currently lexing from
665 // a macro, dig into the include stack.
666 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000667 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000668
669 if (TheLexer)
670 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
671
672 // If this file is older than the file it depends on, emit a diagnostic.
673 const char *Result;
674 if (CurFile) {
675 time_t TT = CurFile->getModificationTime();
676 struct tm *TM = localtime(&TT);
677 Result = asctime(TM);
678 } else {
679 Result = "??? ??? ?? ??:??:?? ????\n";
680 }
681 TmpBuffer[0] = '"';
682 strcpy(TmpBuffer+1, Result);
683 unsigned Len = strlen(TmpBuffer);
684 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
685 Tok.SetKind(tok::string_literal);
686 Tok.SetLength(Len);
687 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000688 } else {
689 assert(0 && "Unknown identifier!");
690 }
691}
Chris Lattner677757a2006-06-28 05:26:32 +0000692
Chris Lattner13044d92006-07-03 05:16:44 +0000693namespace {
694struct UnusedIdentifierReporter : public IdentifierVisitor {
695 Preprocessor &PP;
696 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
697
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000698 void VisitIdentifier(IdentifierInfo &II) const {
699 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
700 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000701 }
702};
703}
704
Chris Lattner677757a2006-06-28 05:26:32 +0000705//===----------------------------------------------------------------------===//
706// Lexer Event Handling.
707//===----------------------------------------------------------------------===//
708
709/// HandleIdentifier - This callback is invoked when the lexer reads an
710/// identifier. This callback looks up the identifier in the map and/or
711/// potentially macro expands it or turns it into a named token (like 'for').
712void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
713 if (Identifier.getIdentifierInfo() == 0) {
714 // If we are skipping tokens (because we are in a #if 0 block), there will
715 // be no identifier info, just return the token.
716 assert(isSkipping() && "Token isn't an identifier?");
717 return;
718 }
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000719 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000720
721 // If this identifier was poisoned, and if it was not produced from a macro
722 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000723 if (II.isPoisoned() && CurLexer) {
724 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
725 Diag(Identifier, diag::err_pp_used_poisoned_id);
726 else
727 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
728 }
Chris Lattner677757a2006-06-28 05:26:32 +0000729
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000730 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +0000731 if (MI->isEnabled() && !DisableMacroExpansion)
732 return HandleMacroExpandedIdentifier(Identifier, MI);
733
734 // Change the kind of this identifier to the appropriate token kind, e.g.
735 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000736 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000737
738 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000739 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000740}
741
Chris Lattner22eb9722006-06-18 05:43:12 +0000742/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
743/// the current file. This either returns the EOF token or pops a level off
744/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000745void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000746 assert(!CurMacroExpander &&
747 "Ending a file when currently in a macro!");
748
749 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
750 // this is an error condition. Just return the EOF token up to
751 // SkipExcludedConditionalBlock. The Lexer will have already have issued
752 // errors for the unterminated #if's on the conditional stack.
753 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000754 Result.StartToken();
755 CurLexer->BufferPtr = CurLexer->BufferEnd;
756 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000757 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000758 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000759 }
760
Chris Lattner371ac8a2006-07-04 07:11:10 +0000761 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000762 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000763 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000764 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000765 // Okay, this has a controlling macro, remember in PerFileInfo.
766 if (const FileEntry *FE =
767 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
768 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +0000769 }
770 }
771
Chris Lattner22eb9722006-06-18 05:43:12 +0000772 // If this is a #include'd file, pop it off the include stack and continue
773 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000774 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000775 // We're done with the #included file.
776 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000777 CurLexer = IncludeMacroStack.back().TheLexer;
778 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
779 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
780 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000781
782 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000783 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000784 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
785
786 // Get the file entry for the current file.
787 if (const FileEntry *FE =
788 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
789 FileType = getFileInfo(FE).DirInfo;
790
Chris Lattner0c885f52006-06-21 06:50:18 +0000791 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000792 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000793 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000794
Chris Lattner22eb9722006-06-18 05:43:12 +0000795 return Lex(Result);
796 }
797
Chris Lattnerd01e2912006-06-18 16:22:51 +0000798 Result.StartToken();
799 CurLexer->BufferPtr = CurLexer->BufferEnd;
800 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000801 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000802
803 // We're done with the #included file.
804 delete CurLexer;
805 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +0000806
807 // This is the end of the top-level file.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000808 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +0000809}
810
811/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000812/// the current macro line.
813void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000814 assert(CurMacroExpander && !CurLexer &&
815 "Ending a macro when currently in a #include file!");
816
817 // Mark macro not ignored now that it is no longer being expanded.
818 CurMacroExpander->getMacro().EnableMacro();
819 delete CurMacroExpander;
820
Chris Lattner69772b02006-07-02 20:34:39 +0000821 // Handle this like a #include file being popped off the stack.
822 CurMacroExpander = 0;
823 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000824}
825
826
827//===----------------------------------------------------------------------===//
828// Utility Methods for Preprocessor Directive Handling.
829//===----------------------------------------------------------------------===//
830
831/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
832/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000833void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000834 LexerToken Tmp;
835 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000836 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000837 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000838}
839
840/// ReadMacroName - Lex and validate a macro name, which occurs after a
841/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +0000842/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
843/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +0000844/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +0000845void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000846 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000847 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000848
849 // Missing macro name?
850 if (MacroNameTok.getKind() == tok::eom)
851 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
852
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000853 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
854 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000855 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000856 // Fall through on error.
857 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000858 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +0000859
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000860 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
861 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000862 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +0000863 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000864 } else if (isDefineUndef && II->getMacroInfo() &&
865 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000866 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +0000867 if (isDefineUndef == 1)
868 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
869 else
870 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +0000871 } else {
872 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000873 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000874 }
875
Chris Lattner22eb9722006-06-18 05:43:12 +0000876 // Invalid macro name, read and discard the rest of the line. Then set the
877 // token kind to tok::eom.
878 MacroNameTok.SetKind(tok::eom);
879 return DiscardUntilEndOfDirective();
880}
881
882/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
883/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000884void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000885 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000886 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000887 // There should be no tokens after the directive, but we allow them as an
888 // extension.
889 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000890 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
891 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000892 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000893}
894
895
896
897/// SkipExcludedConditionalBlock - We just read a #if or related directive and
898/// decided that the subsequent tokens are in the #if'd out portion of the
899/// file. Lex the rest of the file, until we see an #endif. If
900/// FoundNonSkipPortion is true, then we have already emitted code for part of
901/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
902/// is true, then #else directives are ok, if not, then we have already seen one
903/// so a #else directive is a duplicate. When this returns, the caller can lex
904/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000905void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000906 bool FoundNonSkipPortion,
907 bool FoundElse) {
908 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +0000909 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +0000910 "Lexing a macro, not a file?");
911
912 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
913 FoundNonSkipPortion, FoundElse);
914
915 // Know that we are going to be skipping tokens. Set this flag to indicate
916 // this, which has a couple of effects:
917 // 1. If EOF of the current lexer is found, the include stack isn't popped.
918 // 2. Identifier information is not looked up for identifier tokens. As an
919 // effect of this, implicit macro expansion is naturally disabled.
920 // 3. "#" tokens at the start of a line are treated as normal tokens, not
921 // implicitly transformed by the lexer.
922 // 4. All notes, warnings, and extension messages are disabled.
923 //
924 SkippingContents = true;
925 LexerToken Tok;
926 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000927 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000928
929 // If this is the end of the buffer, we have an error. The lexer will have
930 // already handled this error condition, so just return and let the caller
931 // lex after this #include.
932 if (Tok.getKind() == tok::eof) break;
933
934 // If this token is not a preprocessor directive, just skip it.
935 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
936 continue;
937
938 // We just parsed a # character at the start of a line, so we're in
939 // directive mode. Tell the lexer this so any newlines we see will be
940 // converted into an EOM token (this terminates the macro).
941 CurLexer->ParsingPreprocessorDirective = true;
942
943 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000944 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000945
946 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
947 // something bogus), skip it.
948 if (Tok.getKind() != tok::identifier) {
949 CurLexer->ParsingPreprocessorDirective = false;
950 continue;
951 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000952
Chris Lattner22eb9722006-06-18 05:43:12 +0000953 // If the first letter isn't i or e, it isn't intesting to us. We know that
954 // this is safe in the face of spelling differences, because there is no way
955 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000956 // allows us to avoid looking up the identifier info for #define/#undef and
957 // other common directives.
958 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
959 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000960 if (FirstChar >= 'a' && FirstChar <= 'z' &&
961 FirstChar != 'i' && FirstChar != 'e') {
962 CurLexer->ParsingPreprocessorDirective = false;
963 continue;
964 }
965
Chris Lattnere60165f2006-06-22 06:36:29 +0000966 // Get the identifier name without trigraphs or embedded newlines. Note
967 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
968 // when skipping.
969 // TODO: could do this with zero copies in the no-clean case by using
970 // strncmp below.
971 char Directive[20];
972 unsigned IdLen;
973 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
974 IdLen = Tok.getLength();
975 memcpy(Directive, RawCharData, IdLen);
976 Directive[IdLen] = 0;
977 } else {
978 std::string DirectiveStr = getSpelling(Tok);
979 IdLen = DirectiveStr.size();
980 if (IdLen >= 20) {
981 CurLexer->ParsingPreprocessorDirective = false;
982 continue;
983 }
984 memcpy(Directive, &DirectiveStr[0], IdLen);
985 Directive[IdLen] = 0;
986 }
987
Chris Lattner22eb9722006-06-18 05:43:12 +0000988 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000989 if ((IdLen == 2) || // "if"
990 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
991 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +0000992 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
993 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000994 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000995 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000996 /*foundnonskip*/false,
997 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000998 }
999 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001000 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001001 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001002 PPConditionalInfo CondInfo;
1003 CondInfo.WasSkipping = true; // Silence bogus warning.
1004 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1005 assert(!InCond && "Can't be skipping if not in a conditional!");
1006
1007 // If we popped the outermost skipping block, we're done skipping!
1008 if (!CondInfo.WasSkipping)
1009 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001010 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001011 // #else directive in a skipping conditional. If not in some other
1012 // skipping conditional, and if #else hasn't already been seen, enter it
1013 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001014 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001015 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1016
1017 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001018 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001019
1020 // Note that we've seen a #else in this conditional.
1021 CondInfo.FoundElse = true;
1022
1023 // If the conditional is at the top level, and the #if block wasn't
1024 // entered, enter the #else block now.
1025 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1026 CondInfo.FoundNonSkip = true;
1027 break;
1028 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001029 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001030 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1031
1032 bool ShouldEnter;
1033 // If this is in a skipping block or if we're already handled this #if
1034 // block, don't bother parsing the condition.
1035 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001036 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001037 ShouldEnter = false;
1038 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00001039 // Restore the value of SkippingContents so that identifiers are
1040 // looked up, etc, inside the #elif expression.
1041 assert(SkippingContents && "We have to be skipping here!");
1042 SkippingContents = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001043 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001044 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001045 SkippingContents = true;
1046 }
1047
1048 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001049 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001050
1051 // If this condition is true, enter it!
1052 if (ShouldEnter) {
1053 CondInfo.FoundNonSkip = true;
1054 break;
1055 }
1056 }
1057 }
1058
1059 CurLexer->ParsingPreprocessorDirective = false;
1060 }
1061
1062 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1063 // of the file, just stop skipping and return to lexing whatever came after
1064 // the #if block.
1065 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001066}
1067
1068//===----------------------------------------------------------------------===//
1069// Preprocessor Directive Handling.
1070//===----------------------------------------------------------------------===//
1071
1072/// HandleDirective - This callback is invoked when the lexer sees a # token
1073/// at the start of a line. This consumes the directive, modifies the
1074/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1075/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001076void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001077 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001078
1079 // We just parsed a # character at the start of a line, so we're in directive
1080 // mode. Tell the lexer this so any newlines we see will be converted into an
1081 // EOM token (this terminates the macro).
1082 CurLexer->ParsingPreprocessorDirective = true;
1083
1084 ++NumDirectives;
1085
Chris Lattner371ac8a2006-07-04 07:11:10 +00001086 // We are about to read a token. For the multiple-include optimization FA to
1087 // work, we have to remember if we had read any tokens *before* this
1088 // pp-directive.
1089 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1090
Chris Lattner22eb9722006-06-18 05:43:12 +00001091 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001092 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001093
1094 switch (Result.getKind()) {
1095 default: break;
1096 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001097 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001098
1099#if 0
1100 case tok::numeric_constant:
1101 // FIXME: implement # 7 line numbers!
1102 break;
1103#endif
1104 case tok::kw_else:
1105 return HandleElseDirective(Result);
1106 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001107 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001108 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001109 // Get the identifier name without trigraphs or embedded newlines.
1110 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001111 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001112 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001113 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001114 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001115 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001116 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001117 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001118 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1119 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001120 break;
1121 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001122 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001123 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001124 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001125 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001126 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001127 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001128 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001129 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001130 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001131 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001132 break;
1133 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001134 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001136 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001137 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001138 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001139 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001140 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001141 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001142 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1143 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001144 break;
1145 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001146 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1147 return HandleIncludeDirective(Result); // Handle #include.
1148 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001149 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001150 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001151 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 break;
1153 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001154 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001155 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001156 }
1157 break;
1158 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001159 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1160 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001161 break;
1162 }
1163 break;
1164 }
1165
1166 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001167 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001168
1169 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001170 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001171
1172 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001173}
1174
Chris Lattner01d66cc2006-07-03 22:16:27 +00001175void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001176 bool isWarning) {
1177 // Read the rest of the line raw. We do this because we don't want macros
1178 // to be expanded and we don't require that the tokens be valid preprocessing
1179 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1180 // collapse multiple consequtive white space between tokens, but this isn't
1181 // specified by the standard.
1182 std::string Message = CurLexer->ReadToEndOfLine();
1183
1184 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001185 return Diag(Tok, DiagID, Message);
1186}
1187
1188/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1189///
1190void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001191 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001192 Diag(Tok, diag::ext_pp_ident_directive);
1193
Chris Lattner371ac8a2006-07-04 07:11:10 +00001194 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001195 LexerToken StrTok;
1196 Lex(StrTok);
1197
1198 // If the token kind isn't a string, it's a malformed directive.
1199 if (StrTok.getKind() != tok::string_literal)
1200 return Diag(StrTok, diag::err_pp_malformed_ident);
1201
1202 // Verify that there is nothing after the string, other than EOM.
1203 CheckEndOfDirective("#ident");
1204
1205 if (IdentHandler)
1206 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001207}
1208
Chris Lattnerb8761832006-06-24 21:31:03 +00001209//===----------------------------------------------------------------------===//
1210// Preprocessor Include Directive Handling.
1211//===----------------------------------------------------------------------===//
1212
Chris Lattner22eb9722006-06-18 05:43:12 +00001213/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1214/// file to be included from the lexer, then include it! This is a common
1215/// routine with functionality shared between #include, #include_next and
1216/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001217void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001218 const DirectoryLookup *LookupFrom,
1219 bool isImport) {
1220 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001221
Chris Lattner22eb9722006-06-18 05:43:12 +00001222 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001223 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001224
1225 // If the token kind is EOM, the error has already been diagnosed.
1226 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001227 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001228
1229 // Verify that there is nothing after the filename, other than EOM. Use the
1230 // preprocessor to lex this in case lexing the filename entered a macro.
1231 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001232
1233 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001234 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001235 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1236
Chris Lattner269c2322006-06-25 06:23:00 +00001237 // Find out whether the filename is <x> or "x".
1238 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001239
1240 // Remove the quotes.
1241 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1242
Chris Lattner22eb9722006-06-18 05:43:12 +00001243 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001244 const DirectoryLookup *CurDir;
1245 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001246 if (File == 0)
1247 return Diag(FilenameTok, diag::err_pp_file_not_found);
1248
1249 // Get information about this file.
1250 PerFileInfo &FileInfo = getFileInfo(File);
1251
1252 // If this is a #import directive, check that we have not already imported
1253 // this header.
1254 if (isImport) {
1255 // If this has already been imported, don't import it again.
1256 FileInfo.isImport = true;
1257
1258 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001259 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001260 } else {
1261 // Otherwise, if this is a #include of a file that was previously #import'd
1262 // or if this is the second #include of a #pragma once file, ignore it.
1263 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001264 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001265 }
Chris Lattner3665f162006-07-04 07:26:10 +00001266
1267 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1268 // if the macro that guards it is defined, we know the #include has no effect.
1269 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1270 ++NumMultiIncludeFileOptzn;
1271 return;
1272 }
1273
Chris Lattner22eb9722006-06-18 05:43:12 +00001274
1275 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001276 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001277 if (FileID == 0)
1278 return Diag(FilenameTok, diag::err_pp_file_not_found);
1279
1280 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001281 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001282
1283 // Increment the number of times this file has been included.
1284 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001285}
1286
1287/// HandleIncludeNextDirective - Implements #include_next.
1288///
Chris Lattnercb283342006-06-18 06:48:37 +00001289void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1290 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001291
1292 // #include_next is like #include, except that we start searching after
1293 // the current found directory. If we can't do this, issue a
1294 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001295 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001296 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001297 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001298 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001299 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001300 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001301 } else {
1302 // Start looking up in the next directory.
1303 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001304 }
1305
1306 return HandleIncludeDirective(IncludeNextTok, Lookup);
1307}
1308
1309/// HandleImportDirective - Implements #import.
1310///
Chris Lattnercb283342006-06-18 06:48:37 +00001311void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1312 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001313
1314 return HandleIncludeDirective(ImportTok, 0, true);
1315}
1316
Chris Lattnerb8761832006-06-24 21:31:03 +00001317//===----------------------------------------------------------------------===//
1318// Preprocessor Macro Directive Handling.
1319//===----------------------------------------------------------------------===//
1320
Chris Lattner22eb9722006-06-18 05:43:12 +00001321/// HandleDefineDirective - Implements #define. This consumes the entire macro
1322/// line then lets the caller lex the next real token.
1323///
Chris Lattnercb283342006-06-18 06:48:37 +00001324void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001325 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001326
Chris Lattner22eb9722006-06-18 05:43:12 +00001327 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001328 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001329
1330 // Error reading macro name? If so, diagnostic already issued.
1331 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001332 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001333
Chris Lattner50b497e2006-06-18 16:32:35 +00001334 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001335
1336 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001337 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001338
1339 if (Tok.getKind() == tok::eom) {
1340 // If there is no body to this macro, we have no special handling here.
1341 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1342 // This is a function-like macro definition.
1343 //assert(0 && "Function-like macros not implemented!");
Chris Lattnerbff18d52006-07-06 04:49:18 +00001344 delete MI;
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 return DiscardUntilEndOfDirective();
1346
1347 } else if (!Tok.hasLeadingSpace()) {
1348 // C99 requires whitespace between the macro definition and the body. Emit
1349 // a diagnostic for something like "#define X+".
1350 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001351 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001352 } else {
1353 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1354 // one in some cases!
1355 }
1356 } else {
1357 // This is a normal token with leading space. Clear the leading space
1358 // marker on the first token to get proper expansion.
1359 Tok.ClearFlag(LexerToken::LeadingSpace);
1360 }
1361
1362 // Read the rest of the macro body.
1363 while (Tok.getKind() != tok::eom) {
1364 MI->AddTokenToBody(Tok);
1365
Chris Lattnerbff18d52006-07-06 04:49:18 +00001366 // FIXME: Check for #'s that aren't followed by argument names.
1367 // See create_iso_definition.
1368
Chris Lattner22eb9722006-06-18 05:43:12 +00001369 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001370 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001371 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001372
1373 unsigned NumTokens = MI->getNumTokens();
1374
1375 // Check that there is no paste (##) operator at the begining or end of the
1376 // replacement list.
1377 if (NumTokens != 0) {
1378 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
1379 SourceLocation Loc = MI->getReplacementToken(0).getLocation();
1380 delete MI;
1381 return Diag(Loc, diag::err_paste_at_start);
1382 }
1383 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
1384 SourceLocation Loc = MI->getReplacementToken(NumTokens-1).getLocation();
1385 delete MI;
1386 return Diag(Loc, diag::err_paste_at_end);
1387 }
1388 }
1389
Chris Lattner22eb9722006-06-18 05:43:12 +00001390
Chris Lattner13044d92006-07-03 05:16:44 +00001391 // If this is the primary source file, remember that this macro hasn't been
1392 // used yet.
1393 if (isInPrimaryFile())
1394 MI->setIsUsed(false);
1395
Chris Lattner22eb9722006-06-18 05:43:12 +00001396 // Finally, if this identifier already had a macro defined for it, verify that
1397 // the macro bodies are identical and free the old definition.
1398 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001399 if (!OtherMI->isUsed())
1400 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1401
Chris Lattner22eb9722006-06-18 05:43:12 +00001402 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001403 // must be the same. C99 6.10.3.2.
1404 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001405 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1406 MacroNameTok.getIdentifierInfo()->getName());
1407 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1408 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001409 delete OtherMI;
1410 }
1411
1412 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001413}
1414
1415
1416/// HandleUndefDirective - Implements #undef.
1417///
Chris Lattnercb283342006-06-18 06:48:37 +00001418void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001419 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001420
Chris Lattner22eb9722006-06-18 05:43:12 +00001421 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001422 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001423
1424 // Error reading macro name? If so, diagnostic already issued.
1425 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001426 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001427
1428 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001429 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001430
1431 // Okay, we finally have a valid identifier to undef.
1432 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1433
1434 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001435 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001436
Chris Lattner13044d92006-07-03 05:16:44 +00001437 if (!MI->isUsed())
1438 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001439
1440 // Free macro definition.
1441 delete MI;
1442 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001443}
1444
1445
Chris Lattnerb8761832006-06-24 21:31:03 +00001446//===----------------------------------------------------------------------===//
1447// Preprocessor Conditional Directive Handling.
1448//===----------------------------------------------------------------------===//
1449
Chris Lattner22eb9722006-06-18 05:43:12 +00001450/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001451/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1452/// if any tokens have been returned or pp-directives activated before this
1453/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001454///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001455void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1456 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001457 ++NumIf;
1458 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001459
Chris Lattner22eb9722006-06-18 05:43:12 +00001460 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001461 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001462
1463 // Error reading macro name? If so, diagnostic already issued.
1464 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001465 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001466
1467 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001468 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1469
1470 // If the start of a top-level #ifdef, inform MIOpt.
1471 if (!ReadAnyTokensBeforeDirective &&
1472 CurLexer->getConditionalStackDepth() == 0) {
1473 assert(isIfndef && "#ifdef shouldn't reach here");
1474 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1475 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001476
Chris Lattnera78a97e2006-07-03 05:42:18 +00001477 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1478
1479 // If there is a macro, mark it used.
1480 if (MI) MI->setIsUsed(true);
1481
Chris Lattner22eb9722006-06-18 05:43:12 +00001482 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001483 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001484 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001485 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001486 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001487 } else {
1488 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001489 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001490 /*Foundnonskip*/false,
1491 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001492 }
1493}
1494
1495/// HandleIfDirective - Implements the #if directive.
1496///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001497void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1498 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001499 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001500
Chris Lattner371ac8a2006-07-04 07:11:10 +00001501 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001502 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001503 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001504
1505 // Should we include the stuff contained by this directive?
1506 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001507 // If this condition is equivalent to #ifndef X, and if this is the first
1508 // directive seen, handle it for the multiple-include optimization.
1509 if (!ReadAnyTokensBeforeDirective &&
1510 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1511 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1512
Chris Lattner22eb9722006-06-18 05:43:12 +00001513 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001514 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001515 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001516 } else {
1517 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001518 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001519 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001520 }
1521}
1522
1523/// HandleEndifDirective - Implements the #endif directive.
1524///
Chris Lattnercb283342006-06-18 06:48:37 +00001525void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001526 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001527
Chris Lattner22eb9722006-06-18 05:43:12 +00001528 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001529 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001530
1531 PPConditionalInfo CondInfo;
1532 if (CurLexer->popConditionalLevel(CondInfo)) {
1533 // No conditionals on the stack: this is an #endif without an #if.
1534 return Diag(EndifToken, diag::err_pp_endif_without_if);
1535 }
1536
Chris Lattner371ac8a2006-07-04 07:11:10 +00001537 // If this the end of a top-level #endif, inform MIOpt.
1538 if (CurLexer->getConditionalStackDepth() == 0)
1539 CurLexer->MIOpt.ExitTopLevelConditional();
1540
Chris Lattner22eb9722006-06-18 05:43:12 +00001541 assert(!CondInfo.WasSkipping && !isSkipping() &&
1542 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001543}
1544
1545
Chris Lattnercb283342006-06-18 06:48:37 +00001546void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001547 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001548
Chris Lattner22eb9722006-06-18 05:43:12 +00001549 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001550 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001551
1552 PPConditionalInfo CI;
1553 if (CurLexer->popConditionalLevel(CI))
1554 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001555
1556 // If this is a top-level #else, inform the MIOpt.
1557 if (CurLexer->getConditionalStackDepth() == 0)
1558 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001559
1560 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001561 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001562
1563 // Finally, skip the rest of the contents of this block and return the first
1564 // token after it.
1565 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1566 /*FoundElse*/true);
1567}
1568
Chris Lattnercb283342006-06-18 06:48:37 +00001569void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001571
Chris Lattner22eb9722006-06-18 05:43:12 +00001572 // #elif directive in a non-skipping conditional... start skipping.
1573 // We don't care what the condition is, because we will always skip it (since
1574 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001575 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001576
1577 PPConditionalInfo CI;
1578 if (CurLexer->popConditionalLevel(CI))
1579 return Diag(ElifToken, diag::pp_err_elif_without_if);
1580
Chris Lattner371ac8a2006-07-04 07:11:10 +00001581 // If this is a top-level #elif, inform the MIOpt.
1582 if (CurLexer->getConditionalStackDepth() == 0)
1583 CurLexer->MIOpt.FoundTopLevelElse();
1584
Chris Lattner22eb9722006-06-18 05:43:12 +00001585 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001586 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001587
1588 // Finally, skip the rest of the contents of this block and return the first
1589 // token after it.
1590 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1591 /*FoundElse*/CI.FoundElse);
1592}
Chris Lattnerb8761832006-06-24 21:31:03 +00001593