blob: 1a95b887f3939bc31ee91b69d06fcc667f8e4b9a [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
16// -C -CC - Do not discard comments for cpp.
Chris Lattner22eb9722006-06-18 05:43:12 +000017// -d[MDNI] - Dump various things.
18// -fworking-directory - #line's with preprocessor's working dir.
19// -fpreprocessed
20// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
21// -W*
22// -w
23//
24// Messages to emit:
25// "Multiple include guards may be useful for:\n"
26//
Chris Lattner22eb9722006-06-18 05:43:12 +000027//===----------------------------------------------------------------------===//
28
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000031#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000032#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000033#include "clang/Basic/Diagnostic.h"
34#include "clang/Basic/FileManager.h"
35#include "clang/Basic/SourceManager.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000036#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000037#include <iostream>
38using namespace llvm;
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42
43Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
44 FileManager &FM, SourceManager &SM)
45 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
46 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000047 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000048 ScratchBuf = new ScratchBuffer(SourceMgr);
49
Chris Lattner22eb9722006-06-18 05:43:12 +000050 // Clear stats.
51 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
52 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000053 NumEnteredSourceFiles = 0;
54 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000055 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner3665f162006-07-04 07:26:10 +000056 MaxIncludeStackDepth = 0; NumMultiIncludeFileOptzn = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000057 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000058
Chris Lattner22eb9722006-06-18 05:43:12 +000059 // Macro expansion is enabled.
60 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000061 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000062
63 // There is no file-change handler yet.
64 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000065 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000066
Chris Lattner8ff71992006-07-06 05:17:39 +000067 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
68 // This gets unpoisoned where it is allowed.
69 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
70
Chris Lattnerb8761832006-06-24 21:31:03 +000071 // Initialize the pragma handlers.
72 PragmaHandlers = new PragmaNamespace(0);
73 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000074
75 // Initialize builtin macros like __LINE__ and friends.
76 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000077}
78
79Preprocessor::~Preprocessor() {
80 // Free any active lexers.
81 delete CurLexer;
82
Chris Lattner69772b02006-07-02 20:34:39 +000083 while (!IncludeMacroStack.empty()) {
84 delete IncludeMacroStack.back().TheLexer;
85 delete IncludeMacroStack.back().TheMacroExpander;
86 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000087 }
Chris Lattnerb8761832006-06-24 21:31:03 +000088
89 // Release pragma information.
90 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000091
92 // Delete the scratch buffer info.
93 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000094}
95
96/// getFileInfo - Return the PerFileInfo structure for the specified
97/// FileEntry.
98Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
99 if (FE->getUID() >= FileInfo.size())
100 FileInfo.resize(FE->getUID()+1);
101 return FileInfo[FE->getUID()];
102}
103
104
105/// AddKeywords - Add all keywords to the symbol table.
106///
107void Preprocessor::AddKeywords() {
108 enum {
109 C90Shift = 0,
110 EXTC90 = 1 << C90Shift,
111 NOTC90 = 2 << C90Shift,
112 C99Shift = 2,
113 EXTC99 = 1 << C99Shift,
114 NOTC99 = 2 << C99Shift,
115 CPPShift = 4,
116 EXTCPP = 1 << CPPShift,
117 NOTCPP = 2 << CPPShift,
118 Mask = 3
119 };
120
121 // Add keywords and tokens for the current language.
122#define KEYWORD(NAME, FLAGS) \
123 AddKeyword(#NAME+1, tok::kw##NAME, \
124 (FLAGS >> C90Shift) & Mask, \
125 (FLAGS >> C99Shift) & Mask, \
126 (FLAGS >> CPPShift) & Mask);
127#define ALIAS(NAME, TOK) \
128 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
129#include "clang/Basic/TokenKinds.def"
130}
131
132/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
133/// the specified LexerToken's location, translating the token's start
134/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000135void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000136 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000137 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000138}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000139
140void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
141 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
142 << getSpelling(Tok) << "'";
143
144 if (!DumpFlags) return;
145 std::cerr << "\t";
146 if (Tok.isAtStartOfLine())
147 std::cerr << " [StartOfLine]";
148 if (Tok.hasLeadingSpace())
149 std::cerr << " [LeadingSpace]";
150 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000151 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000152 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
153 << "']";
154 }
155}
156
157void Preprocessor::DumpMacro(const MacroInfo &MI) const {
158 std::cerr << "MACRO: ";
159 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
160 DumpToken(MI.getReplacementToken(i));
161 std::cerr << " ";
162 }
163 std::cerr << "\n";
164}
165
Chris Lattner22eb9722006-06-18 05:43:12 +0000166void Preprocessor::PrintStats() {
167 std::cerr << "\n*** Preprocessor Stats:\n";
168 std::cerr << FileInfo.size() << " files tracked.\n";
169 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
170 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
171 NumOnceOnlyFiles += FileInfo[i].isImport;
172 if (MaxNumIncludes < FileInfo[i].NumIncludes)
173 MaxNumIncludes = FileInfo[i].NumIncludes;
174 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
175 }
176 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
177 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
178 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
179
180 std::cerr << NumDirectives << " directives found:\n";
181 std::cerr << " " << NumDefined << " #define.\n";
182 std::cerr << " " << NumUndefined << " #undef.\n";
183 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
Chris Lattner3665f162006-07-04 07:26:10 +0000184 std::cerr << " " << NumMultiIncludeFileOptzn << " #includes skipped due to"
185 << " the multi-include optimization.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000186 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
187 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
188 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
189 std::cerr << " " << NumElse << " #else/#elif.\n";
190 std::cerr << " " << NumEndif << " #endif.\n";
191 std::cerr << " " << NumPragma << " #pragma.\n";
192 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
193
Chris Lattner78186052006-07-09 00:45:31 +0000194 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
195 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000196 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000197 std::cerr << (NumFastTokenPaste+NumTokenPaste)
198 << " token paste (##) operations performed, "
199 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000200}
201
202//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000203// Token Spelling
204//===----------------------------------------------------------------------===//
205
206
207/// getSpelling() - Return the 'spelling' of this token. The spelling of a
208/// token are the characters used to represent the token in the source file
209/// after trigraph expansion and escaped-newline folding. In particular, this
210/// wants to get the true, uncanonicalized, spelling of things like digraphs
211/// UCNs, etc.
212std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
213 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
214
215 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000216 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000217 if (!Tok.needsCleaning())
218 return std::string(TokStart, TokStart+Tok.getLength());
219
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220 std::string Result;
221 Result.reserve(Tok.getLength());
222
Chris Lattneref9eae12006-07-04 22:33:12 +0000223 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
225 Ptr != End; ) {
226 unsigned CharSize;
227 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
228 Ptr += CharSize;
229 }
230 assert(Result.size() != unsigned(Tok.getLength()) &&
231 "NeedsCleaning flag set on something that didn't need cleaning!");
232 return Result;
233}
234
235/// getSpelling - This method is used to get the spelling of a token into a
236/// preallocated buffer, instead of as an std::string. The caller is required
237/// to allocate enough space for the token, which is guaranteed to be at least
238/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000239///
240/// Note that this method may do two possible things: it may either fill in
241/// the buffer specified with characters, or it may *change the input pointer*
242/// to point to a constant buffer with the data already in it (avoiding a
243/// copy). The caller is not allowed to modify the returned buffer pointer
244/// if an internal buffer is returned.
245unsigned Preprocessor::getSpelling(const LexerToken &Tok,
246 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000247 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
248
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000249 // If this token is an identifier, just return the string from the identifier
250 // table, which is very quick.
251 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
252 Buffer = II->getName();
253 return Tok.getLength();
254 }
255
256 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000257 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000258
259 // If this token contains nothing interesting, return it directly.
260 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000261 Buffer = TokStart;
262 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000263 }
264 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000265 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000266 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
267 Ptr != End; ) {
268 unsigned CharSize;
269 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
270 Ptr += CharSize;
271 }
272 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
273 "NeedsCleaning flag set on something that didn't need cleaning!");
274
275 return OutBuf-Buffer;
276}
277
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000278
279/// CreateString - Plop the specified string into a scratch buffer and return a
280/// location for it. If specified, the source location provides a source
281/// location for the token.
282SourceLocation Preprocessor::
283CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
284 if (SLoc.isValid())
285 return ScratchBuf->getToken(Buf, Len, SLoc);
286 return ScratchBuf->getToken(Buf, Len);
287}
288
289
Chris Lattnerd01e2912006-06-18 16:22:51 +0000290//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000291// Source File Location Methods.
292//===----------------------------------------------------------------------===//
293
294
295/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
296/// return null on failure. isAngled indicates whether the file reference is
297/// for system #include's or not (i.e. using <> instead of "").
298const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000299 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000300 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000301 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000302 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000303 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000304
305 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000306 // FIXME: Portability. This should be a sys::Path interface, this doesn't
307 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000308 if (Filename[0] == '/') {
309 // If this was an #include_next "/absolute/file", fail.
310 if (FromDir) return 0;
311
312 // Otherwise, just return the file.
313 return FileMgr.getFile(Filename);
314 }
315
316 // Step #0, unless disabled, check to see if the file is in the #includer's
317 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000318 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000319 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
320 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000321 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000322 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000323 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000324 if (const FileEntry *FE =
325 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000326 if (CurDirLookup)
327 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000328 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000329 CurDir = 0;
330
331 // This file is a system header or C++ unfriendly if the old file is.
332 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000333 return FE;
334 }
335 }
336 }
337
338 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000339 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000340
341 // If this is a #include_next request, start searching after the directory the
342 // file was found in.
343 if (FromDir)
344 i = FromDir-&SearchDirs[0];
345
346 // Check each directory in sequence to see if it contains this file.
347 for (; i != SearchDirs.size(); ++i) {
348 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000349 // FIXME: Portability. Adding file to dir should be in sys::Path.
350 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
351 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000352 CurDir = &SearchDirs[i];
353
354 // This file is a system header or C++ unfriendly if the dir is.
355 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000356 return FE;
357 }
358 }
359
360 // Otherwise, didn't find it.
361 return 0;
362}
363
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000364/// isInPrimaryFile - Return true if we're in the top-level file, not in a
365/// #include.
366bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000367 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000368 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000369
Chris Lattner13044d92006-07-03 05:16:44 +0000370 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000371 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000372 if (IncludeMacroStack[i].TheLexer &&
373 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
374 return IncludeMacroStack[i].TheLexer->isMainFile();
375 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000376}
377
378/// getCurrentLexer - Return the current file lexer being lexed from. Note
379/// that this ignores any potentially active macro expansions and _Pragma
380/// expansions going on at the time.
381Lexer *Preprocessor::getCurrentFileLexer() const {
382 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
383
384 // Look for a stacked lexer.
385 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000386 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000387 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
388 return L;
389 }
390 return 0;
391}
392
393
Chris Lattner22eb9722006-06-18 05:43:12 +0000394/// EnterSourceFile - Add a source file to the top of the include stack and
395/// start lexing tokens from it instead of the current buffer. Return true
396/// on failure.
397void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000398 const DirectoryLookup *CurDir,
399 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000400 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000401 ++NumEnteredSourceFiles;
402
Chris Lattner69772b02006-07-02 20:34:39 +0000403 if (MaxIncludeStackDepth < IncludeMacroStack.size())
404 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000405
Chris Lattner22eb9722006-06-18 05:43:12 +0000406 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000407 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000408 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000409 EnterSourceFileWithLexer(TheLexer, CurDir);
410}
Chris Lattner22eb9722006-06-18 05:43:12 +0000411
Chris Lattner69772b02006-07-02 20:34:39 +0000412/// EnterSourceFile - Add a source file to the top of the include stack and
413/// start lexing tokens from it instead of the current buffer.
414void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
415 const DirectoryLookup *CurDir) {
416
417 // Add the current lexer to the include stack.
418 if (CurLexer || CurMacroExpander)
419 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
420 CurMacroExpander));
421
422 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000423 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000424 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000425
426 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000427 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000428 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
429
430 // Get the file entry for the current file.
431 if (const FileEntry *FE =
432 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
433 FileType = getFileInfo(FE).DirInfo;
434
Chris Lattner1840e492006-07-02 22:30:01 +0000435 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000436 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000437 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000438}
439
Chris Lattner69772b02006-07-02 20:34:39 +0000440
441
Chris Lattner22eb9722006-06-18 05:43:12 +0000442/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000443/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000444void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000445 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000446 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000447 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
448 CurMacroExpander));
449 CurLexer = 0;
450 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000451
Chris Lattneree8760b2006-07-15 07:42:55 +0000452 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000453}
454
Chris Lattner7667d0d2006-07-16 18:16:58 +0000455/// EnterTokenStream - Add a "macro" context to the top of the include stack,
456/// which will cause the lexer to start returning the specified tokens. Note
457/// that these tokens will be re-macro-expanded when/if expansion is enabled.
458/// This method assumes that the specified stream of tokens has a permanent
459/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000460void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000461 // Save our current state.
462 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
463 CurMacroExpander));
464 CurLexer = 0;
465 CurDirLookup = 0;
466
467 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000468 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000469}
470
471/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
472/// lexer stack. This should only be used in situations where the current
473/// state of the top-of-stack lexer is known.
474void Preprocessor::RemoveTopOfLexerStack() {
475 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
476 delete CurLexer;
477 delete CurMacroExpander;
478 CurLexer = IncludeMacroStack.back().TheLexer;
479 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
480 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
481 IncludeMacroStack.pop_back();
482}
483
Chris Lattner22eb9722006-06-18 05:43:12 +0000484//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000485// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000486//===----------------------------------------------------------------------===//
487
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000488/// RegisterBuiltinMacro - Register the specified identifier in the identifier
489/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000490IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000491 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000492 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000493
494 // Mark it as being a macro that is builtin.
495 MacroInfo *MI = new MacroInfo(SourceLocation());
496 MI->setIsBuiltinMacro();
497 Id->setMacroInfo(MI);
498 return Id;
499}
500
501
Chris Lattner677757a2006-06-28 05:26:32 +0000502/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
503/// identifier table.
504void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000505 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000506 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000507 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
508 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000509 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000510
511 // GCC Extensions.
512 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
513 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000514 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000515}
516
Chris Lattnerc2395832006-07-09 00:57:04 +0000517/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
518/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000519static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
520 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000521 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
522
523 // If the token isn't an identifier, it's always literally expanded.
524 if (II == 0) return true;
525
526 // If the identifier is a macro, and if that macro is enabled, it may be
527 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000528 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
529 // Fast expanding "#define X X" is ok, because X would be disabled.
530 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000531 return false;
532
533 // If this is an object-like macro invocation, it is safe to trivially expand
534 // it.
535 if (MI->isObjectLike()) return true;
536
537 // If this is a function-like macro invocation, it's safe to trivially expand
538 // as long as the identifier is not a macro argument.
539 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
540 I != E; ++I)
541 if (*I == II)
542 return false; // Identifier is a macro argument.
543 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000544}
545
Chris Lattnerc2395832006-07-09 00:57:04 +0000546
Chris Lattnerafe603f2006-07-11 04:02:46 +0000547/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
548/// lexed is a '('. If so, consume the token and return true, if not, this
549/// method should have no observable side-effect on the lexed tokens.
550bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000551 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000552 unsigned Val;
553 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000554 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000555 else
556 Val = CurMacroExpander->isNextTokenLParen();
557
558 if (Val == 2) {
559 // If we ran off the end of the lexer or macro expander, walk the include
560 // stack, looking for whatever will return the next token.
561 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
562 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
563 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000564 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000565 else
566 Val = Entry.TheMacroExpander->isNextTokenLParen();
567 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000568 }
569
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000570 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
571 // have found something that isn't a '(' or we found the end of the
572 // translation unit. In either case, return false.
573 if (Val != 1)
574 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000575
576 LexerToken Tok;
577 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000578 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
579 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000580}
Chris Lattner677757a2006-06-28 05:26:32 +0000581
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000582/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
583/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000584bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000585 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000586
587 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
588 if (MI->isBuiltinMacro()) {
589 ExpandBuiltinMacro(Identifier);
590 return false;
591 }
592
Chris Lattneree8760b2006-07-15 07:42:55 +0000593 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000594 /// for each macro argument, the list of tokens that were provided to the
595 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000596 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000597
598 // If this is a function-like macro, read the arguments.
599 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000600 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
601 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000602 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000603 return true;
604
Chris Lattner78186052006-07-09 00:45:31 +0000605 // Remember that we are now parsing the arguments to a macro invocation.
606 // Preprocessor directives used inside macro arguments are not portable, and
607 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000608 InMacroArgs = true;
609 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000610
611 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000612 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000613
614 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000615 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000616
617 ++NumFnMacroExpanded;
618 } else {
619 ++NumMacroExpanded;
620 }
Chris Lattner13044d92006-07-03 05:16:44 +0000621
622 // Notice that this macro has been used.
623 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000624
625 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000626
627 // If this macro expands to no tokens, don't bother to push it onto the
628 // expansion stack, only to take it right back off.
629 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000630 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000631 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000632
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000633 // Ignore this macro use, just return the next token in the current
634 // buffer.
635 bool HadLeadingSpace = Identifier.hasLeadingSpace();
636 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
637
638 Lex(Identifier);
639
640 // If the identifier isn't on some OTHER line, inherit the leading
641 // whitespace/first-on-a-line property of this token. This handles
642 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
643 // empty.
644 if (!Identifier.isAtStartOfLine()) {
645 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
646 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
647 }
648 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000649 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000650
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000651 } else if (MI->getNumTokens() == 1 &&
652 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000653 // Otherwise, if this macro expands into a single trivially-expanded
654 // token: expand it now. This handles common cases like
655 // "#define VAL 42".
656
657 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
658 // identifier to the expanded token.
659 bool isAtStartOfLine = Identifier.isAtStartOfLine();
660 bool hasLeadingSpace = Identifier.hasLeadingSpace();
661
662 // Remember where the token is instantiated.
663 SourceLocation InstantiateLoc = Identifier.getLocation();
664
665 // Replace the result token.
666 Identifier = MI->getReplacementToken(0);
667
668 // Restore the StartOfLine/LeadingSpace markers.
669 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
670 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
671
672 // Update the tokens location to include both its logical and physical
673 // locations.
674 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000675 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000676 Identifier.SetLocation(Loc);
677
678 // Since this is not an identifier token, it can't be macro expanded, so
679 // we're done.
680 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000681 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000682 }
683
Chris Lattner78186052006-07-09 00:45:31 +0000684 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000685 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000686
687 // Now that the macro is at the top of the include stack, ask the
688 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000689 Lex(Identifier);
690 return false;
691}
692
Chris Lattneree8760b2006-07-15 07:42:55 +0000693/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000694/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000695/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000696MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
697 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000698 // The number of fixed arguments to parse.
699 unsigned NumFixedArgsLeft = MI->getNumArgs();
700 bool isVariadic = MI->isVariadic();
701
702 // If this is a C99-style varargs macro invocation, add an extra expected
Chris Lattner2ada5d32006-07-15 07:51:24 +0000703 // argument, which will catch all of the vararg args in one argument.
Chris Lattner78186052006-07-09 00:45:31 +0000704 if (MI->isC99Varargs())
705 ++NumFixedArgsLeft;
706
707 // Outer loop, while there are more arguments, keep reading them.
708 LexerToken Tok;
709 Tok.SetKind(tok::comma);
710 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000711
712 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000713 // argument is separated by an EOF token. Use a SmallVector so we can avoid
714 // heap allocations in the common case.
715 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000716
717 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000718 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000719 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
720 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000721
Chris Lattner78186052006-07-09 00:45:31 +0000722 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000723 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
724 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000725 LexUnexpandedToken(Tok);
726
727 if (Tok.getKind() == tok::eof) {
728 Diag(MacroName, diag::err_unterm_macro_invoc);
729 // Do not lose the EOF. Return it to the client.
730 MacroName = Tok;
731 return 0;
732 } else if (Tok.getKind() == tok::r_paren) {
733 // If we found the ) token, the macro arg list is done.
734 if (NumParens-- == 0)
735 break;
736 } else if (Tok.getKind() == tok::l_paren) {
737 ++NumParens;
738 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
739 // Comma ends this argument if there are more fixed arguments expected.
740 if (NumFixedArgsLeft)
741 break;
742
Chris Lattner2ada5d32006-07-15 07:51:24 +0000743 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000744 if (!isVariadic) {
745 // Emit the diagnostic at the macro name in case there is a missing ).
746 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000747 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000748 return 0;
749 }
750 // Otherwise, continue to add the tokens to this variable argument.
751 }
752
753 ArgTokens.push_back(Tok);
754 }
755
Chris Lattnera12dd152006-07-11 04:09:02 +0000756 // Empty arguments are standard in C99 and supported as an extension in
757 // other modes.
758 if (ArgTokens.empty() && !Features.C99)
759 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000760
Chris Lattner36b6e812006-07-21 06:38:30 +0000761 // Add a marker EOF token to the end of the token list for this argument.
762 LexerToken EOFTok;
763 EOFTok.StartToken();
764 EOFTok.SetKind(tok::eof);
765 EOFTok.SetLocation(Tok.getLocation());
766 EOFTok.SetLength(0);
767 ArgTokens.push_back(EOFTok);
768 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000769 --NumFixedArgsLeft;
770 };
771
772 // Okay, we either found the r_paren. Check to see if we parsed too few
773 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000774 unsigned MinArgsExpected = MI->getNumArgs();
775
776 // C99 expects us to pass at least one vararg arg (but as an extension, we
Chris Lattnerc2395832006-07-09 00:57:04 +0000777 // don't require this). GNU-style varargs already include the 'rest' name in
778 // the count.
779 MinArgsExpected += MI->isC99Varargs();
Chris Lattner78186052006-07-09 00:45:31 +0000780
Chris Lattner2ada5d32006-07-15 07:51:24 +0000781 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000782 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000783 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000784 // Varargs where the named vararg parameter is missing: ok as extension.
785 // #define A(x, ...)
786 // A("blah")
787 Diag(Tok, diag::ext_missing_varargs_arg);
788 } else if (MI->getNumArgs() == 1) {
789 // #define A(x)
790 // A()
Chris Lattnerafe603f2006-07-11 04:02:46 +0000791 // is ok because it is an empty argument. Add it explicitly.
Chris Lattner36b6e812006-07-21 06:38:30 +0000792
793
794 // Add a marker EOF token to the end of the token list for this argument.
795 SourceLocation EndLoc = Tok.getLocation();
796 Tok.StartToken();
797 Tok.SetKind(tok::eof);
798 Tok.SetLocation(EndLoc);
799 Tok.SetLength(0);
800 ArgTokens.push_back(Tok);
Chris Lattnera12dd152006-07-11 04:09:02 +0000801
802 // Empty arguments are standard in C99 and supported as an extension in
803 // other modes.
804 if (ArgTokens.empty() && !Features.C99)
805 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000806 } else {
807 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000808 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000809 return 0;
810 }
811 }
812
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000813 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size());
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000814}
815
Chris Lattnerc673f902006-06-30 06:10:41 +0000816/// ComputeDATE_TIME - Compute the current time, enter it into the specified
817/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
818/// the identifier tokens inserted.
819static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000820 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000821 time_t TT = time(0);
822 struct tm *TM = localtime(&TT);
823
824 static const char * const Months[] = {
825 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
826 };
827
828 char TmpBuffer[100];
829 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
830 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000831 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000832
833 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000834 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000835}
836
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000837/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
838/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000839void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000840 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000841 IdentifierInfo *II = Tok.getIdentifierInfo();
842 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000843
844 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
845 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000846 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000847 return Handle_Pragma(Tok);
848
Chris Lattner78186052006-07-09 00:45:31 +0000849 ++NumBuiltinMacroExpanded;
850
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000851 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000852
853 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000854 Tok.SetIdentifierInfo(0);
855 Tok.ClearFlag(LexerToken::NeedsCleaning);
856
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000857 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000858 // __LINE__ expands to a simple numeric value.
859 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
860 unsigned Length = strlen(TmpBuffer);
861 Tok.SetKind(tok::numeric_constant);
862 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000863 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000864 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000865 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000866 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000867 Diag(Tok, diag::ext_pp_base_file);
868 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
869 while (NextLoc.getFileID() != 0) {
870 Loc = NextLoc;
871 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
872 }
873 }
874
Chris Lattner0766e592006-07-03 01:07:01 +0000875 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
876 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000877 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner630b33c2006-07-01 22:46:53 +0000878 Tok.SetKind(tok::string_literal);
879 Tok.SetLength(FN.size());
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000880 Tok.SetLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000881 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000882 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000883 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000884 Tok.SetKind(tok::string_literal);
885 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
886 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000887 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000888 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000889 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000890 Tok.SetKind(tok::string_literal);
891 Tok.SetLength(strlen("\"hh:mm:ss\""));
892 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000893 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000894 Diag(Tok, diag::ext_pp_include_level);
895
896 // Compute the include depth of this token.
897 unsigned Depth = 0;
898 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
899 for (; Loc.getFileID() != 0; ++Depth)
900 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
901
902 // __INCLUDE_LEVEL__ expands to a simple numeric value.
903 sprintf(TmpBuffer, "%u", Depth);
904 unsigned Length = strlen(TmpBuffer);
905 Tok.SetKind(tok::numeric_constant);
906 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000907 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000908 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000909 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
910 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
911 Diag(Tok, diag::ext_pp_timestamp);
912
913 // Get the file that we are lexing out of. If we're currently lexing from
914 // a macro, dig into the include stack.
915 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000916 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000917
918 if (TheLexer)
919 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
920
921 // If this file is older than the file it depends on, emit a diagnostic.
922 const char *Result;
923 if (CurFile) {
924 time_t TT = CurFile->getModificationTime();
925 struct tm *TM = localtime(&TT);
926 Result = asctime(TM);
927 } else {
928 Result = "??? ??? ?? ??:??:?? ????\n";
929 }
930 TmpBuffer[0] = '"';
931 strcpy(TmpBuffer+1, Result);
932 unsigned Len = strlen(TmpBuffer);
933 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
934 Tok.SetKind(tok::string_literal);
935 Tok.SetLength(Len);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000936 Tok.SetLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000937 } else {
938 assert(0 && "Unknown identifier!");
939 }
940}
Chris Lattner677757a2006-06-28 05:26:32 +0000941
Chris Lattner13044d92006-07-03 05:16:44 +0000942namespace {
943struct UnusedIdentifierReporter : public IdentifierVisitor {
944 Preprocessor &PP;
945 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
946
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000947 void VisitIdentifier(IdentifierInfo &II) const {
948 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
949 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000950 }
951};
952}
953
Chris Lattner677757a2006-06-28 05:26:32 +0000954//===----------------------------------------------------------------------===//
955// Lexer Event Handling.
956//===----------------------------------------------------------------------===//
957
Chris Lattnercefc7682006-07-08 08:28:12 +0000958/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
959/// identifier information for the token and install it into the token.
960IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
961 const char *BufPtr) {
962 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
963 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
964
965 // Look up this token, see if it is a macro, or if it is a language keyword.
966 IdentifierInfo *II;
967 if (BufPtr && !Identifier.needsCleaning()) {
968 // No cleaning needed, just use the characters from the lexed buffer.
969 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
970 } else {
971 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
972 const char *TmpBuf = (char*)alloca(Identifier.getLength());
973 unsigned Size = getSpelling(Identifier, TmpBuf);
974 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
975 }
976 Identifier.SetIdentifierInfo(II);
977 return II;
978}
979
980
Chris Lattner677757a2006-06-28 05:26:32 +0000981/// HandleIdentifier - This callback is invoked when the lexer reads an
982/// identifier. This callback looks up the identifier in the map and/or
983/// potentially macro expands it or turns it into a named token (like 'for').
984void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000985 assert(Identifier.getIdentifierInfo() &&
986 "Can't handle identifiers without identifier info!");
987
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000988 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000989
990 // If this identifier was poisoned, and if it was not produced from a macro
991 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000992 if (II.isPoisoned() && CurLexer) {
993 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
994 Diag(Identifier, diag::err_pp_used_poisoned_id);
995 else
996 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
997 }
Chris Lattner677757a2006-06-28 05:26:32 +0000998
Chris Lattner78186052006-07-09 00:45:31 +0000999 // If this is a macro to be expanded, do it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001000 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +00001001 if (MI->isEnabled() && !DisableMacroExpansion)
Chris Lattner78186052006-07-09 00:45:31 +00001002 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1003 return;
Chris Lattner677757a2006-06-28 05:26:32 +00001004
1005 // Change the kind of this identifier to the appropriate token kind, e.g.
1006 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001007 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001008
1009 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001010 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001011}
1012
Chris Lattner22eb9722006-06-18 05:43:12 +00001013/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1014/// the current file. This either returns the EOF token or pops a level off
1015/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001016bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001017 assert(!CurMacroExpander &&
1018 "Ending a file when currently in a macro!");
1019
Chris Lattner371ac8a2006-07-04 07:11:10 +00001020 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001021 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001022 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001023 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001024 // Okay, this has a controlling macro, remember in PerFileInfo.
1025 if (const FileEntry *FE =
1026 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1027 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001028 }
1029 }
1030
Chris Lattner22eb9722006-06-18 05:43:12 +00001031 // If this is a #include'd file, pop it off the include stack and continue
1032 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001033 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001034 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001035 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001036
1037 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001038 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001039 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1040
1041 // Get the file entry for the current file.
1042 if (const FileEntry *FE =
1043 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1044 FileType = getFileInfo(FE).DirInfo;
1045
Chris Lattner0c885f52006-06-21 06:50:18 +00001046 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001047 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001048 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001049
1050 // Client should lex another token.
1051 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001052 }
1053
Chris Lattnerd01e2912006-06-18 16:22:51 +00001054 Result.StartToken();
1055 CurLexer->BufferPtr = CurLexer->BufferEnd;
1056 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001057 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001058
1059 // We're done with the #included file.
1060 delete CurLexer;
1061 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001062
Chris Lattner03f83482006-07-10 06:16:26 +00001063 // This is the end of the top-level file. If the diag::pp_macro_not_used
1064 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1065 // have not been used.
1066 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1067 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001068
1069 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001070}
1071
1072/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001073/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001074bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001075 assert(CurMacroExpander && !CurLexer &&
1076 "Ending a macro when currently in a #include file!");
1077
Chris Lattner22eb9722006-06-18 05:43:12 +00001078 delete CurMacroExpander;
1079
Chris Lattner69772b02006-07-02 20:34:39 +00001080 // Handle this like a #include file being popped off the stack.
1081 CurMacroExpander = 0;
1082 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001083}
1084
1085
1086//===----------------------------------------------------------------------===//
1087// Utility Methods for Preprocessor Directive Handling.
1088//===----------------------------------------------------------------------===//
1089
1090/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1091/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001092void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001093 LexerToken Tmp;
1094 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001095 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001096 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001097}
1098
1099/// ReadMacroName - Lex and validate a macro name, which occurs after a
1100/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001101/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1102/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001103/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001104void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001105 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001106 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001107
1108 // Missing macro name?
1109 if (MacroNameTok.getKind() == tok::eom)
1110 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1111
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001112 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1113 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001114 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001115 // Fall through on error.
1116 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001117 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001118
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001119 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1120 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001121 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001122 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001123 } else if (isDefineUndef && II->getMacroInfo() &&
1124 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001125 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001126 if (isDefineUndef == 1)
1127 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1128 else
1129 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001130 } else {
1131 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001132 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001133 }
1134
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 // Invalid macro name, read and discard the rest of the line. Then set the
1136 // token kind to tok::eom.
1137 MacroNameTok.SetKind(tok::eom);
1138 return DiscardUntilEndOfDirective();
1139}
1140
1141/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1142/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001143void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001144 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001145 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001146 // There should be no tokens after the directive, but we allow them as an
1147 // extension.
1148 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001149 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1150 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001151 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001152}
1153
1154
1155
1156/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1157/// decided that the subsequent tokens are in the #if'd out portion of the
1158/// file. Lex the rest of the file, until we see an #endif. If
1159/// FoundNonSkipPortion is true, then we have already emitted code for part of
1160/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1161/// is true, then #else directives are ok, if not, then we have already seen one
1162/// so a #else directive is a duplicate. When this returns, the caller can lex
1163/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001164void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001165 bool FoundNonSkipPortion,
1166 bool FoundElse) {
1167 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001168 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001169 "Lexing a macro, not a file?");
1170
1171 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1172 FoundNonSkipPortion, FoundElse);
1173
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001174 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1175 // disabling warnings, etc.
1176 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001177 LexerToken Tok;
1178 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001179 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001180
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001181 // If this is the end of the buffer, we have an error.
1182 if (Tok.getKind() == tok::eof) {
1183 // Emit errors for each unterminated conditional on the stack, including
1184 // the current one.
1185 while (!CurLexer->ConditionalStack.empty()) {
1186 Diag(CurLexer->ConditionalStack.back().IfLoc,
1187 diag::err_pp_unterminated_conditional);
1188 CurLexer->ConditionalStack.pop_back();
1189 }
1190
1191 // Just return and let the caller lex after this #include.
1192 break;
1193 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001194
1195 // If this token is not a preprocessor directive, just skip it.
1196 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1197 continue;
1198
1199 // We just parsed a # character at the start of a line, so we're in
1200 // directive mode. Tell the lexer this so any newlines we see will be
1201 // converted into an EOM token (this terminates the macro).
1202 CurLexer->ParsingPreprocessorDirective = true;
1203
1204 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001205 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001206
1207 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1208 // something bogus), skip it.
1209 if (Tok.getKind() != tok::identifier) {
1210 CurLexer->ParsingPreprocessorDirective = false;
1211 continue;
1212 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001213
Chris Lattner22eb9722006-06-18 05:43:12 +00001214 // If the first letter isn't i or e, it isn't intesting to us. We know that
1215 // this is safe in the face of spelling differences, because there is no way
1216 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001217 // allows us to avoid looking up the identifier info for #define/#undef and
1218 // other common directives.
1219 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1220 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001221 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1222 FirstChar != 'i' && FirstChar != 'e') {
1223 CurLexer->ParsingPreprocessorDirective = false;
1224 continue;
1225 }
1226
Chris Lattnere60165f2006-06-22 06:36:29 +00001227 // Get the identifier name without trigraphs or embedded newlines. Note
1228 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1229 // when skipping.
1230 // TODO: could do this with zero copies in the no-clean case by using
1231 // strncmp below.
1232 char Directive[20];
1233 unsigned IdLen;
1234 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1235 IdLen = Tok.getLength();
1236 memcpy(Directive, RawCharData, IdLen);
1237 Directive[IdLen] = 0;
1238 } else {
1239 std::string DirectiveStr = getSpelling(Tok);
1240 IdLen = DirectiveStr.size();
1241 if (IdLen >= 20) {
1242 CurLexer->ParsingPreprocessorDirective = false;
1243 continue;
1244 }
1245 memcpy(Directive, &DirectiveStr[0], IdLen);
1246 Directive[IdLen] = 0;
1247 }
1248
Chris Lattner22eb9722006-06-18 05:43:12 +00001249 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001250 if ((IdLen == 2) || // "if"
1251 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1252 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001253 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1254 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001255 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001256 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001257 /*foundnonskip*/false,
1258 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001259 }
1260 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001261 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001262 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001263 PPConditionalInfo CondInfo;
1264 CondInfo.WasSkipping = true; // Silence bogus warning.
1265 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1266 assert(!InCond && "Can't be skipping if not in a conditional!");
1267
1268 // If we popped the outermost skipping block, we're done skipping!
1269 if (!CondInfo.WasSkipping)
1270 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001271 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001272 // #else directive in a skipping conditional. If not in some other
1273 // skipping conditional, and if #else hasn't already been seen, enter it
1274 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001275 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001276 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1277
1278 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001279 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001280
1281 // Note that we've seen a #else in this conditional.
1282 CondInfo.FoundElse = true;
1283
1284 // If the conditional is at the top level, and the #if block wasn't
1285 // entered, enter the #else block now.
1286 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1287 CondInfo.FoundNonSkip = true;
1288 break;
1289 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001290 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001291 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1292
1293 bool ShouldEnter;
1294 // If this is in a skipping block or if we're already handled this #if
1295 // block, don't bother parsing the condition.
1296 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001297 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001298 ShouldEnter = false;
1299 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001300 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001301 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001302 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1303 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001304 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001305 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001306 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001307 }
1308
1309 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001310 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001311
1312 // If this condition is true, enter it!
1313 if (ShouldEnter) {
1314 CondInfo.FoundNonSkip = true;
1315 break;
1316 }
1317 }
1318 }
1319
1320 CurLexer->ParsingPreprocessorDirective = false;
1321 }
1322
1323 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1324 // of the file, just stop skipping and return to lexing whatever came after
1325 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001326 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001327}
1328
1329//===----------------------------------------------------------------------===//
1330// Preprocessor Directive Handling.
1331//===----------------------------------------------------------------------===//
1332
1333/// HandleDirective - This callback is invoked when the lexer sees a # token
1334/// at the start of a line. This consumes the directive, modifies the
1335/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1336/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001337void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001338 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001339
1340 // We just parsed a # character at the start of a line, so we're in directive
1341 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001342 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001343 CurLexer->ParsingPreprocessorDirective = true;
1344
1345 ++NumDirectives;
1346
Chris Lattner371ac8a2006-07-04 07:11:10 +00001347 // We are about to read a token. For the multiple-include optimization FA to
1348 // work, we have to remember if we had read any tokens *before* this
1349 // pp-directive.
1350 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1351
Chris Lattner78186052006-07-09 00:45:31 +00001352 // Read the next token, the directive flavor. This isn't expanded due to
1353 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001354 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001355
Chris Lattner78186052006-07-09 00:45:31 +00001356 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1357 // #define A(x) #x
1358 // A(abc
1359 // #warning blah
1360 // def)
1361 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001362 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001363 Diag(Result, diag::ext_embedded_directive);
1364
Chris Lattner22eb9722006-06-18 05:43:12 +00001365 switch (Result.getKind()) {
1366 default: break;
1367 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001368 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001369
1370#if 0
1371 case tok::numeric_constant:
1372 // FIXME: implement # 7 line numbers!
1373 break;
1374#endif
1375 case tok::kw_else:
1376 return HandleElseDirective(Result);
1377 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001378 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001379 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001380 // Get the identifier name without trigraphs or embedded newlines.
1381 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001382 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001383 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001384 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001385 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001386 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001387 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001388 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001389 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1390 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001391 break;
1392 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001393 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001394 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001395 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001396 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001397 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001398 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001399 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001400 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001401 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001402 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001403 break;
1404 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001405 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001406 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001407 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001408 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001409 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001410 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001411 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001412 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001413 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1414 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001415 break;
1416 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001417 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1418 return HandleIncludeDirective(Result); // Handle #include.
1419 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001420 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001421 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001422 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001423 break;
1424 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001425 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001426 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001427 }
1428 break;
1429 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001430 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1431 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001432 break;
1433 }
1434 break;
1435 }
1436
1437 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001438 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001439
1440 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001441 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001442
1443 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001444}
1445
Chris Lattner01d66cc2006-07-03 22:16:27 +00001446void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001447 bool isWarning) {
1448 // Read the rest of the line raw. We do this because we don't want macros
1449 // to be expanded and we don't require that the tokens be valid preprocessing
1450 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1451 // collapse multiple consequtive white space between tokens, but this isn't
1452 // specified by the standard.
1453 std::string Message = CurLexer->ReadToEndOfLine();
1454
1455 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001456 return Diag(Tok, DiagID, Message);
1457}
1458
1459/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1460///
1461void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001462 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001463 Diag(Tok, diag::ext_pp_ident_directive);
1464
Chris Lattner371ac8a2006-07-04 07:11:10 +00001465 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001466 LexerToken StrTok;
1467 Lex(StrTok);
1468
1469 // If the token kind isn't a string, it's a malformed directive.
1470 if (StrTok.getKind() != tok::string_literal)
1471 return Diag(StrTok, diag::err_pp_malformed_ident);
1472
1473 // Verify that there is nothing after the string, other than EOM.
1474 CheckEndOfDirective("#ident");
1475
1476 if (IdentHandler)
1477 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001478}
1479
Chris Lattnerb8761832006-06-24 21:31:03 +00001480//===----------------------------------------------------------------------===//
1481// Preprocessor Include Directive Handling.
1482//===----------------------------------------------------------------------===//
1483
Chris Lattner22eb9722006-06-18 05:43:12 +00001484/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1485/// file to be included from the lexer, then include it! This is a common
1486/// routine with functionality shared between #include, #include_next and
1487/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001488void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001489 const DirectoryLookup *LookupFrom,
1490 bool isImport) {
1491 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001492
Chris Lattner22eb9722006-06-18 05:43:12 +00001493 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001494 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001495
1496 // If the token kind is EOM, the error has already been diagnosed.
1497 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001498 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001499
1500 // Verify that there is nothing after the filename, other than EOM. Use the
1501 // preprocessor to lex this in case lexing the filename entered a macro.
1502 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001503
1504 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001505 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001506 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1507
Chris Lattner269c2322006-06-25 06:23:00 +00001508 // Find out whether the filename is <x> or "x".
1509 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001510
1511 // Remove the quotes.
1512 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1513
Chris Lattner22eb9722006-06-18 05:43:12 +00001514 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001515 const DirectoryLookup *CurDir;
1516 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001517 if (File == 0)
1518 return Diag(FilenameTok, diag::err_pp_file_not_found);
1519
1520 // Get information about this file.
1521 PerFileInfo &FileInfo = getFileInfo(File);
1522
1523 // If this is a #import directive, check that we have not already imported
1524 // this header.
1525 if (isImport) {
1526 // If this has already been imported, don't import it again.
1527 FileInfo.isImport = true;
1528
1529 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001530 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001531 } else {
1532 // Otherwise, if this is a #include of a file that was previously #import'd
1533 // or if this is the second #include of a #pragma once file, ignore it.
1534 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001535 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001536 }
Chris Lattner3665f162006-07-04 07:26:10 +00001537
1538 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1539 // if the macro that guards it is defined, we know the #include has no effect.
1540 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1541 ++NumMultiIncludeFileOptzn;
1542 return;
1543 }
1544
Chris Lattner22eb9722006-06-18 05:43:12 +00001545
1546 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001547 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001548 if (FileID == 0)
1549 return Diag(FilenameTok, diag::err_pp_file_not_found);
1550
1551 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001552 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001553
1554 // Increment the number of times this file has been included.
1555 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001556}
1557
1558/// HandleIncludeNextDirective - Implements #include_next.
1559///
Chris Lattnercb283342006-06-18 06:48:37 +00001560void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1561 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001562
1563 // #include_next is like #include, except that we start searching after
1564 // the current found directory. If we can't do this, issue a
1565 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001566 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001567 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001568 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001569 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001571 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001572 } else {
1573 // Start looking up in the next directory.
1574 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001575 }
1576
1577 return HandleIncludeDirective(IncludeNextTok, Lookup);
1578}
1579
1580/// HandleImportDirective - Implements #import.
1581///
Chris Lattnercb283342006-06-18 06:48:37 +00001582void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1583 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001584
1585 return HandleIncludeDirective(ImportTok, 0, true);
1586}
1587
Chris Lattnerb8761832006-06-24 21:31:03 +00001588//===----------------------------------------------------------------------===//
1589// Preprocessor Macro Directive Handling.
1590//===----------------------------------------------------------------------===//
1591
Chris Lattnercefc7682006-07-08 08:28:12 +00001592/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1593/// definition has just been read. Lex the rest of the arguments and the
1594/// closing ), updating MI with what we learn. Return true if an error occurs
1595/// parsing the arg list.
1596bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1597 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001598 while (1) {
1599 LexUnexpandedToken(Tok);
1600 switch (Tok.getKind()) {
1601 case tok::r_paren:
1602 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001603 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001604 // Otherwise we have #define FOO(A,)
1605 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1606 return true;
1607 case tok::ellipsis: // #define X(... -> C99 varargs
1608 // Warn if use of C99 feature in non-C99 mode.
1609 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1610
1611 // Lex the token after the identifier.
1612 LexUnexpandedToken(Tok);
1613 if (Tok.getKind() != tok::r_paren) {
1614 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1615 return true;
1616 }
1617 MI->setIsC99Varargs();
1618 return false;
1619 case tok::eom: // #define X(
1620 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1621 return true;
1622 default: // #define X(1
1623 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1624 return true;
1625 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001626 IdentifierInfo *II = Tok.getIdentifierInfo();
1627
1628 // If this is already used as an argument, it is used multiple times (e.g.
1629 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001630 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001631 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1632 return true;
1633 }
1634
1635 // Add the argument to the macro info.
1636 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001637
1638 // Lex the token after the identifier.
1639 LexUnexpandedToken(Tok);
1640
1641 switch (Tok.getKind()) {
1642 default: // #define X(A B
1643 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1644 return true;
1645 case tok::r_paren: // #define X(A)
1646 return false;
1647 case tok::comma: // #define X(A,
1648 break;
1649 case tok::ellipsis: // #define X(A... -> GCC extension
1650 // Diagnose extension.
1651 Diag(Tok, diag::ext_named_variadic_macro);
1652
1653 // Lex the token after the identifier.
1654 LexUnexpandedToken(Tok);
1655 if (Tok.getKind() != tok::r_paren) {
1656 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1657 return true;
1658 }
1659
1660 MI->setIsGNUVarargs();
1661 return false;
1662 }
1663 }
1664 }
1665}
1666
Chris Lattner22eb9722006-06-18 05:43:12 +00001667/// HandleDefineDirective - Implements #define. This consumes the entire macro
1668/// line then lets the caller lex the next real token.
1669///
Chris Lattnercb283342006-06-18 06:48:37 +00001670void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001671 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001672
Chris Lattner22eb9722006-06-18 05:43:12 +00001673 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001674 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001675
1676 // Error reading macro name? If so, diagnostic already issued.
1677 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001678 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001679
Chris Lattner50b497e2006-06-18 16:32:35 +00001680 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001681
1682 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001683 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001684
Chris Lattner78186052006-07-09 00:45:31 +00001685 // FIXME: Enable __VA_ARGS__.
1686
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001687 // If this is a function-like macro definition, parse the argument list,
1688 // marking each of the identifiers as being used as macro arguments. Also,
1689 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001690 if (Tok.getKind() == tok::eom) {
1691 // If there is no body to this macro, we have no special handling here.
1692 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001693 // This is a function-like macro definition. Read the argument list.
1694 MI->setIsFunctionLike();
1695 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001696 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001697 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001698 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001699 if (CurLexer->ParsingPreprocessorDirective)
1700 DiscardUntilEndOfDirective();
1701 return;
1702 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001703
Chris Lattner815a1f92006-07-08 20:48:04 +00001704 // Read the first token after the arg list for down below.
1705 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001706 } else if (!Tok.hasLeadingSpace()) {
1707 // C99 requires whitespace between the macro definition and the body. Emit
1708 // a diagnostic for something like "#define X+".
1709 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001710 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001711 } else {
1712 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1713 // one in some cases!
1714 }
1715 } else {
1716 // This is a normal token with leading space. Clear the leading space
1717 // marker on the first token to get proper expansion.
1718 Tok.ClearFlag(LexerToken::LeadingSpace);
1719 }
1720
1721 // Read the rest of the macro body.
1722 while (Tok.getKind() != tok::eom) {
1723 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001724
1725 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001726 // parameters in function-like macro expansions.
1727 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001728 // Get the next token of the macro.
1729 LexUnexpandedToken(Tok);
1730 continue;
1731 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001732
Chris Lattner815a1f92006-07-08 20:48:04 +00001733 // Get the next token of the macro.
1734 LexUnexpandedToken(Tok);
1735
1736 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001737 if (!Tok.getIdentifierInfo() ||
1738 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001739 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001740 delete MI;
1741 return;
1742 }
1743
1744 // Things look ok, add the param name token to the macro.
1745 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001746
Chris Lattner22eb9722006-06-18 05:43:12 +00001747 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001748 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001749 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001750
Chris Lattnerbff18d52006-07-06 04:49:18 +00001751 // Check that there is no paste (##) operator at the begining or end of the
1752 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001753 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001754 if (NumTokens != 0) {
1755 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001756 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001757 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001758 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001759 }
1760 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001761 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001762 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001763 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001764 }
1765 }
1766
Chris Lattner13044d92006-07-03 05:16:44 +00001767 // If this is the primary source file, remember that this macro hasn't been
1768 // used yet.
1769 if (isInPrimaryFile())
1770 MI->setIsUsed(false);
1771
Chris Lattner22eb9722006-06-18 05:43:12 +00001772 // Finally, if this identifier already had a macro defined for it, verify that
1773 // the macro bodies are identical and free the old definition.
1774 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001775 if (!OtherMI->isUsed())
1776 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1777
Chris Lattner22eb9722006-06-18 05:43:12 +00001778 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001779 // must be the same. C99 6.10.3.2.
1780 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001781 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1782 MacroNameTok.getIdentifierInfo()->getName());
1783 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1784 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001785 delete OtherMI;
1786 }
1787
1788 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001789}
1790
1791
1792/// HandleUndefDirective - Implements #undef.
1793///
Chris Lattnercb283342006-06-18 06:48:37 +00001794void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001795 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001796
Chris Lattner22eb9722006-06-18 05:43:12 +00001797 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001798 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001799
1800 // Error reading macro name? If so, diagnostic already issued.
1801 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001802 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001803
1804 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001805 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001806
1807 // Okay, we finally have a valid identifier to undef.
1808 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1809
1810 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001811 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001812
Chris Lattner13044d92006-07-03 05:16:44 +00001813 if (!MI->isUsed())
1814 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001815
1816 // Free macro definition.
1817 delete MI;
1818 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001819}
1820
1821
Chris Lattnerb8761832006-06-24 21:31:03 +00001822//===----------------------------------------------------------------------===//
1823// Preprocessor Conditional Directive Handling.
1824//===----------------------------------------------------------------------===//
1825
Chris Lattner22eb9722006-06-18 05:43:12 +00001826/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001827/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1828/// if any tokens have been returned or pp-directives activated before this
1829/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001830///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001831void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1832 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001833 ++NumIf;
1834 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001835
Chris Lattner22eb9722006-06-18 05:43:12 +00001836 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001837 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001838
1839 // Error reading macro name? If so, diagnostic already issued.
1840 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001841 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001842
1843 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001844 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1845
1846 // If the start of a top-level #ifdef, inform MIOpt.
1847 if (!ReadAnyTokensBeforeDirective &&
1848 CurLexer->getConditionalStackDepth() == 0) {
1849 assert(isIfndef && "#ifdef shouldn't reach here");
1850 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1851 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001852
Chris Lattnera78a97e2006-07-03 05:42:18 +00001853 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1854
1855 // If there is a macro, mark it used.
1856 if (MI) MI->setIsUsed(true);
1857
Chris Lattner22eb9722006-06-18 05:43:12 +00001858 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001859 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001860 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001861 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001862 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001863 } else {
1864 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001865 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001866 /*Foundnonskip*/false,
1867 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001868 }
1869}
1870
1871/// HandleIfDirective - Implements the #if directive.
1872///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001873void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1874 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001875 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001876
Chris Lattner371ac8a2006-07-04 07:11:10 +00001877 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001878 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001879 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001880
1881 // Should we include the stuff contained by this directive?
1882 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001883 // If this condition is equivalent to #ifndef X, and if this is the first
1884 // directive seen, handle it for the multiple-include optimization.
1885 if (!ReadAnyTokensBeforeDirective &&
1886 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1887 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1888
Chris Lattner22eb9722006-06-18 05:43:12 +00001889 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001890 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001891 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001892 } else {
1893 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001894 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001895 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001896 }
1897}
1898
1899/// HandleEndifDirective - Implements the #endif directive.
1900///
Chris Lattnercb283342006-06-18 06:48:37 +00001901void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001902 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001903
Chris Lattner22eb9722006-06-18 05:43:12 +00001904 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001905 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001906
1907 PPConditionalInfo CondInfo;
1908 if (CurLexer->popConditionalLevel(CondInfo)) {
1909 // No conditionals on the stack: this is an #endif without an #if.
1910 return Diag(EndifToken, diag::err_pp_endif_without_if);
1911 }
1912
Chris Lattner371ac8a2006-07-04 07:11:10 +00001913 // If this the end of a top-level #endif, inform MIOpt.
1914 if (CurLexer->getConditionalStackDepth() == 0)
1915 CurLexer->MIOpt.ExitTopLevelConditional();
1916
Chris Lattner538d7f32006-07-20 04:31:52 +00001917 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001918 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001919}
1920
1921
Chris Lattnercb283342006-06-18 06:48:37 +00001922void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001923 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001924
Chris Lattner22eb9722006-06-18 05:43:12 +00001925 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001926 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001927
1928 PPConditionalInfo CI;
1929 if (CurLexer->popConditionalLevel(CI))
1930 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001931
1932 // If this is a top-level #else, inform the MIOpt.
1933 if (CurLexer->getConditionalStackDepth() == 0)
1934 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001935
1936 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001937 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001938
1939 // Finally, skip the rest of the contents of this block and return the first
1940 // token after it.
1941 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1942 /*FoundElse*/true);
1943}
1944
Chris Lattnercb283342006-06-18 06:48:37 +00001945void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001946 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001947
Chris Lattner22eb9722006-06-18 05:43:12 +00001948 // #elif directive in a non-skipping conditional... start skipping.
1949 // We don't care what the condition is, because we will always skip it (since
1950 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001951 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001952
1953 PPConditionalInfo CI;
1954 if (CurLexer->popConditionalLevel(CI))
1955 return Diag(ElifToken, diag::pp_err_elif_without_if);
1956
Chris Lattner371ac8a2006-07-04 07:11:10 +00001957 // If this is a top-level #elif, inform the MIOpt.
1958 if (CurLexer->getConditionalStackDepth() == 0)
1959 CurLexer->MIOpt.FoundTopLevelElse();
1960
Chris Lattner22eb9722006-06-18 05:43:12 +00001961 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001962 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001963
1964 // Finally, skip the rest of the contents of this block and return the first
1965 // token after it.
1966 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1967 /*FoundElse*/CI.FoundElse);
1968}
Chris Lattnerb8761832006-06-24 21:31:03 +00001969