blob: 4aeaf9d0df1b926bfbb086fb201c0f7e681c7de0 [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.
Chris Lattner22eb9722006-06-18 05:43:12 +000016// -d[MDNI] - Dump various things.
17// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000030#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000031#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000032#include "clang/Basic/Diagnostic.h"
33#include "clang/Basic/FileManager.h"
34#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000035#include "clang/Basic/TargetInfo.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
Chris Lattner02dffbd2006-10-14 07:50:21 +000043Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
44 TargetInfo &target,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000045 FileManager &FM, SourceManager &SM,
46 HeaderSearch &Headers)
Chris Lattner02dffbd2006-10-14 07:50:21 +000047 : Diags(diags), Features(opts), Target(target), FileMgr(FM), SourceMgr(SM),
Chris Lattner25e0d542006-10-18 06:07:05 +000048 HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerc8997182006-06-22 05:52:16 +000049 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000050 ScratchBuf = new ScratchBuffer(SourceMgr);
51
Chris Lattner22eb9722006-06-18 05:43:12 +000052 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000053 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000054 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000055 NumEnteredSourceFiles = 0;
56 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000057 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000058 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000059 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000060
Chris Lattner22eb9722006-06-18 05:43:12 +000061 // Macro expansion is enabled.
62 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000063 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000064
65 // There is no file-change handler yet.
66 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000067 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000068
Chris Lattner8ff71992006-07-06 05:17:39 +000069 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
70 // This gets unpoisoned where it is allowed.
71 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
72
Chris Lattnerb8761832006-06-24 21:31:03 +000073 // Initialize the pragma handlers.
74 PragmaHandlers = new PragmaNamespace(0);
75 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000076
77 // Initialize builtin macros like __LINE__ and friends.
78 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000079}
80
81Preprocessor::~Preprocessor() {
82 // Free any active lexers.
83 delete CurLexer;
84
Chris Lattner69772b02006-07-02 20:34:39 +000085 while (!IncludeMacroStack.empty()) {
86 delete IncludeMacroStack.back().TheLexer;
87 delete IncludeMacroStack.back().TheMacroExpander;
88 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000089 }
Chris Lattnerb8761832006-06-24 21:31:03 +000090
91 // Release pragma information.
92 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000093
94 // Delete the scratch buffer info.
95 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000096}
97
Chris Lattner87d3bec2006-10-17 03:44:32 +000098
99
Chris Lattner22eb9722006-06-18 05:43:12 +0000100/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
101/// the specified LexerToken's location, translating the token's start
102/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000103void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000104 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000105 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000106}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000107
108void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
109 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
110 << getSpelling(Tok) << "'";
111
112 if (!DumpFlags) return;
113 std::cerr << "\t";
114 if (Tok.isAtStartOfLine())
115 std::cerr << " [StartOfLine]";
116 if (Tok.hasLeadingSpace())
117 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000118 if (Tok.isExpandDisabled())
119 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000120 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000121 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000122 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
123 << "']";
124 }
125}
126
127void Preprocessor::DumpMacro(const MacroInfo &MI) const {
128 std::cerr << "MACRO: ";
129 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
130 DumpToken(MI.getReplacementToken(i));
131 std::cerr << " ";
132 }
133 std::cerr << "\n";
134}
135
Chris Lattner22eb9722006-06-18 05:43:12 +0000136void Preprocessor::PrintStats() {
137 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000138 std::cerr << NumDirectives << " directives found:\n";
139 std::cerr << " " << NumDefined << " #define.\n";
140 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000141 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000142 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
143 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
144 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
145 std::cerr << " " << NumElse << " #else/#elif.\n";
146 std::cerr << " " << NumEndif << " #endif.\n";
147 std::cerr << " " << NumPragma << " #pragma.\n";
148 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
149
Chris Lattner78186052006-07-09 00:45:31 +0000150 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
151 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000152 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000153 std::cerr << (NumFastTokenPaste+NumTokenPaste)
154 << " token paste (##) operations performed, "
155 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000156}
157
158//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000159// Token Spelling
160//===----------------------------------------------------------------------===//
161
162
163/// getSpelling() - Return the 'spelling' of this token. The spelling of a
164/// token are the characters used to represent the token in the source file
165/// after trigraph expansion and escaped-newline folding. In particular, this
166/// wants to get the true, uncanonicalized, spelling of things like digraphs
167/// UCNs, etc.
168std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
169 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
170
171 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000172 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000173 if (!Tok.needsCleaning())
174 return std::string(TokStart, TokStart+Tok.getLength());
175
Chris Lattnerd01e2912006-06-18 16:22:51 +0000176 std::string Result;
177 Result.reserve(Tok.getLength());
178
Chris Lattneref9eae12006-07-04 22:33:12 +0000179 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000180 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
181 Ptr != End; ) {
182 unsigned CharSize;
183 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
184 Ptr += CharSize;
185 }
186 assert(Result.size() != unsigned(Tok.getLength()) &&
187 "NeedsCleaning flag set on something that didn't need cleaning!");
188 return Result;
189}
190
191/// getSpelling - This method is used to get the spelling of a token into a
192/// preallocated buffer, instead of as an std::string. The caller is required
193/// to allocate enough space for the token, which is guaranteed to be at least
194/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000195///
196/// Note that this method may do two possible things: it may either fill in
197/// the buffer specified with characters, or it may *change the input pointer*
198/// to point to a constant buffer with the data already in it (avoiding a
199/// copy). The caller is not allowed to modify the returned buffer pointer
200/// if an internal buffer is returned.
201unsigned Preprocessor::getSpelling(const LexerToken &Tok,
202 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000203 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
204
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000205 // If this token is an identifier, just return the string from the identifier
206 // table, which is very quick.
207 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
208 Buffer = II->getName();
209 return Tok.getLength();
210 }
211
212 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000213 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000214
215 // If this token contains nothing interesting, return it directly.
216 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000217 Buffer = TokStart;
218 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000219 }
220 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000221 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000222 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
223 Ptr != End; ) {
224 unsigned CharSize;
225 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
226 Ptr += CharSize;
227 }
228 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
229 "NeedsCleaning flag set on something that didn't need cleaning!");
230
231 return OutBuf-Buffer;
232}
233
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000234
235/// CreateString - Plop the specified string into a scratch buffer and return a
236/// location for it. If specified, the source location provides a source
237/// location for the token.
238SourceLocation Preprocessor::
239CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
240 if (SLoc.isValid())
241 return ScratchBuf->getToken(Buf, Len, SLoc);
242 return ScratchBuf->getToken(Buf, Len);
243}
244
245
Chris Lattnerd01e2912006-06-18 16:22:51 +0000246//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000247// Source File Location Methods.
248//===----------------------------------------------------------------------===//
249
Chris Lattner22eb9722006-06-18 05:43:12 +0000250/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
251/// return null on failure. isAngled indicates whether the file reference is
252/// for system #include's or not (i.e. using <> instead of "").
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000253const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000254 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000255 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000256 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000257 // If the header lookup mechanism may be relative to the current file, pass in
258 // info about where the current file is.
259 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000260 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000261 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000262 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000263 }
264
Chris Lattner63dd32b2006-10-20 04:42:40 +0000265 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000266 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000267 const FileEntry *FE =
268 HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
269 if (FE) return FE;
270
271 // Otherwise, see if this is a subframework header. If so, this is relative
272 // to one of the headers on the #include stack. Walk the list of the current
273 // headers on the #include stack and pass them to HeaderInfo.
274 if (CurLexer) {
275 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
276 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
277 return FE;
278 }
279
280 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
281 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
282 if (ISEntry.TheLexer) {
283 CurFileEnt =
284 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
285 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
286 return FE;
287 }
288 }
289
290 // Otherwise, we really couldn't find the file.
291 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000292}
293
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000294/// isInPrimaryFile - Return true if we're in the top-level file, not in a
295/// #include.
296bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000297 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000298 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000299
Chris Lattner13044d92006-07-03 05:16:44 +0000300 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000301 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000302 if (IncludeMacroStack[i].TheLexer &&
303 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
304 return IncludeMacroStack[i].TheLexer->isMainFile();
305 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000306}
307
308/// getCurrentLexer - Return the current file lexer being lexed from. Note
309/// that this ignores any potentially active macro expansions and _Pragma
310/// expansions going on at the time.
311Lexer *Preprocessor::getCurrentFileLexer() const {
312 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
313
314 // Look for a stacked lexer.
315 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000316 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000317 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
318 return L;
319 }
320 return 0;
321}
322
323
Chris Lattner22eb9722006-06-18 05:43:12 +0000324/// EnterSourceFile - Add a source file to the top of the include stack and
325/// start lexing tokens from it instead of the current buffer. Return true
326/// on failure.
327void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000328 const DirectoryLookup *CurDir,
329 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000330 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000331 ++NumEnteredSourceFiles;
332
Chris Lattner69772b02006-07-02 20:34:39 +0000333 if (MaxIncludeStackDepth < IncludeMacroStack.size())
334 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000335
Chris Lattner22eb9722006-06-18 05:43:12 +0000336 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000337 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000338 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000339 EnterSourceFileWithLexer(TheLexer, CurDir);
340}
Chris Lattner22eb9722006-06-18 05:43:12 +0000341
Chris Lattner69772b02006-07-02 20:34:39 +0000342/// EnterSourceFile - Add a source file to the top of the include stack and
343/// start lexing tokens from it instead of the current buffer.
344void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
345 const DirectoryLookup *CurDir) {
346
347 // Add the current lexer to the include stack.
348 if (CurLexer || CurMacroExpander)
349 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
350 CurMacroExpander));
351
352 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000353 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000354 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000355
356 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000357 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000358 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
359
360 // Get the file entry for the current file.
361 if (const FileEntry *FE =
362 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000363 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000364
Chris Lattner1840e492006-07-02 22:30:01 +0000365 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000366 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000367 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000368}
369
Chris Lattner69772b02006-07-02 20:34:39 +0000370
371
Chris Lattner22eb9722006-06-18 05:43:12 +0000372/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000373/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000374void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000375 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
376 CurMacroExpander));
377 CurLexer = 0;
378 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000379
Chris Lattneree8760b2006-07-15 07:42:55 +0000380 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000381}
382
Chris Lattner7667d0d2006-07-16 18:16:58 +0000383/// EnterTokenStream - Add a "macro" context to the top of the include stack,
384/// which will cause the lexer to start returning the specified tokens. Note
385/// that these tokens will be re-macro-expanded when/if expansion is enabled.
386/// This method assumes that the specified stream of tokens has a permanent
387/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000388void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000389 // Save our current state.
390 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
391 CurMacroExpander));
392 CurLexer = 0;
393 CurDirLookup = 0;
394
395 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000396 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000397}
398
399/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
400/// lexer stack. This should only be used in situations where the current
401/// state of the top-of-stack lexer is known.
402void Preprocessor::RemoveTopOfLexerStack() {
403 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
404 delete CurLexer;
405 delete CurMacroExpander;
406 CurLexer = IncludeMacroStack.back().TheLexer;
407 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
408 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
409 IncludeMacroStack.pop_back();
410}
411
Chris Lattner22eb9722006-06-18 05:43:12 +0000412//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000413// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000414//===----------------------------------------------------------------------===//
415
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000416/// RegisterBuiltinMacro - Register the specified identifier in the identifier
417/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000418IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000419 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000420 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000421
422 // Mark it as being a macro that is builtin.
423 MacroInfo *MI = new MacroInfo(SourceLocation());
424 MI->setIsBuiltinMacro();
425 Id->setMacroInfo(MI);
426 return Id;
427}
428
429
Chris Lattner677757a2006-06-28 05:26:32 +0000430/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
431/// identifier table.
432void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000433 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000434 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000435 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
436 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000437 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000438
439 // GCC Extensions.
440 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
441 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000442 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000443}
444
Chris Lattnerc2395832006-07-09 00:57:04 +0000445/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
446/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000447static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
448 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000449 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
450
451 // If the token isn't an identifier, it's always literally expanded.
452 if (II == 0) return true;
453
454 // If the identifier is a macro, and if that macro is enabled, it may be
455 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000456 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
457 // Fast expanding "#define X X" is ok, because X would be disabled.
458 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000459 return false;
460
461 // If this is an object-like macro invocation, it is safe to trivially expand
462 // it.
463 if (MI->isObjectLike()) return true;
464
465 // If this is a function-like macro invocation, it's safe to trivially expand
466 // as long as the identifier is not a macro argument.
467 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
468 I != E; ++I)
469 if (*I == II)
470 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000471
Chris Lattnerc2395832006-07-09 00:57:04 +0000472 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000473}
474
Chris Lattnerc2395832006-07-09 00:57:04 +0000475
Chris Lattnerafe603f2006-07-11 04:02:46 +0000476/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
477/// lexed is a '('. If so, consume the token and return true, if not, this
478/// method should have no observable side-effect on the lexed tokens.
479bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000480 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000481 unsigned Val;
482 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000483 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000484 else
485 Val = CurMacroExpander->isNextTokenLParen();
486
487 if (Val == 2) {
488 // If we ran off the end of the lexer or macro expander, walk the include
489 // stack, looking for whatever will return the next token.
490 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
491 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
492 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000493 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000494 else
495 Val = Entry.TheMacroExpander->isNextTokenLParen();
496 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000497 }
498
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000499 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
500 // have found something that isn't a '(' or we found the end of the
501 // translation unit. In either case, return false.
502 if (Val != 1)
503 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000504
505 LexerToken Tok;
506 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000507 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
508 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000509}
Chris Lattner677757a2006-06-28 05:26:32 +0000510
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000511/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
512/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000513bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000514 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000515
516 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
517 if (MI->isBuiltinMacro()) {
518 ExpandBuiltinMacro(Identifier);
519 return false;
520 }
521
Chris Lattner81278c62006-10-14 19:03:49 +0000522 // If this is the first use of a target-specific macro, warn about it.
523 if (MI->isTargetSpecific()) {
524 MI->setIsTargetSpecific(false); // Don't warn on second use.
525 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
526 diag::port_target_macro_use);
527 }
528
Chris Lattneree8760b2006-07-15 07:42:55 +0000529 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000530 /// for each macro argument, the list of tokens that were provided to the
531 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000532 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000533
534 // If this is a function-like macro, read the arguments.
535 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000536 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
537 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000538 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000539 return true;
540
Chris Lattner78186052006-07-09 00:45:31 +0000541 // Remember that we are now parsing the arguments to a macro invocation.
542 // Preprocessor directives used inside macro arguments are not portable, and
543 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000544 InMacroArgs = true;
545 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000546
547 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000548 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000549
550 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000551 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000552
553 ++NumFnMacroExpanded;
554 } else {
555 ++NumMacroExpanded;
556 }
Chris Lattner13044d92006-07-03 05:16:44 +0000557
558 // Notice that this macro has been used.
559 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000560
561 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000562
563 // If this macro expands to no tokens, don't bother to push it onto the
564 // expansion stack, only to take it right back off.
565 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000566 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000567 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000568
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000569 // Ignore this macro use, just return the next token in the current
570 // buffer.
571 bool HadLeadingSpace = Identifier.hasLeadingSpace();
572 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
573
574 Lex(Identifier);
575
576 // If the identifier isn't on some OTHER line, inherit the leading
577 // whitespace/first-on-a-line property of this token. This handles
578 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
579 // empty.
580 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000581 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
582 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000583 }
584 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000585 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000586
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000587 } else if (MI->getNumTokens() == 1 &&
588 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000589 // Otherwise, if this macro expands into a single trivially-expanded
590 // token: expand it now. This handles common cases like
591 // "#define VAL 42".
592
593 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
594 // identifier to the expanded token.
595 bool isAtStartOfLine = Identifier.isAtStartOfLine();
596 bool hasLeadingSpace = Identifier.hasLeadingSpace();
597
598 // Remember where the token is instantiated.
599 SourceLocation InstantiateLoc = Identifier.getLocation();
600
601 // Replace the result token.
602 Identifier = MI->getReplacementToken(0);
603
604 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000605 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
606 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000607
608 // Update the tokens location to include both its logical and physical
609 // locations.
610 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000611 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000612 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000613
Chris Lattner6e4bf522006-07-27 06:59:25 +0000614 // If this is #define X X, we must mark the result as unexpandible.
615 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
616 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000617 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000618
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000619 // Since this is not an identifier token, it can't be macro expanded, so
620 // we're done.
621 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000622 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000623 }
624
Chris Lattner78186052006-07-09 00:45:31 +0000625 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000626 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000627
628 // Now that the macro is at the top of the include stack, ask the
629 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000630 Lex(Identifier);
631 return false;
632}
633
Chris Lattneree8760b2006-07-15 07:42:55 +0000634/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000635/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000636/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000637MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
638 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000639 // The number of fixed arguments to parse.
640 unsigned NumFixedArgsLeft = MI->getNumArgs();
641 bool isVariadic = MI->isVariadic();
642
Chris Lattner78186052006-07-09 00:45:31 +0000643 // Outer loop, while there are more arguments, keep reading them.
644 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000645 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000646 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000647
648 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000649 // argument is separated by an EOF token. Use a SmallVector so we can avoid
650 // heap allocations in the common case.
651 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000652
653 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000654 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000655 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
656 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000657
Chris Lattner78186052006-07-09 00:45:31 +0000658 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000659 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
660 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000661 LexUnexpandedToken(Tok);
662
663 if (Tok.getKind() == tok::eof) {
664 Diag(MacroName, diag::err_unterm_macro_invoc);
665 // Do not lose the EOF. Return it to the client.
666 MacroName = Tok;
667 return 0;
668 } else if (Tok.getKind() == tok::r_paren) {
669 // If we found the ) token, the macro arg list is done.
670 if (NumParens-- == 0)
671 break;
672 } else if (Tok.getKind() == tok::l_paren) {
673 ++NumParens;
674 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
675 // Comma ends this argument if there are more fixed arguments expected.
676 if (NumFixedArgsLeft)
677 break;
678
Chris Lattner2ada5d32006-07-15 07:51:24 +0000679 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000680 if (!isVariadic) {
681 // Emit the diagnostic at the macro name in case there is a missing ).
682 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000683 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000684 return 0;
685 }
686 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000687 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
688 // If this is a comment token in the argument list and we're just in
689 // -C mode (not -CC mode), discard the comment.
690 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000691 }
692
693 ArgTokens.push_back(Tok);
694 }
695
Chris Lattnera12dd152006-07-11 04:09:02 +0000696 // Empty arguments are standard in C99 and supported as an extension in
697 // other modes.
698 if (ArgTokens.empty() && !Features.C99)
699 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000700
Chris Lattner36b6e812006-07-21 06:38:30 +0000701 // Add a marker EOF token to the end of the token list for this argument.
702 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000703 EOFTok.startToken();
704 EOFTok.setKind(tok::eof);
705 EOFTok.setLocation(Tok.getLocation());
706 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000707 ArgTokens.push_back(EOFTok);
708 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000709 --NumFixedArgsLeft;
710 };
711
712 // Okay, we either found the r_paren. Check to see if we parsed too few
713 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000714 unsigned MinArgsExpected = MI->getNumArgs();
715
Chris Lattner775d8322006-07-29 04:39:41 +0000716 // See MacroArgs instance var for description of this.
717 bool isVarargsElided = false;
718
Chris Lattner2ada5d32006-07-15 07:51:24 +0000719 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000720 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000721 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000722 // Varargs where the named vararg parameter is missing: ok as extension.
723 // #define A(x, ...)
724 // A("blah")
725 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000726
727 // Remember this occurred if this is a C99 macro invocation with at least
728 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000729 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000730 } else if (MI->getNumArgs() == 1) {
731 // #define A(x)
732 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000733 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000734
735 // Empty arguments are standard in C99 and supported as an extension in
736 // other modes.
737 if (ArgTokens.empty() && !Features.C99)
738 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000739 } else {
740 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000741 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000742 return 0;
743 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000744
745 // Add a marker EOF token to the end of the token list for this argument.
746 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000747 Tok.startToken();
748 Tok.setKind(tok::eof);
749 Tok.setLocation(EndLoc);
750 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000751 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000752 }
753
Chris Lattner775d8322006-07-29 04:39:41 +0000754 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000755}
756
Chris Lattnerc673f902006-06-30 06:10:41 +0000757/// ComputeDATE_TIME - Compute the current time, enter it into the specified
758/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
759/// the identifier tokens inserted.
760static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000761 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000762 time_t TT = time(0);
763 struct tm *TM = localtime(&TT);
764
765 static const char * const Months[] = {
766 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
767 };
768
769 char TmpBuffer[100];
770 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
771 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000772 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000773
774 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000775 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000776}
777
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000778/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
779/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000780void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000781 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000782 IdentifierInfo *II = Tok.getIdentifierInfo();
783 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000784
785 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
786 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000787 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000788 return Handle_Pragma(Tok);
789
Chris Lattner78186052006-07-09 00:45:31 +0000790 ++NumBuiltinMacroExpanded;
791
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000792 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000793
794 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000795 Tok.setIdentifierInfo(0);
796 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000797
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000798 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000799 // __LINE__ expands to a simple numeric value.
800 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
801 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000802 Tok.setKind(tok::numeric_constant);
803 Tok.setLength(Length);
804 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000805 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000806 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000807 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000808 Diag(Tok, diag::ext_pp_base_file);
809 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
810 while (NextLoc.getFileID() != 0) {
811 Loc = NextLoc;
812 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
813 }
814 }
815
Chris Lattner0766e592006-07-03 01:07:01 +0000816 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
817 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000818 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000819 Tok.setKind(tok::string_literal);
820 Tok.setLength(FN.size());
821 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000822 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000823 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000824 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000825 Tok.setKind(tok::string_literal);
826 Tok.setLength(strlen("\"Mmm dd yyyy\""));
827 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000828 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000829 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000830 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000831 Tok.setKind(tok::string_literal);
832 Tok.setLength(strlen("\"hh:mm:ss\""));
833 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000834 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000835 Diag(Tok, diag::ext_pp_include_level);
836
837 // Compute the include depth of this token.
838 unsigned Depth = 0;
839 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
840 for (; Loc.getFileID() != 0; ++Depth)
841 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
842
843 // __INCLUDE_LEVEL__ expands to a simple numeric value.
844 sprintf(TmpBuffer, "%u", Depth);
845 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000846 Tok.setKind(tok::numeric_constant);
847 Tok.setLength(Length);
848 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000849 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000850 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
851 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
852 Diag(Tok, diag::ext_pp_timestamp);
853
854 // Get the file that we are lexing out of. If we're currently lexing from
855 // a macro, dig into the include stack.
856 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000857 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000858
859 if (TheLexer)
860 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
861
862 // If this file is older than the file it depends on, emit a diagnostic.
863 const char *Result;
864 if (CurFile) {
865 time_t TT = CurFile->getModificationTime();
866 struct tm *TM = localtime(&TT);
867 Result = asctime(TM);
868 } else {
869 Result = "??? ??? ?? ??:??:?? ????\n";
870 }
871 TmpBuffer[0] = '"';
872 strcpy(TmpBuffer+1, Result);
873 unsigned Len = strlen(TmpBuffer);
874 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000875 Tok.setKind(tok::string_literal);
876 Tok.setLength(Len);
877 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000878 } else {
879 assert(0 && "Unknown identifier!");
880 }
881}
Chris Lattner677757a2006-06-28 05:26:32 +0000882
Chris Lattner13044d92006-07-03 05:16:44 +0000883namespace {
884struct UnusedIdentifierReporter : public IdentifierVisitor {
885 Preprocessor &PP;
886 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
887
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000888 void VisitIdentifier(IdentifierInfo &II) const {
889 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
890 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000891 }
892};
893}
894
Chris Lattner677757a2006-06-28 05:26:32 +0000895//===----------------------------------------------------------------------===//
896// Lexer Event Handling.
897//===----------------------------------------------------------------------===//
898
Chris Lattnercefc7682006-07-08 08:28:12 +0000899/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
900/// identifier information for the token and install it into the token.
901IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
902 const char *BufPtr) {
903 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
904 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
905
906 // Look up this token, see if it is a macro, or if it is a language keyword.
907 IdentifierInfo *II;
908 if (BufPtr && !Identifier.needsCleaning()) {
909 // No cleaning needed, just use the characters from the lexed buffer.
910 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
911 } else {
912 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
913 const char *TmpBuf = (char*)alloca(Identifier.getLength());
914 unsigned Size = getSpelling(Identifier, TmpBuf);
915 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
916 }
Chris Lattner8c204872006-10-14 05:19:21 +0000917 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000918 return II;
919}
920
921
Chris Lattner677757a2006-06-28 05:26:32 +0000922/// HandleIdentifier - This callback is invoked when the lexer reads an
923/// identifier. This callback looks up the identifier in the map and/or
924/// potentially macro expands it or turns it into a named token (like 'for').
925void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000926 assert(Identifier.getIdentifierInfo() &&
927 "Can't handle identifiers without identifier info!");
928
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000929 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000930
931 // If this identifier was poisoned, and if it was not produced from a macro
932 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000933 if (II.isPoisoned() && CurLexer) {
934 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
935 Diag(Identifier, diag::err_pp_used_poisoned_id);
936 else
937 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
938 }
Chris Lattner677757a2006-06-28 05:26:32 +0000939
Chris Lattner78186052006-07-09 00:45:31 +0000940 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000941 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000942 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
943 if (MI->isEnabled()) {
944 if (!HandleMacroExpandedIdentifier(Identifier, MI))
945 return;
946 } else {
947 // C99 6.10.3.4p2 says that a disabled macro may never again be
948 // expanded, even if it's in a context where it could be expanded in the
949 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000950 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000951 }
952 }
Chris Lattner063400e2006-10-14 19:54:15 +0000953 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
954 // If this identifier is a macro on some other target, emit a diagnostic.
955 // This diagnosic is only emitted when macro expansion is enabled, because
956 // the macro would not have been expanded for the other target either.
957 II.setIsOtherTargetMacro(false); // Don't warn on second use.
958 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
959 diag::port_target_macro_use);
960
961 }
Chris Lattner677757a2006-06-28 05:26:32 +0000962
963 // Change the kind of this identifier to the appropriate token kind, e.g.
964 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000965 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000966
967 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000968 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000969}
970
Chris Lattner22eb9722006-06-18 05:43:12 +0000971/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
972/// the current file. This either returns the EOF token or pops a level off
973/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000974bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000975 assert(!CurMacroExpander &&
976 "Ending a file when currently in a macro!");
977
Chris Lattner371ac8a2006-07-04 07:11:10 +0000978 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000979 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000980 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000981 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000982 // Okay, this has a controlling macro, remember in PerFileInfo.
983 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000984 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
985 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000986 }
987 }
988
Chris Lattner22eb9722006-06-18 05:43:12 +0000989 // If this is a #include'd file, pop it off the include stack and continue
990 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000991 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000992 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000993 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +0000994
995 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000996 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000997 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
998
999 // Get the file entry for the current file.
1000 if (const FileEntry *FE =
1001 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001002 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001003
Chris Lattner0c885f52006-06-21 06:50:18 +00001004 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001005 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001006 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001007
1008 // Client should lex another token.
1009 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001010 }
1011
Chris Lattner8c204872006-10-14 05:19:21 +00001012 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001013 CurLexer->BufferPtr = CurLexer->BufferEnd;
1014 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001015 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001016
1017 // We're done with the #included file.
1018 delete CurLexer;
1019 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001020
Chris Lattner03f83482006-07-10 06:16:26 +00001021 // This is the end of the top-level file. If the diag::pp_macro_not_used
1022 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1023 // have not been used.
1024 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1025 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001026
1027 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001028}
1029
1030/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001031/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001032bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001033 assert(CurMacroExpander && !CurLexer &&
1034 "Ending a macro when currently in a #include file!");
1035
Chris Lattner22eb9722006-06-18 05:43:12 +00001036 delete CurMacroExpander;
1037
Chris Lattner69772b02006-07-02 20:34:39 +00001038 // Handle this like a #include file being popped off the stack.
1039 CurMacroExpander = 0;
1040 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001041}
1042
1043
1044//===----------------------------------------------------------------------===//
1045// Utility Methods for Preprocessor Directive Handling.
1046//===----------------------------------------------------------------------===//
1047
1048/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1049/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001050void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001051 LexerToken Tmp;
1052 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001053 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001054 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001055}
1056
1057/// ReadMacroName - Lex and validate a macro name, which occurs after a
1058/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001059/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1060/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001061/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001062void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001063 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001064 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001065
1066 // Missing macro name?
1067 if (MacroNameTok.getKind() == tok::eom)
1068 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1069
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001070 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1071 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001072 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001073 // Fall through on error.
1074 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001075 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001076
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001077 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1078 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001079 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001080 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001081 } else if (isDefineUndef && II->getMacroInfo() &&
1082 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001083 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001084 if (isDefineUndef == 1)
1085 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1086 else
1087 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001088 } else {
1089 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001090 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001091 }
1092
Chris Lattner22eb9722006-06-18 05:43:12 +00001093 // Invalid macro name, read and discard the rest of the line. Then set the
1094 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001095 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001096 return DiscardUntilEndOfDirective();
1097}
1098
1099/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1100/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001101void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001102 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001103 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001104 // There should be no tokens after the directive, but we allow them as an
1105 // extension.
1106 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001107 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1108 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001109 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001110}
1111
1112
1113
1114/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1115/// decided that the subsequent tokens are in the #if'd out portion of the
1116/// file. Lex the rest of the file, until we see an #endif. If
1117/// FoundNonSkipPortion is true, then we have already emitted code for part of
1118/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1119/// is true, then #else directives are ok, if not, then we have already seen one
1120/// so a #else directive is a duplicate. When this returns, the caller can lex
1121/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001122void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001123 bool FoundNonSkipPortion,
1124 bool FoundElse) {
1125 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001126 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001127 "Lexing a macro, not a file?");
1128
1129 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1130 FoundNonSkipPortion, FoundElse);
1131
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001132 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1133 // disabling warnings, etc.
1134 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 LexerToken Tok;
1136 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001137 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001138
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001139 // If this is the end of the buffer, we have an error.
1140 if (Tok.getKind() == tok::eof) {
1141 // Emit errors for each unterminated conditional on the stack, including
1142 // the current one.
1143 while (!CurLexer->ConditionalStack.empty()) {
1144 Diag(CurLexer->ConditionalStack.back().IfLoc,
1145 diag::err_pp_unterminated_conditional);
1146 CurLexer->ConditionalStack.pop_back();
1147 }
1148
1149 // Just return and let the caller lex after this #include.
1150 break;
1151 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001152
1153 // If this token is not a preprocessor directive, just skip it.
1154 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1155 continue;
1156
1157 // We just parsed a # character at the start of a line, so we're in
1158 // directive mode. Tell the lexer this so any newlines we see will be
1159 // converted into an EOM token (this terminates the macro).
1160 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001161 CurLexer->KeepCommentMode = false;
1162
Chris Lattner22eb9722006-06-18 05:43:12 +00001163
1164 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001165 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001166
1167 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1168 // something bogus), skip it.
1169 if (Tok.getKind() != tok::identifier) {
1170 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001171 // Restore comment saving mode.
1172 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001173 continue;
1174 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001175
Chris Lattner22eb9722006-06-18 05:43:12 +00001176 // If the first letter isn't i or e, it isn't intesting to us. We know that
1177 // this is safe in the face of spelling differences, because there is no way
1178 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001179 // allows us to avoid looking up the identifier info for #define/#undef and
1180 // other common directives.
1181 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1182 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001183 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1184 FirstChar != 'i' && FirstChar != 'e') {
1185 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001186 // Restore comment saving mode.
1187 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001188 continue;
1189 }
1190
Chris Lattnere60165f2006-06-22 06:36:29 +00001191 // Get the identifier name without trigraphs or embedded newlines. Note
1192 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1193 // when skipping.
1194 // TODO: could do this with zero copies in the no-clean case by using
1195 // strncmp below.
1196 char Directive[20];
1197 unsigned IdLen;
1198 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1199 IdLen = Tok.getLength();
1200 memcpy(Directive, RawCharData, IdLen);
1201 Directive[IdLen] = 0;
1202 } else {
1203 std::string DirectiveStr = getSpelling(Tok);
1204 IdLen = DirectiveStr.size();
1205 if (IdLen >= 20) {
1206 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001207 // Restore comment saving mode.
1208 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001209 continue;
1210 }
1211 memcpy(Directive, &DirectiveStr[0], IdLen);
1212 Directive[IdLen] = 0;
1213 }
1214
Chris Lattner22eb9722006-06-18 05:43:12 +00001215 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001216 if ((IdLen == 2) || // "if"
1217 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1218 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001219 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1220 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001221 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001222 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001223 /*foundnonskip*/false,
1224 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001225 }
1226 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001227 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001228 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001229 PPConditionalInfo CondInfo;
1230 CondInfo.WasSkipping = true; // Silence bogus warning.
1231 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1232 assert(!InCond && "Can't be skipping if not in a conditional!");
1233
1234 // If we popped the outermost skipping block, we're done skipping!
1235 if (!CondInfo.WasSkipping)
1236 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001237 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001238 // #else directive in a skipping conditional. If not in some other
1239 // skipping conditional, and if #else hasn't already been seen, enter it
1240 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001241 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001242 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1243
1244 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001245 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001246
1247 // Note that we've seen a #else in this conditional.
1248 CondInfo.FoundElse = true;
1249
1250 // If the conditional is at the top level, and the #if block wasn't
1251 // entered, enter the #else block now.
1252 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1253 CondInfo.FoundNonSkip = true;
1254 break;
1255 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001256 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001257 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1258
1259 bool ShouldEnter;
1260 // If this is in a skipping block or if we're already handled this #if
1261 // block, don't bother parsing the condition.
1262 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001263 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001264 ShouldEnter = false;
1265 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001266 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001267 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001268 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1269 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001270 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001271 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001272 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001273 }
1274
1275 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001276 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001277
1278 // If this condition is true, enter it!
1279 if (ShouldEnter) {
1280 CondInfo.FoundNonSkip = true;
1281 break;
1282 }
1283 }
1284 }
1285
1286 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001287 // Restore comment saving mode.
1288 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001289 }
1290
1291 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1292 // of the file, just stop skipping and return to lexing whatever came after
1293 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001294 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001295}
1296
1297//===----------------------------------------------------------------------===//
1298// Preprocessor Directive Handling.
1299//===----------------------------------------------------------------------===//
1300
1301/// HandleDirective - This callback is invoked when the lexer sees a # token
1302/// at the start of a line. This consumes the directive, modifies the
1303/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1304/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001305void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001306 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001307
1308 // We just parsed a # character at the start of a line, so we're in directive
1309 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001310 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001311 CurLexer->ParsingPreprocessorDirective = true;
1312
1313 ++NumDirectives;
1314
Chris Lattner371ac8a2006-07-04 07:11:10 +00001315 // We are about to read a token. For the multiple-include optimization FA to
1316 // work, we have to remember if we had read any tokens *before* this
1317 // pp-directive.
1318 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1319
Chris Lattner78186052006-07-09 00:45:31 +00001320 // Read the next token, the directive flavor. This isn't expanded due to
1321 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001322 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001323
Chris Lattner78186052006-07-09 00:45:31 +00001324 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1325 // #define A(x) #x
1326 // A(abc
1327 // #warning blah
1328 // def)
1329 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001330 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001331 Diag(Result, diag::ext_embedded_directive);
1332
Chris Lattner22eb9722006-06-18 05:43:12 +00001333 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001334 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001335 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001336
Chris Lattner22eb9722006-06-18 05:43:12 +00001337 case tok::numeric_constant:
1338 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001339 DiscardUntilEndOfDirective();
1340 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001341 default:
1342 IdentifierInfo *II = Result.getIdentifierInfo();
1343 if (II == 0) break; // Not an identifier.
1344
1345 // Ask what the preprocessor keyword ID is.
1346 switch (II->getPPKeywordID()) {
1347 default: break;
1348 // C99 6.10.1 - Conditional Inclusion.
1349 case tok::pp_if:
1350 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1351 case tok::pp_ifdef:
1352 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1353 case tok::pp_ifndef:
1354 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1355 case tok::pp_elif:
1356 return HandleElifDirective(Result);
1357 case tok::pp_else:
1358 return HandleElseDirective(Result);
1359 case tok::pp_endif:
1360 return HandleEndifDirective(Result);
1361
1362 // C99 6.10.2 - Source File Inclusion.
1363 case tok::pp_include:
1364 return HandleIncludeDirective(Result); // Handle #include.
1365
1366 // C99 6.10.3 - Macro Replacement.
1367 case tok::pp_define:
1368 return HandleDefineDirective(Result, false);
1369 case tok::pp_undef:
1370 return HandleUndefDirective(Result);
1371
1372 // C99 6.10.4 - Line Control.
1373 case tok::pp_line:
1374 // FIXME: implement #line
1375 DiscardUntilEndOfDirective();
1376 return;
1377
1378 // C99 6.10.5 - Error Directive.
1379 case tok::pp_error:
1380 return HandleUserDiagnosticDirective(Result, false);
1381
1382 // C99 6.10.6 - Pragma Directive.
1383 case tok::pp_pragma:
1384 return HandlePragmaDirective();
1385
1386 // GNU Extensions.
1387 case tok::pp_import:
1388 return HandleImportDirective(Result);
1389 case tok::pp_include_next:
1390 return HandleIncludeNextDirective(Result);
1391
1392 case tok::pp_warning:
1393 Diag(Result, diag::ext_pp_warning_directive);
1394 return HandleUserDiagnosticDirective(Result, true);
1395 case tok::pp_ident:
1396 return HandleIdentSCCSDirective(Result);
1397 case tok::pp_sccs:
1398 return HandleIdentSCCSDirective(Result);
1399 case tok::pp_assert:
1400 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001401 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001402 case tok::pp_unassert:
1403 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001404 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001405
1406 // clang extensions.
1407 case tok::pp_define_target:
1408 return HandleDefineDirective(Result, true);
1409 case tok::pp_define_other_target:
1410 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001411 }
1412 break;
1413 }
1414
1415 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001416 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001417
1418 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001419 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001420
1421 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001422}
1423
Chris Lattner01d66cc2006-07-03 22:16:27 +00001424void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 bool isWarning) {
1426 // Read the rest of the line raw. We do this because we don't want macros
1427 // to be expanded and we don't require that the tokens be valid preprocessing
1428 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1429 // collapse multiple consequtive white space between tokens, but this isn't
1430 // specified by the standard.
1431 std::string Message = CurLexer->ReadToEndOfLine();
1432
1433 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001434 return Diag(Tok, DiagID, Message);
1435}
1436
1437/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1438///
1439void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001440 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001441 Diag(Tok, diag::ext_pp_ident_directive);
1442
Chris Lattner371ac8a2006-07-04 07:11:10 +00001443 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001444 LexerToken StrTok;
1445 Lex(StrTok);
1446
1447 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001448 if (StrTok.getKind() != tok::string_literal &&
1449 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001450 return Diag(StrTok, diag::err_pp_malformed_ident);
1451
1452 // Verify that there is nothing after the string, other than EOM.
1453 CheckEndOfDirective("#ident");
1454
1455 if (IdentHandler)
1456 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001457}
1458
Chris Lattnerb8761832006-06-24 21:31:03 +00001459//===----------------------------------------------------------------------===//
1460// Preprocessor Include Directive Handling.
1461//===----------------------------------------------------------------------===//
1462
Chris Lattner22eb9722006-06-18 05:43:12 +00001463/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1464/// file to be included from the lexer, then include it! This is a common
1465/// routine with functionality shared between #include, #include_next and
1466/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001467void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001468 const DirectoryLookup *LookupFrom,
1469 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001470
Chris Lattner22eb9722006-06-18 05:43:12 +00001471 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001472 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001473
1474 // If the token kind is EOM, the error has already been diagnosed.
1475 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001476 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001477
1478 // Verify that there is nothing after the filename, other than EOM. Use the
1479 // preprocessor to lex this in case lexing the filename entered a macro.
1480 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001481
1482 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001483 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001484 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1485
Chris Lattner269c2322006-06-25 06:23:00 +00001486 // Find out whether the filename is <x> or "x".
1487 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001488
1489 // Remove the quotes.
1490 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1491
Chris Lattner22eb9722006-06-18 05:43:12 +00001492 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001493 const DirectoryLookup *CurDir;
1494 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001495 if (File == 0)
1496 return Diag(FilenameTok, diag::err_pp_file_not_found);
1497
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001498 // Ask HeaderInfo if we should enter this #include file.
1499 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1500 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001501 return;
1502 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001503
1504 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001505 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001506 if (FileID == 0)
1507 return Diag(FilenameTok, diag::err_pp_file_not_found);
1508
1509 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001510 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001511}
1512
1513/// HandleIncludeNextDirective - Implements #include_next.
1514///
Chris Lattnercb283342006-06-18 06:48:37 +00001515void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1516 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001517
1518 // #include_next is like #include, except that we start searching after
1519 // the current found directory. If we can't do this, issue a
1520 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001521 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001522 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001523 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001524 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001525 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001526 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001527 } else {
1528 // Start looking up in the next directory.
1529 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001530 }
1531
1532 return HandleIncludeDirective(IncludeNextTok, Lookup);
1533}
1534
1535/// HandleImportDirective - Implements #import.
1536///
Chris Lattnercb283342006-06-18 06:48:37 +00001537void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1538 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001539
1540 return HandleIncludeDirective(ImportTok, 0, true);
1541}
1542
Chris Lattnerb8761832006-06-24 21:31:03 +00001543//===----------------------------------------------------------------------===//
1544// Preprocessor Macro Directive Handling.
1545//===----------------------------------------------------------------------===//
1546
Chris Lattnercefc7682006-07-08 08:28:12 +00001547/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1548/// definition has just been read. Lex the rest of the arguments and the
1549/// closing ), updating MI with what we learn. Return true if an error occurs
1550/// parsing the arg list.
1551bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1552 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001553 while (1) {
1554 LexUnexpandedToken(Tok);
1555 switch (Tok.getKind()) {
1556 case tok::r_paren:
1557 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001558 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001559 // Otherwise we have #define FOO(A,)
1560 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1561 return true;
1562 case tok::ellipsis: // #define X(... -> C99 varargs
1563 // Warn if use of C99 feature in non-C99 mode.
1564 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1565
1566 // Lex the token after the identifier.
1567 LexUnexpandedToken(Tok);
1568 if (Tok.getKind() != tok::r_paren) {
1569 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1570 return true;
1571 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001572 // Add the __VA_ARGS__ identifier as an argument.
1573 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001574 MI->setIsC99Varargs();
1575 return false;
1576 case tok::eom: // #define X(
1577 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1578 return true;
1579 default: // #define X(1
1580 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1581 return true;
1582 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001583 IdentifierInfo *II = Tok.getIdentifierInfo();
1584
1585 // If this is already used as an argument, it is used multiple times (e.g.
1586 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001587 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001588 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1589 return true;
1590 }
1591
1592 // Add the argument to the macro info.
1593 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001594
1595 // Lex the token after the identifier.
1596 LexUnexpandedToken(Tok);
1597
1598 switch (Tok.getKind()) {
1599 default: // #define X(A B
1600 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1601 return true;
1602 case tok::r_paren: // #define X(A)
1603 return false;
1604 case tok::comma: // #define X(A,
1605 break;
1606 case tok::ellipsis: // #define X(A... -> GCC extension
1607 // Diagnose extension.
1608 Diag(Tok, diag::ext_named_variadic_macro);
1609
1610 // Lex the token after the identifier.
1611 LexUnexpandedToken(Tok);
1612 if (Tok.getKind() != tok::r_paren) {
1613 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1614 return true;
1615 }
1616
1617 MI->setIsGNUVarargs();
1618 return false;
1619 }
1620 }
1621 }
1622}
1623
Chris Lattner22eb9722006-06-18 05:43:12 +00001624/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001625/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1626/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001627///
Chris Lattner81278c62006-10-14 19:03:49 +00001628void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1629 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001630 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001631
Chris Lattner22eb9722006-06-18 05:43:12 +00001632 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001633 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001634
1635 // Error reading macro name? If so, diagnostic already issued.
1636 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001637 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001638
Chris Lattner457fc152006-07-29 06:30:25 +00001639 // If we are supposed to keep comments in #defines, reenable comment saving
1640 // mode.
1641 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1642
Chris Lattner063400e2006-10-14 19:54:15 +00001643 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001644 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001645 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001646
Chris Lattner063400e2006-10-14 19:54:15 +00001647 // If the identifier is an 'other target' macro, clear this bit.
1648 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1649
1650
Chris Lattner22eb9722006-06-18 05:43:12 +00001651 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001652 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001653
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001654 // If this is a function-like macro definition, parse the argument list,
1655 // marking each of the identifiers as being used as macro arguments. Also,
1656 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001657 if (Tok.getKind() == tok::eom) {
1658 // If there is no body to this macro, we have no special handling here.
1659 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001660 // This is a function-like macro definition. Read the argument list.
1661 MI->setIsFunctionLike();
1662 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001663 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001664 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001665 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001666 if (CurLexer->ParsingPreprocessorDirective)
1667 DiscardUntilEndOfDirective();
1668 return;
1669 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001670
Chris Lattner815a1f92006-07-08 20:48:04 +00001671 // Read the first token after the arg list for down below.
1672 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001673 } else if (!Tok.hasLeadingSpace()) {
1674 // C99 requires whitespace between the macro definition and the body. Emit
1675 // a diagnostic for something like "#define X+".
1676 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001677 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001678 } else {
1679 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1680 // one in some cases!
1681 }
1682 } else {
1683 // This is a normal token with leading space. Clear the leading space
1684 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001685 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001686 }
1687
Chris Lattner7e374832006-07-29 03:46:57 +00001688 // If this is a definition of a variadic C99 function-like macro, not using
1689 // the GNU named varargs extension, enabled __VA_ARGS__.
1690
1691 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1692 // This gets unpoisoned where it is allowed.
1693 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1694 if (MI->isC99Varargs())
1695 Ident__VA_ARGS__->setIsPoisoned(false);
1696
Chris Lattner22eb9722006-06-18 05:43:12 +00001697 // Read the rest of the macro body.
1698 while (Tok.getKind() != tok::eom) {
1699 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001700
1701 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001702 // parameters in function-like macro expansions.
1703 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001704 // Get the next token of the macro.
1705 LexUnexpandedToken(Tok);
1706 continue;
1707 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001708
Chris Lattner815a1f92006-07-08 20:48:04 +00001709 // Get the next token of the macro.
1710 LexUnexpandedToken(Tok);
1711
1712 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001713 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001714 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001715 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001716 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001717
1718 // Disable __VA_ARGS__ again.
1719 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001720 return;
1721 }
1722
1723 // Things look ok, add the param name token to the macro.
1724 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001725
Chris Lattner22eb9722006-06-18 05:43:12 +00001726 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001727 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001728 }
Chris Lattner7e374832006-07-29 03:46:57 +00001729
1730 // Disable __VA_ARGS__ again.
1731 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001732
Chris Lattnerbff18d52006-07-06 04:49:18 +00001733 // Check that there is no paste (##) operator at the begining or end of the
1734 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001735 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001736 if (NumTokens != 0) {
1737 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001738 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001739 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001740 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001741 }
1742 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001743 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001744 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001745 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001746 }
1747 }
1748
Chris Lattner13044d92006-07-03 05:16:44 +00001749 // If this is the primary source file, remember that this macro hasn't been
1750 // used yet.
1751 if (isInPrimaryFile())
1752 MI->setIsUsed(false);
1753
Chris Lattner22eb9722006-06-18 05:43:12 +00001754 // Finally, if this identifier already had a macro defined for it, verify that
1755 // the macro bodies are identical and free the old definition.
1756 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001757 if (!OtherMI->isUsed())
1758 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1759
Chris Lattner22eb9722006-06-18 05:43:12 +00001760 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001761 // must be the same. C99 6.10.3.2.
1762 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001763 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1764 MacroNameTok.getIdentifierInfo()->getName());
1765 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1766 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001767 delete OtherMI;
1768 }
1769
1770 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001771}
1772
Chris Lattner063400e2006-10-14 19:54:15 +00001773/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1774void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1775 LexerToken MacroNameTok;
1776 ReadMacroName(MacroNameTok, 1);
1777
1778 // Error reading macro name? If so, diagnostic already issued.
1779 if (MacroNameTok.getKind() == tok::eom)
1780 return;
1781
1782 // Check to see if this is the last token on the #undef line.
1783 CheckEndOfDirective("#define_other_target");
1784
1785 // If there is already a macro defined by this name, turn it into a
1786 // target-specific define.
1787 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1788 MI->setIsTargetSpecific(true);
1789 return;
1790 }
1791
1792 // Mark the identifier as being a macro on some other target.
1793 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1794}
1795
Chris Lattner22eb9722006-06-18 05:43:12 +00001796
1797/// HandleUndefDirective - Implements #undef.
1798///
Chris Lattnercb283342006-06-18 06:48:37 +00001799void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001800 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001801
Chris Lattner22eb9722006-06-18 05:43:12 +00001802 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001803 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001804
1805 // Error reading macro name? If so, diagnostic already issued.
1806 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001807 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001808
1809 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001810 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001811
1812 // Okay, we finally have a valid identifier to undef.
1813 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1814
Chris Lattner063400e2006-10-14 19:54:15 +00001815 // #undef untaints an identifier if it were marked by define_other_target.
1816 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1817
Chris Lattner22eb9722006-06-18 05:43:12 +00001818 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001819 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001820
Chris Lattner13044d92006-07-03 05:16:44 +00001821 if (!MI->isUsed())
1822 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001823
1824 // Free macro definition.
1825 delete MI;
1826 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001827}
1828
1829
Chris Lattnerb8761832006-06-24 21:31:03 +00001830//===----------------------------------------------------------------------===//
1831// Preprocessor Conditional Directive Handling.
1832//===----------------------------------------------------------------------===//
1833
Chris Lattner22eb9722006-06-18 05:43:12 +00001834/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001835/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1836/// if any tokens have been returned or pp-directives activated before this
1837/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001838///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001839void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1840 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001841 ++NumIf;
1842 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001843
Chris Lattner22eb9722006-06-18 05:43:12 +00001844 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001845 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001846
1847 // Error reading macro name? If so, diagnostic already issued.
1848 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001849 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001850
1851 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001852 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1853
1854 // If the start of a top-level #ifdef, inform MIOpt.
1855 if (!ReadAnyTokensBeforeDirective &&
1856 CurLexer->getConditionalStackDepth() == 0) {
1857 assert(isIfndef && "#ifdef shouldn't reach here");
1858 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1859 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001860
Chris Lattner063400e2006-10-14 19:54:15 +00001861 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1862 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001863
Chris Lattner81278c62006-10-14 19:03:49 +00001864 // If there is a macro, process it.
1865 if (MI) {
1866 // Mark it used.
1867 MI->setIsUsed(true);
1868
1869 // If this is the first use of a target-specific macro, warn about it.
1870 if (MI->isTargetSpecific()) {
1871 MI->setIsTargetSpecific(false); // Don't warn on second use.
1872 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1873 diag::port_target_macro_use);
1874 }
Chris Lattner063400e2006-10-14 19:54:15 +00001875 } else {
1876 // Use of a target-specific macro for some other target? If so, warn.
1877 if (MII->isOtherTargetMacro()) {
1878 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1879 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1880 diag::port_target_macro_use);
1881 }
Chris Lattner81278c62006-10-14 19:03:49 +00001882 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001883
Chris Lattner22eb9722006-06-18 05:43:12 +00001884 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001885 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001886 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001887 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001888 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001889 } else {
1890 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001891 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001892 /*Foundnonskip*/false,
1893 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001894 }
1895}
1896
1897/// HandleIfDirective - Implements the #if directive.
1898///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001899void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1900 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001901 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001902
Chris Lattner371ac8a2006-07-04 07:11:10 +00001903 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001904 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001905 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001906
1907 // Should we include the stuff contained by this directive?
1908 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001909 // If this condition is equivalent to #ifndef X, and if this is the first
1910 // directive seen, handle it for the multiple-include optimization.
1911 if (!ReadAnyTokensBeforeDirective &&
1912 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1913 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1914
Chris Lattner22eb9722006-06-18 05:43:12 +00001915 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001916 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001917 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001918 } else {
1919 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001920 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001921 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001922 }
1923}
1924
1925/// HandleEndifDirective - Implements the #endif directive.
1926///
Chris Lattnercb283342006-06-18 06:48:37 +00001927void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001928 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001929
Chris Lattner22eb9722006-06-18 05:43:12 +00001930 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001931 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001932
1933 PPConditionalInfo CondInfo;
1934 if (CurLexer->popConditionalLevel(CondInfo)) {
1935 // No conditionals on the stack: this is an #endif without an #if.
1936 return Diag(EndifToken, diag::err_pp_endif_without_if);
1937 }
1938
Chris Lattner371ac8a2006-07-04 07:11:10 +00001939 // If this the end of a top-level #endif, inform MIOpt.
1940 if (CurLexer->getConditionalStackDepth() == 0)
1941 CurLexer->MIOpt.ExitTopLevelConditional();
1942
Chris Lattner538d7f32006-07-20 04:31:52 +00001943 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001944 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001945}
1946
1947
Chris Lattnercb283342006-06-18 06:48:37 +00001948void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001949 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001950
Chris Lattner22eb9722006-06-18 05:43:12 +00001951 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001952 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001953
1954 PPConditionalInfo CI;
1955 if (CurLexer->popConditionalLevel(CI))
1956 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001957
1958 // If this is a top-level #else, inform the MIOpt.
1959 if (CurLexer->getConditionalStackDepth() == 0)
1960 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001961
1962 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001963 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001964
1965 // Finally, skip the rest of the contents of this block and return the first
1966 // token after it.
1967 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1968 /*FoundElse*/true);
1969}
1970
Chris Lattnercb283342006-06-18 06:48:37 +00001971void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001972 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001973
Chris Lattner22eb9722006-06-18 05:43:12 +00001974 // #elif directive in a non-skipping conditional... start skipping.
1975 // We don't care what the condition is, because we will always skip it (since
1976 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001977 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001978
1979 PPConditionalInfo CI;
1980 if (CurLexer->popConditionalLevel(CI))
1981 return Diag(ElifToken, diag::pp_err_elif_without_if);
1982
Chris Lattner371ac8a2006-07-04 07:11:10 +00001983 // If this is a top-level #elif, inform the MIOpt.
1984 if (CurLexer->getConditionalStackDepth() == 0)
1985 CurLexer->MIOpt.FoundTopLevelElse();
1986
Chris Lattner22eb9722006-06-18 05:43:12 +00001987 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001988 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001989
1990 // Finally, skip the rest of the contents of this block and return the first
1991 // token after it.
1992 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1993 /*FoundElse*/CI.FoundElse);
1994}
Chris Lattnerb8761832006-06-24 21:31:03 +00001995