blob: 661785c1b8bf2d26c0ea144a3638814279f5c120 [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"
Chris Lattner07b019a2006-10-22 07:28:56 +000029#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000030#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000031#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000032#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000033#include "clang/Basic/Diagnostic.h"
34#include "clang/Basic/FileManager.h"
35#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000036#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000037#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000038#include <iostream>
39using namespace llvm;
40using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
Chris Lattner02dffbd2006-10-14 07:50:21 +000044Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
45 TargetInfo &target,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000046 FileManager &FM, SourceManager &SM,
47 HeaderSearch &Headers)
Chris Lattner02dffbd2006-10-14 07:50:21 +000048 : Diags(diags), Features(opts), Target(target), FileMgr(FM), SourceMgr(SM),
Chris Lattner25e0d542006-10-18 06:07:05 +000049 HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerc8997182006-06-22 05:52:16 +000050 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000051 ScratchBuf = new ScratchBuffer(SourceMgr);
52
Chris Lattner22eb9722006-06-18 05:43:12 +000053 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000054 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000055 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000056 NumEnteredSourceFiles = 0;
57 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000058 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000059 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000061
Chris Lattner22eb9722006-06-18 05:43:12 +000062 // Macro expansion is enabled.
63 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000064 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000065
66 // There is no file-change handler yet.
67 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000068 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000069
Chris Lattner8ff71992006-07-06 05:17:39 +000070 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
71 // This gets unpoisoned where it is allowed.
72 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
73
Chris Lattnerb8761832006-06-24 21:31:03 +000074 // Initialize the pragma handlers.
75 PragmaHandlers = new PragmaNamespace(0);
76 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000077
78 // Initialize builtin macros like __LINE__ and friends.
79 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000080}
81
82Preprocessor::~Preprocessor() {
83 // Free any active lexers.
84 delete CurLexer;
85
Chris Lattner69772b02006-07-02 20:34:39 +000086 while (!IncludeMacroStack.empty()) {
87 delete IncludeMacroStack.back().TheLexer;
88 delete IncludeMacroStack.back().TheMacroExpander;
89 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000090 }
Chris Lattnerb8761832006-06-24 21:31:03 +000091
92 // Release pragma information.
93 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000094
95 // Delete the scratch buffer info.
96 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000097}
98
Chris Lattner87d3bec2006-10-17 03:44:32 +000099
100
Chris Lattner22eb9722006-06-18 05:43:12 +0000101/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
102/// the specified LexerToken's location, translating the token's start
103/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000104void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000105 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000106 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000107}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000108
109void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
110 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
111 << getSpelling(Tok) << "'";
112
113 if (!DumpFlags) return;
114 std::cerr << "\t";
115 if (Tok.isAtStartOfLine())
116 std::cerr << " [StartOfLine]";
117 if (Tok.hasLeadingSpace())
118 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000119 if (Tok.isExpandDisabled())
120 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000121 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000122 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000123 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
124 << "']";
125 }
126}
127
128void Preprocessor::DumpMacro(const MacroInfo &MI) const {
129 std::cerr << "MACRO: ";
130 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
131 DumpToken(MI.getReplacementToken(i));
132 std::cerr << " ";
133 }
134 std::cerr << "\n";
135}
136
Chris Lattner22eb9722006-06-18 05:43:12 +0000137void Preprocessor::PrintStats() {
138 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000139 std::cerr << NumDirectives << " directives found:\n";
140 std::cerr << " " << NumDefined << " #define.\n";
141 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000142 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000143 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
144 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
145 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
146 std::cerr << " " << NumElse << " #else/#elif.\n";
147 std::cerr << " " << NumEndif << " #endif.\n";
148 std::cerr << " " << NumPragma << " #pragma.\n";
149 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
150
Chris Lattner78186052006-07-09 00:45:31 +0000151 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
152 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000153 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000154 std::cerr << (NumFastTokenPaste+NumTokenPaste)
155 << " token paste (##) operations performed, "
156 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000157}
158
159//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000160// Token Spelling
161//===----------------------------------------------------------------------===//
162
163
164/// getSpelling() - Return the 'spelling' of this token. The spelling of a
165/// token are the characters used to represent the token in the source file
166/// after trigraph expansion and escaped-newline folding. In particular, this
167/// wants to get the true, uncanonicalized, spelling of things like digraphs
168/// UCNs, etc.
169std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
170 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
171
172 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000173 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000174 if (!Tok.needsCleaning())
175 return std::string(TokStart, TokStart+Tok.getLength());
176
Chris Lattnerd01e2912006-06-18 16:22:51 +0000177 std::string Result;
178 Result.reserve(Tok.getLength());
179
Chris Lattneref9eae12006-07-04 22:33:12 +0000180 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000181 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
182 Ptr != End; ) {
183 unsigned CharSize;
184 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
185 Ptr += CharSize;
186 }
187 assert(Result.size() != unsigned(Tok.getLength()) &&
188 "NeedsCleaning flag set on something that didn't need cleaning!");
189 return Result;
190}
191
192/// getSpelling - This method is used to get the spelling of a token into a
193/// preallocated buffer, instead of as an std::string. The caller is required
194/// to allocate enough space for the token, which is guaranteed to be at least
195/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000196///
197/// Note that this method may do two possible things: it may either fill in
198/// the buffer specified with characters, or it may *change the input pointer*
199/// to point to a constant buffer with the data already in it (avoiding a
200/// copy). The caller is not allowed to modify the returned buffer pointer
201/// if an internal buffer is returned.
202unsigned Preprocessor::getSpelling(const LexerToken &Tok,
203 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000204 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
205
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000206 // If this token is an identifier, just return the string from the identifier
207 // table, which is very quick.
208 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
209 Buffer = II->getName();
210 return Tok.getLength();
211 }
212
213 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000214 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000215
216 // If this token contains nothing interesting, return it directly.
217 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000218 Buffer = TokStart;
219 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220 }
221 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000222 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000223 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
224 Ptr != End; ) {
225 unsigned CharSize;
226 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
227 Ptr += CharSize;
228 }
229 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
230 "NeedsCleaning flag set on something that didn't need cleaning!");
231
232 return OutBuf-Buffer;
233}
234
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000235
236/// CreateString - Plop the specified string into a scratch buffer and return a
237/// location for it. If specified, the source location provides a source
238/// location for the token.
239SourceLocation Preprocessor::
240CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
241 if (SLoc.isValid())
242 return ScratchBuf->getToken(Buf, Len, SLoc);
243 return ScratchBuf->getToken(Buf, Len);
244}
245
246
Chris Lattnerd01e2912006-06-18 16:22:51 +0000247//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000248// Source File Location Methods.
249//===----------------------------------------------------------------------===//
250
Chris Lattner22eb9722006-06-18 05:43:12 +0000251/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
252/// return null on failure. isAngled indicates whether the file reference is
253/// for system #include's or not (i.e. using <> instead of "").
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000254const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000255 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000256 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000257 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000258 // If the header lookup mechanism may be relative to the current file, pass in
259 // info about where the current file is.
260 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000261 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000262 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000263 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000264 }
265
Chris Lattner7cdbad92006-10-30 05:33:15 +0000266 const char *FilenameStart = &Filename[0];
267 const char *FilenameEnd = FilenameStart+Filename.size();
268
Chris Lattner63dd32b2006-10-20 04:42:40 +0000269 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000270 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000271 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000272 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
273 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000274 if (FE) return FE;
275
276 // Otherwise, see if this is a subframework header. If so, this is relative
277 // to one of the headers on the #include stack. Walk the list of the current
278 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000279 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000280 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000281 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
282 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000283 return FE;
284 }
285
286 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
287 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000288 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000289 CurFileEnt =
290 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000291 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
292 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000293 return FE;
294 }
295 }
296
297 // Otherwise, we really couldn't find the file.
298 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000299}
300
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000301/// isInPrimaryFile - Return true if we're in the top-level file, not in a
302/// #include.
303bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000304 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000305 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000306
Chris Lattner13044d92006-07-03 05:16:44 +0000307 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000308 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000309 if (IncludeMacroStack[i].TheLexer &&
310 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
311 return IncludeMacroStack[i].TheLexer->isMainFile();
312 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000313}
314
315/// getCurrentLexer - Return the current file lexer being lexed from. Note
316/// that this ignores any potentially active macro expansions and _Pragma
317/// expansions going on at the time.
318Lexer *Preprocessor::getCurrentFileLexer() const {
319 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
320
321 // Look for a stacked lexer.
322 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000323 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000324 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
325 return L;
326 }
327 return 0;
328}
329
330
Chris Lattner22eb9722006-06-18 05:43:12 +0000331/// EnterSourceFile - Add a source file to the top of the include stack and
332/// start lexing tokens from it instead of the current buffer. Return true
333/// on failure.
334void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000335 const DirectoryLookup *CurDir,
336 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000337 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000338 ++NumEnteredSourceFiles;
339
Chris Lattner69772b02006-07-02 20:34:39 +0000340 if (MaxIncludeStackDepth < IncludeMacroStack.size())
341 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000342
Chris Lattner22eb9722006-06-18 05:43:12 +0000343 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000344 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000345 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000346 EnterSourceFileWithLexer(TheLexer, CurDir);
347}
Chris Lattner22eb9722006-06-18 05:43:12 +0000348
Chris Lattner69772b02006-07-02 20:34:39 +0000349/// EnterSourceFile - Add a source file to the top of the include stack and
350/// start lexing tokens from it instead of the current buffer.
351void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
352 const DirectoryLookup *CurDir) {
353
354 // Add the current lexer to the include stack.
355 if (CurLexer || CurMacroExpander)
356 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
357 CurMacroExpander));
358
359 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000360 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000361 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000362
363 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000364 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000365 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
366
367 // Get the file entry for the current file.
368 if (const FileEntry *FE =
369 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000370 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000371
Chris Lattner1840e492006-07-02 22:30:01 +0000372 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000373 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000374 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000375}
376
Chris Lattner69772b02006-07-02 20:34:39 +0000377
378
Chris Lattner22eb9722006-06-18 05:43:12 +0000379/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000380/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000381void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000382 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
383 CurMacroExpander));
384 CurLexer = 0;
385 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000386
Chris Lattneree8760b2006-07-15 07:42:55 +0000387 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000388}
389
Chris Lattner7667d0d2006-07-16 18:16:58 +0000390/// EnterTokenStream - Add a "macro" context to the top of the include stack,
391/// which will cause the lexer to start returning the specified tokens. Note
392/// that these tokens will be re-macro-expanded when/if expansion is enabled.
393/// This method assumes that the specified stream of tokens has a permanent
394/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000395void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000396 // Save our current state.
397 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
398 CurMacroExpander));
399 CurLexer = 0;
400 CurDirLookup = 0;
401
402 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000403 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000404}
405
406/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
407/// lexer stack. This should only be used in situations where the current
408/// state of the top-of-stack lexer is known.
409void Preprocessor::RemoveTopOfLexerStack() {
410 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
411 delete CurLexer;
412 delete CurMacroExpander;
413 CurLexer = IncludeMacroStack.back().TheLexer;
414 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
415 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
416 IncludeMacroStack.pop_back();
417}
418
Chris Lattner22eb9722006-06-18 05:43:12 +0000419//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000420// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000421//===----------------------------------------------------------------------===//
422
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000423/// RegisterBuiltinMacro - Register the specified identifier in the identifier
424/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000425IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000426 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000427 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000428
429 // Mark it as being a macro that is builtin.
430 MacroInfo *MI = new MacroInfo(SourceLocation());
431 MI->setIsBuiltinMacro();
432 Id->setMacroInfo(MI);
433 return Id;
434}
435
436
Chris Lattner677757a2006-06-28 05:26:32 +0000437/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
438/// identifier table.
439void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000440 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000441 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000442 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
443 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000444 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000445
446 // GCC Extensions.
447 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
448 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000449 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000450}
451
Chris Lattnerc2395832006-07-09 00:57:04 +0000452/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
453/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000454static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
455 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000456 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
457
458 // If the token isn't an identifier, it's always literally expanded.
459 if (II == 0) return true;
460
461 // If the identifier is a macro, and if that macro is enabled, it may be
462 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000463 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
464 // Fast expanding "#define X X" is ok, because X would be disabled.
465 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000466 return false;
467
468 // If this is an object-like macro invocation, it is safe to trivially expand
469 // it.
470 if (MI->isObjectLike()) return true;
471
472 // If this is a function-like macro invocation, it's safe to trivially expand
473 // as long as the identifier is not a macro argument.
474 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
475 I != E; ++I)
476 if (*I == II)
477 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000478
Chris Lattnerc2395832006-07-09 00:57:04 +0000479 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000480}
481
Chris Lattnerc2395832006-07-09 00:57:04 +0000482
Chris Lattnerafe603f2006-07-11 04:02:46 +0000483/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
484/// lexed is a '('. If so, consume the token and return true, if not, this
485/// method should have no observable side-effect on the lexed tokens.
486bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000487 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000488 unsigned Val;
489 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000490 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000491 else
492 Val = CurMacroExpander->isNextTokenLParen();
493
494 if (Val == 2) {
495 // If we ran off the end of the lexer or macro expander, walk the include
496 // stack, looking for whatever will return the next token.
497 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
498 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
499 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000500 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000501 else
502 Val = Entry.TheMacroExpander->isNextTokenLParen();
503 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000504 }
505
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000506 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
507 // have found something that isn't a '(' or we found the end of the
508 // translation unit. In either case, return false.
509 if (Val != 1)
510 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000511
512 LexerToken Tok;
513 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000514 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
515 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000516}
Chris Lattner677757a2006-06-28 05:26:32 +0000517
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000518/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
519/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000520bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000521 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000522
523 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
524 if (MI->isBuiltinMacro()) {
525 ExpandBuiltinMacro(Identifier);
526 return false;
527 }
528
Chris Lattner81278c62006-10-14 19:03:49 +0000529 // If this is the first use of a target-specific macro, warn about it.
530 if (MI->isTargetSpecific()) {
531 MI->setIsTargetSpecific(false); // Don't warn on second use.
532 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
533 diag::port_target_macro_use);
534 }
535
Chris Lattneree8760b2006-07-15 07:42:55 +0000536 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000537 /// for each macro argument, the list of tokens that were provided to the
538 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000539 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000540
541 // If this is a function-like macro, read the arguments.
542 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000543 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
544 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000545 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000546 return true;
547
Chris Lattner78186052006-07-09 00:45:31 +0000548 // Remember that we are now parsing the arguments to a macro invocation.
549 // Preprocessor directives used inside macro arguments are not portable, and
550 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000551 InMacroArgs = true;
552 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000553
554 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000555 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000556
557 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000558 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000559
560 ++NumFnMacroExpanded;
561 } else {
562 ++NumMacroExpanded;
563 }
Chris Lattner13044d92006-07-03 05:16:44 +0000564
565 // Notice that this macro has been used.
566 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000567
568 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000569
570 // If this macro expands to no tokens, don't bother to push it onto the
571 // expansion stack, only to take it right back off.
572 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000573 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000574 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000575
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000576 // Ignore this macro use, just return the next token in the current
577 // buffer.
578 bool HadLeadingSpace = Identifier.hasLeadingSpace();
579 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
580
581 Lex(Identifier);
582
583 // If the identifier isn't on some OTHER line, inherit the leading
584 // whitespace/first-on-a-line property of this token. This handles
585 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
586 // empty.
587 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000588 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
589 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000590 }
591 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000592 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000593
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000594 } else if (MI->getNumTokens() == 1 &&
595 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000596 // Otherwise, if this macro expands into a single trivially-expanded
597 // token: expand it now. This handles common cases like
598 // "#define VAL 42".
599
600 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
601 // identifier to the expanded token.
602 bool isAtStartOfLine = Identifier.isAtStartOfLine();
603 bool hasLeadingSpace = Identifier.hasLeadingSpace();
604
605 // Remember where the token is instantiated.
606 SourceLocation InstantiateLoc = Identifier.getLocation();
607
608 // Replace the result token.
609 Identifier = MI->getReplacementToken(0);
610
611 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000612 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
613 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000614
615 // Update the tokens location to include both its logical and physical
616 // locations.
617 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000618 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000619 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000620
Chris Lattner6e4bf522006-07-27 06:59:25 +0000621 // If this is #define X X, we must mark the result as unexpandible.
622 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
623 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000624 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000625
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000626 // Since this is not an identifier token, it can't be macro expanded, so
627 // we're done.
628 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000629 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000630 }
631
Chris Lattner78186052006-07-09 00:45:31 +0000632 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000633 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000634
635 // Now that the macro is at the top of the include stack, ask the
636 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000637 Lex(Identifier);
638 return false;
639}
640
Chris Lattneree8760b2006-07-15 07:42:55 +0000641/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000642/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000643/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000644MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
645 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000646 // The number of fixed arguments to parse.
647 unsigned NumFixedArgsLeft = MI->getNumArgs();
648 bool isVariadic = MI->isVariadic();
649
Chris Lattner78186052006-07-09 00:45:31 +0000650 // Outer loop, while there are more arguments, keep reading them.
651 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000652 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000653 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000654
655 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000656 // argument is separated by an EOF token. Use a SmallVector so we can avoid
657 // heap allocations in the common case.
658 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000659
660 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000661 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000662 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
663 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000664
Chris Lattner78186052006-07-09 00:45:31 +0000665 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000666 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
667 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000668 LexUnexpandedToken(Tok);
669
670 if (Tok.getKind() == tok::eof) {
671 Diag(MacroName, diag::err_unterm_macro_invoc);
672 // Do not lose the EOF. Return it to the client.
673 MacroName = Tok;
674 return 0;
675 } else if (Tok.getKind() == tok::r_paren) {
676 // If we found the ) token, the macro arg list is done.
677 if (NumParens-- == 0)
678 break;
679 } else if (Tok.getKind() == tok::l_paren) {
680 ++NumParens;
681 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
682 // Comma ends this argument if there are more fixed arguments expected.
683 if (NumFixedArgsLeft)
684 break;
685
Chris Lattner2ada5d32006-07-15 07:51:24 +0000686 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000687 if (!isVariadic) {
688 // Emit the diagnostic at the macro name in case there is a missing ).
689 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000690 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000691 return 0;
692 }
693 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000694 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
695 // If this is a comment token in the argument list and we're just in
696 // -C mode (not -CC mode), discard the comment.
697 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000698 }
699
700 ArgTokens.push_back(Tok);
701 }
702
Chris Lattnera12dd152006-07-11 04:09:02 +0000703 // Empty arguments are standard in C99 and supported as an extension in
704 // other modes.
705 if (ArgTokens.empty() && !Features.C99)
706 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000707
Chris Lattner36b6e812006-07-21 06:38:30 +0000708 // Add a marker EOF token to the end of the token list for this argument.
709 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000710 EOFTok.startToken();
711 EOFTok.setKind(tok::eof);
712 EOFTok.setLocation(Tok.getLocation());
713 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000714 ArgTokens.push_back(EOFTok);
715 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000716 --NumFixedArgsLeft;
717 };
718
719 // Okay, we either found the r_paren. Check to see if we parsed too few
720 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000721 unsigned MinArgsExpected = MI->getNumArgs();
722
Chris Lattner775d8322006-07-29 04:39:41 +0000723 // See MacroArgs instance var for description of this.
724 bool isVarargsElided = false;
725
Chris Lattner2ada5d32006-07-15 07:51:24 +0000726 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000727 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000728 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000729 // Varargs where the named vararg parameter is missing: ok as extension.
730 // #define A(x, ...)
731 // A("blah")
732 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000733
734 // Remember this occurred if this is a C99 macro invocation with at least
735 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000736 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000737 } else if (MI->getNumArgs() == 1) {
738 // #define A(x)
739 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000740 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000741
742 // Empty arguments are standard in C99 and supported as an extension in
743 // other modes.
744 if (ArgTokens.empty() && !Features.C99)
745 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000746 } else {
747 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000748 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000749 return 0;
750 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000751
752 // Add a marker EOF token to the end of the token list for this argument.
753 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000754 Tok.startToken();
755 Tok.setKind(tok::eof);
756 Tok.setLocation(EndLoc);
757 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000758 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000759 }
760
Chris Lattner775d8322006-07-29 04:39:41 +0000761 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000762}
763
Chris Lattnerc673f902006-06-30 06:10:41 +0000764/// ComputeDATE_TIME - Compute the current time, enter it into the specified
765/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
766/// the identifier tokens inserted.
767static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000768 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000769 time_t TT = time(0);
770 struct tm *TM = localtime(&TT);
771
772 static const char * const Months[] = {
773 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
774 };
775
776 char TmpBuffer[100];
777 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
778 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000779 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000780
781 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000782 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000783}
784
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000785/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
786/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000787void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000788 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000789 IdentifierInfo *II = Tok.getIdentifierInfo();
790 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000791
792 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
793 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000794 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000795 return Handle_Pragma(Tok);
796
Chris Lattner78186052006-07-09 00:45:31 +0000797 ++NumBuiltinMacroExpanded;
798
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000799 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000800
801 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000802 Tok.setIdentifierInfo(0);
803 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000804
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000805 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000806 // __LINE__ expands to a simple numeric value.
807 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
808 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000809 Tok.setKind(tok::numeric_constant);
810 Tok.setLength(Length);
811 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000812 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000813 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000814 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000815 Diag(Tok, diag::ext_pp_base_file);
816 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
817 while (NextLoc.getFileID() != 0) {
818 Loc = NextLoc;
819 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
820 }
821 }
822
Chris Lattner0766e592006-07-03 01:07:01 +0000823 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
824 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000825 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000826 Tok.setKind(tok::string_literal);
827 Tok.setLength(FN.size());
828 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000829 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000830 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000831 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000832 Tok.setKind(tok::string_literal);
833 Tok.setLength(strlen("\"Mmm dd yyyy\""));
834 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000835 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000836 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000837 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000838 Tok.setKind(tok::string_literal);
839 Tok.setLength(strlen("\"hh:mm:ss\""));
840 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000841 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000842 Diag(Tok, diag::ext_pp_include_level);
843
844 // Compute the include depth of this token.
845 unsigned Depth = 0;
846 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
847 for (; Loc.getFileID() != 0; ++Depth)
848 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
849
850 // __INCLUDE_LEVEL__ expands to a simple numeric value.
851 sprintf(TmpBuffer, "%u", Depth);
852 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000853 Tok.setKind(tok::numeric_constant);
854 Tok.setLength(Length);
855 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000856 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000857 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
858 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
859 Diag(Tok, diag::ext_pp_timestamp);
860
861 // Get the file that we are lexing out of. If we're currently lexing from
862 // a macro, dig into the include stack.
863 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000864 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000865
866 if (TheLexer)
867 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
868
869 // If this file is older than the file it depends on, emit a diagnostic.
870 const char *Result;
871 if (CurFile) {
872 time_t TT = CurFile->getModificationTime();
873 struct tm *TM = localtime(&TT);
874 Result = asctime(TM);
875 } else {
876 Result = "??? ??? ?? ??:??:?? ????\n";
877 }
878 TmpBuffer[0] = '"';
879 strcpy(TmpBuffer+1, Result);
880 unsigned Len = strlen(TmpBuffer);
881 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000882 Tok.setKind(tok::string_literal);
883 Tok.setLength(Len);
884 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000885 } else {
886 assert(0 && "Unknown identifier!");
887 }
888}
Chris Lattner677757a2006-06-28 05:26:32 +0000889
Chris Lattner13044d92006-07-03 05:16:44 +0000890namespace {
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000891struct UnusedIdentifierReporter : public CStringMapVisitor {
Chris Lattner13044d92006-07-03 05:16:44 +0000892 Preprocessor &PP;
893 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
894
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000895 void Visit(const char *Key, void *Value) const {
896 IdentifierInfo &II = *static_cast<IdentifierInfo*>(Value);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000897 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
898 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000899 }
900};
901}
902
Chris Lattner677757a2006-06-28 05:26:32 +0000903//===----------------------------------------------------------------------===//
904// Lexer Event Handling.
905//===----------------------------------------------------------------------===//
906
Chris Lattnercefc7682006-07-08 08:28:12 +0000907/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
908/// identifier information for the token and install it into the token.
909IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
910 const char *BufPtr) {
911 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
912 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
913
914 // Look up this token, see if it is a macro, or if it is a language keyword.
915 IdentifierInfo *II;
916 if (BufPtr && !Identifier.needsCleaning()) {
917 // No cleaning needed, just use the characters from the lexed buffer.
918 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
919 } else {
920 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
921 const char *TmpBuf = (char*)alloca(Identifier.getLength());
922 unsigned Size = getSpelling(Identifier, TmpBuf);
923 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
924 }
Chris Lattner8c204872006-10-14 05:19:21 +0000925 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000926 return II;
927}
928
929
Chris Lattner677757a2006-06-28 05:26:32 +0000930/// HandleIdentifier - This callback is invoked when the lexer reads an
931/// identifier. This callback looks up the identifier in the map and/or
932/// potentially macro expands it or turns it into a named token (like 'for').
933void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000934 assert(Identifier.getIdentifierInfo() &&
935 "Can't handle identifiers without identifier info!");
936
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000937 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000938
939 // If this identifier was poisoned, and if it was not produced from a macro
940 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000941 if (II.isPoisoned() && CurLexer) {
942 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
943 Diag(Identifier, diag::err_pp_used_poisoned_id);
944 else
945 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
946 }
Chris Lattner677757a2006-06-28 05:26:32 +0000947
Chris Lattner78186052006-07-09 00:45:31 +0000948 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000949 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000950 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
951 if (MI->isEnabled()) {
952 if (!HandleMacroExpandedIdentifier(Identifier, MI))
953 return;
954 } else {
955 // C99 6.10.3.4p2 says that a disabled macro may never again be
956 // expanded, even if it's in a context where it could be expanded in the
957 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000958 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000959 }
960 }
Chris Lattner063400e2006-10-14 19:54:15 +0000961 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
962 // If this identifier is a macro on some other target, emit a diagnostic.
963 // This diagnosic is only emitted when macro expansion is enabled, because
964 // the macro would not have been expanded for the other target either.
965 II.setIsOtherTargetMacro(false); // Don't warn on second use.
966 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
967 diag::port_target_macro_use);
968
969 }
Chris Lattner677757a2006-06-28 05:26:32 +0000970
971 // Change the kind of this identifier to the appropriate token kind, e.g.
972 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000973 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000974
975 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000976 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000977}
978
Chris Lattner22eb9722006-06-18 05:43:12 +0000979/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
980/// the current file. This either returns the EOF token or pops a level off
981/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000982bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000983 assert(!CurMacroExpander &&
984 "Ending a file when currently in a macro!");
985
Chris Lattner371ac8a2006-07-04 07:11:10 +0000986 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000987 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000988 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000989 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000990 // Okay, this has a controlling macro, remember in PerFileInfo.
991 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000992 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
993 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000994 }
995 }
996
Chris Lattner22eb9722006-06-18 05:43:12 +0000997 // If this is a #include'd file, pop it off the include stack and continue
998 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000999 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001000 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001001 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001002
1003 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001004 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001005 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1006
1007 // Get the file entry for the current file.
1008 if (const FileEntry *FE =
1009 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001010 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001011
Chris Lattner0c885f52006-06-21 06:50:18 +00001012 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001013 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001014 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001015
1016 // Client should lex another token.
1017 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001018 }
1019
Chris Lattner8c204872006-10-14 05:19:21 +00001020 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001021 CurLexer->BufferPtr = CurLexer->BufferEnd;
1022 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001023 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001024
1025 // We're done with the #included file.
1026 delete CurLexer;
1027 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001028
Chris Lattner03f83482006-07-10 06:16:26 +00001029 // This is the end of the top-level file. If the diag::pp_macro_not_used
1030 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1031 // have not been used.
1032 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1033 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001034
1035 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001036}
1037
1038/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001039/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001040bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001041 assert(CurMacroExpander && !CurLexer &&
1042 "Ending a macro when currently in a #include file!");
1043
Chris Lattner22eb9722006-06-18 05:43:12 +00001044 delete CurMacroExpander;
1045
Chris Lattner69772b02006-07-02 20:34:39 +00001046 // Handle this like a #include file being popped off the stack.
1047 CurMacroExpander = 0;
1048 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001049}
1050
1051
1052//===----------------------------------------------------------------------===//
1053// Utility Methods for Preprocessor Directive Handling.
1054//===----------------------------------------------------------------------===//
1055
1056/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1057/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001058void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001059 LexerToken Tmp;
1060 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001061 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001062 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001063}
1064
1065/// ReadMacroName - Lex and validate a macro name, which occurs after a
1066/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001067/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1068/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001069/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001070void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001071 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001072 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001073
1074 // Missing macro name?
1075 if (MacroNameTok.getKind() == tok::eom)
1076 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1077
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001078 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1079 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001080 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001081 // Fall through on error.
1082 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001083 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001084
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001085 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1086 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001087 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001088 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001089 } else if (isDefineUndef && II->getMacroInfo() &&
1090 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001091 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001092 if (isDefineUndef == 1)
1093 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1094 else
1095 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001096 } else {
1097 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001098 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001099 }
1100
Chris Lattner22eb9722006-06-18 05:43:12 +00001101 // Invalid macro name, read and discard the rest of the line. Then set the
1102 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001103 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001104 return DiscardUntilEndOfDirective();
1105}
1106
1107/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1108/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001109void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001110 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001111 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001112 // There should be no tokens after the directive, but we allow them as an
1113 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001114 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1115 Lex(Tmp);
1116
Chris Lattner22eb9722006-06-18 05:43:12 +00001117 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001118 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1119 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001120 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001121}
1122
1123
1124
1125/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1126/// decided that the subsequent tokens are in the #if'd out portion of the
1127/// file. Lex the rest of the file, until we see an #endif. If
1128/// FoundNonSkipPortion is true, then we have already emitted code for part of
1129/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1130/// is true, then #else directives are ok, if not, then we have already seen one
1131/// so a #else directive is a duplicate. When this returns, the caller can lex
1132/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001133void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001134 bool FoundNonSkipPortion,
1135 bool FoundElse) {
1136 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001137 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001138 "Lexing a macro, not a file?");
1139
1140 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1141 FoundNonSkipPortion, FoundElse);
1142
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001143 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1144 // disabling warnings, etc.
1145 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001146 LexerToken Tok;
1147 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001148 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001149
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001150 // If this is the end of the buffer, we have an error.
1151 if (Tok.getKind() == tok::eof) {
1152 // Emit errors for each unterminated conditional on the stack, including
1153 // the current one.
1154 while (!CurLexer->ConditionalStack.empty()) {
1155 Diag(CurLexer->ConditionalStack.back().IfLoc,
1156 diag::err_pp_unterminated_conditional);
1157 CurLexer->ConditionalStack.pop_back();
1158 }
1159
1160 // Just return and let the caller lex after this #include.
1161 break;
1162 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001163
1164 // If this token is not a preprocessor directive, just skip it.
1165 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1166 continue;
1167
1168 // We just parsed a # character at the start of a line, so we're in
1169 // directive mode. Tell the lexer this so any newlines we see will be
1170 // converted into an EOM token (this terminates the macro).
1171 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001172 CurLexer->KeepCommentMode = false;
1173
Chris Lattner22eb9722006-06-18 05:43:12 +00001174
1175 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001176 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001177
1178 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1179 // something bogus), skip it.
1180 if (Tok.getKind() != tok::identifier) {
1181 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001182 // Restore comment saving mode.
1183 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001184 continue;
1185 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001186
Chris Lattner22eb9722006-06-18 05:43:12 +00001187 // If the first letter isn't i or e, it isn't intesting to us. We know that
1188 // this is safe in the face of spelling differences, because there is no way
1189 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001190 // allows us to avoid looking up the identifier info for #define/#undef and
1191 // other common directives.
1192 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1193 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001194 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1195 FirstChar != 'i' && FirstChar != 'e') {
1196 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001197 // Restore comment saving mode.
1198 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001199 continue;
1200 }
1201
Chris Lattnere60165f2006-06-22 06:36:29 +00001202 // Get the identifier name without trigraphs or embedded newlines. Note
1203 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1204 // when skipping.
1205 // TODO: could do this with zero copies in the no-clean case by using
1206 // strncmp below.
1207 char Directive[20];
1208 unsigned IdLen;
1209 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1210 IdLen = Tok.getLength();
1211 memcpy(Directive, RawCharData, IdLen);
1212 Directive[IdLen] = 0;
1213 } else {
1214 std::string DirectiveStr = getSpelling(Tok);
1215 IdLen = DirectiveStr.size();
1216 if (IdLen >= 20) {
1217 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001218 // Restore comment saving mode.
1219 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001220 continue;
1221 }
1222 memcpy(Directive, &DirectiveStr[0], IdLen);
1223 Directive[IdLen] = 0;
1224 }
1225
Chris Lattner22eb9722006-06-18 05:43:12 +00001226 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001227 if ((IdLen == 2) || // "if"
1228 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1229 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001230 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1231 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001232 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001233 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001234 /*foundnonskip*/false,
1235 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001236 }
1237 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001238 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001239 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001240 PPConditionalInfo CondInfo;
1241 CondInfo.WasSkipping = true; // Silence bogus warning.
1242 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1243 assert(!InCond && "Can't be skipping if not in a conditional!");
1244
1245 // If we popped the outermost skipping block, we're done skipping!
1246 if (!CondInfo.WasSkipping)
1247 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001248 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001249 // #else directive in a skipping conditional. If not in some other
1250 // skipping conditional, and if #else hasn't already been seen, enter it
1251 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001252 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001253 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1254
1255 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001256 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001257
1258 // Note that we've seen a #else in this conditional.
1259 CondInfo.FoundElse = true;
1260
1261 // If the conditional is at the top level, and the #if block wasn't
1262 // entered, enter the #else block now.
1263 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1264 CondInfo.FoundNonSkip = true;
1265 break;
1266 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001267 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001268 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1269
1270 bool ShouldEnter;
1271 // If this is in a skipping block or if we're already handled this #if
1272 // block, don't bother parsing the condition.
1273 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001274 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001275 ShouldEnter = false;
1276 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001277 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001278 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001279 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1280 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001281 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001282 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001283 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001284 }
1285
1286 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001287 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001288
1289 // If this condition is true, enter it!
1290 if (ShouldEnter) {
1291 CondInfo.FoundNonSkip = true;
1292 break;
1293 }
1294 }
1295 }
1296
1297 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001298 // Restore comment saving mode.
1299 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001300 }
1301
1302 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1303 // of the file, just stop skipping and return to lexing whatever came after
1304 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001305 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001306}
1307
1308//===----------------------------------------------------------------------===//
1309// Preprocessor Directive Handling.
1310//===----------------------------------------------------------------------===//
1311
1312/// HandleDirective - This callback is invoked when the lexer sees a # token
1313/// at the start of a line. This consumes the directive, modifies the
1314/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1315/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001316void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001317 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001318
1319 // We just parsed a # character at the start of a line, so we're in directive
1320 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001321 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001322 CurLexer->ParsingPreprocessorDirective = true;
1323
1324 ++NumDirectives;
1325
Chris Lattner371ac8a2006-07-04 07:11:10 +00001326 // We are about to read a token. For the multiple-include optimization FA to
1327 // work, we have to remember if we had read any tokens *before* this
1328 // pp-directive.
1329 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1330
Chris Lattner78186052006-07-09 00:45:31 +00001331 // Read the next token, the directive flavor. This isn't expanded due to
1332 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001333 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001334
Chris Lattner78186052006-07-09 00:45:31 +00001335 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1336 // #define A(x) #x
1337 // A(abc
1338 // #warning blah
1339 // def)
1340 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001341 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001342 Diag(Result, diag::ext_embedded_directive);
1343
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001344TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001346 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001347 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001348 case tok::comment:
1349 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1350 LexUnexpandedToken(Result);
1351 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001352
Chris Lattner22eb9722006-06-18 05:43:12 +00001353 case tok::numeric_constant:
1354 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001355 DiscardUntilEndOfDirective();
1356 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001357 default:
1358 IdentifierInfo *II = Result.getIdentifierInfo();
1359 if (II == 0) break; // Not an identifier.
1360
1361 // Ask what the preprocessor keyword ID is.
1362 switch (II->getPPKeywordID()) {
1363 default: break;
1364 // C99 6.10.1 - Conditional Inclusion.
1365 case tok::pp_if:
1366 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1367 case tok::pp_ifdef:
1368 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1369 case tok::pp_ifndef:
1370 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1371 case tok::pp_elif:
1372 return HandleElifDirective(Result);
1373 case tok::pp_else:
1374 return HandleElseDirective(Result);
1375 case tok::pp_endif:
1376 return HandleEndifDirective(Result);
1377
1378 // C99 6.10.2 - Source File Inclusion.
1379 case tok::pp_include:
1380 return HandleIncludeDirective(Result); // Handle #include.
1381
1382 // C99 6.10.3 - Macro Replacement.
1383 case tok::pp_define:
1384 return HandleDefineDirective(Result, false);
1385 case tok::pp_undef:
1386 return HandleUndefDirective(Result);
1387
1388 // C99 6.10.4 - Line Control.
1389 case tok::pp_line:
1390 // FIXME: implement #line
1391 DiscardUntilEndOfDirective();
1392 return;
1393
1394 // C99 6.10.5 - Error Directive.
1395 case tok::pp_error:
1396 return HandleUserDiagnosticDirective(Result, false);
1397
1398 // C99 6.10.6 - Pragma Directive.
1399 case tok::pp_pragma:
1400 return HandlePragmaDirective();
1401
1402 // GNU Extensions.
1403 case tok::pp_import:
1404 return HandleImportDirective(Result);
1405 case tok::pp_include_next:
1406 return HandleIncludeNextDirective(Result);
1407
1408 case tok::pp_warning:
1409 Diag(Result, diag::ext_pp_warning_directive);
1410 return HandleUserDiagnosticDirective(Result, true);
1411 case tok::pp_ident:
1412 return HandleIdentSCCSDirective(Result);
1413 case tok::pp_sccs:
1414 return HandleIdentSCCSDirective(Result);
1415 case tok::pp_assert:
1416 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001417 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001418 case tok::pp_unassert:
1419 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001420 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001421
1422 // clang extensions.
1423 case tok::pp_define_target:
1424 return HandleDefineDirective(Result, true);
1425 case tok::pp_define_other_target:
1426 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001427 }
1428 break;
1429 }
1430
1431 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001432 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001433
1434 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001435 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001436
1437 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001438}
1439
Chris Lattner01d66cc2006-07-03 22:16:27 +00001440void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001441 bool isWarning) {
1442 // Read the rest of the line raw. We do this because we don't want macros
1443 // to be expanded and we don't require that the tokens be valid preprocessing
1444 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1445 // collapse multiple consequtive white space between tokens, but this isn't
1446 // specified by the standard.
1447 std::string Message = CurLexer->ReadToEndOfLine();
1448
1449 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001450 return Diag(Tok, DiagID, Message);
1451}
1452
1453/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1454///
1455void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001456 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001457 Diag(Tok, diag::ext_pp_ident_directive);
1458
Chris Lattner371ac8a2006-07-04 07:11:10 +00001459 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001460 LexerToken StrTok;
1461 Lex(StrTok);
1462
1463 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001464 if (StrTok.getKind() != tok::string_literal &&
1465 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001466 return Diag(StrTok, diag::err_pp_malformed_ident);
1467
1468 // Verify that there is nothing after the string, other than EOM.
1469 CheckEndOfDirective("#ident");
1470
1471 if (IdentHandler)
1472 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001473}
1474
Chris Lattnerb8761832006-06-24 21:31:03 +00001475//===----------------------------------------------------------------------===//
1476// Preprocessor Include Directive Handling.
1477//===----------------------------------------------------------------------===//
1478
Chris Lattner22eb9722006-06-18 05:43:12 +00001479/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1480/// file to be included from the lexer, then include it! This is a common
1481/// routine with functionality shared between #include, #include_next and
1482/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001483void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001484 const DirectoryLookup *LookupFrom,
1485 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001486
Chris Lattner22eb9722006-06-18 05:43:12 +00001487 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001488 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001489
1490 // If the token kind is EOM, the error has already been diagnosed.
1491 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001492 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001493
1494 // Verify that there is nothing after the filename, other than EOM. Use the
1495 // preprocessor to lex this in case lexing the filename entered a macro.
1496 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001497
1498 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001499 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001500 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1501
Chris Lattner269c2322006-06-25 06:23:00 +00001502 // Find out whether the filename is <x> or "x".
1503 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001504
1505 // Remove the quotes.
1506 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1507
Chris Lattner22eb9722006-06-18 05:43:12 +00001508 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001509 const DirectoryLookup *CurDir;
1510 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001511 if (File == 0)
1512 return Diag(FilenameTok, diag::err_pp_file_not_found);
1513
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001514 // Ask HeaderInfo if we should enter this #include file.
1515 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1516 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001517 return;
1518 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001519
1520 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001521 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001522 if (FileID == 0)
1523 return Diag(FilenameTok, diag::err_pp_file_not_found);
1524
1525 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001526 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001527}
1528
1529/// HandleIncludeNextDirective - Implements #include_next.
1530///
Chris Lattnercb283342006-06-18 06:48:37 +00001531void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1532 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001533
1534 // #include_next is like #include, except that we start searching after
1535 // the current found directory. If we can't do this, issue a
1536 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001537 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001538 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001539 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001540 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001541 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001542 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001543 } else {
1544 // Start looking up in the next directory.
1545 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001546 }
1547
1548 return HandleIncludeDirective(IncludeNextTok, Lookup);
1549}
1550
1551/// HandleImportDirective - Implements #import.
1552///
Chris Lattnercb283342006-06-18 06:48:37 +00001553void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1554 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001555
1556 return HandleIncludeDirective(ImportTok, 0, true);
1557}
1558
Chris Lattnerb8761832006-06-24 21:31:03 +00001559//===----------------------------------------------------------------------===//
1560// Preprocessor Macro Directive Handling.
1561//===----------------------------------------------------------------------===//
1562
Chris Lattnercefc7682006-07-08 08:28:12 +00001563/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1564/// definition has just been read. Lex the rest of the arguments and the
1565/// closing ), updating MI with what we learn. Return true if an error occurs
1566/// parsing the arg list.
1567bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1568 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001569 while (1) {
1570 LexUnexpandedToken(Tok);
1571 switch (Tok.getKind()) {
1572 case tok::r_paren:
1573 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001574 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001575 // Otherwise we have #define FOO(A,)
1576 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1577 return true;
1578 case tok::ellipsis: // #define X(... -> C99 varargs
1579 // Warn if use of C99 feature in non-C99 mode.
1580 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1581
1582 // Lex the token after the identifier.
1583 LexUnexpandedToken(Tok);
1584 if (Tok.getKind() != tok::r_paren) {
1585 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1586 return true;
1587 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001588 // Add the __VA_ARGS__ identifier as an argument.
1589 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001590 MI->setIsC99Varargs();
1591 return false;
1592 case tok::eom: // #define X(
1593 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1594 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001595 default:
1596 // Handle keywords and identifiers here to accept things like
1597 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001598 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001599 if (II == 0) {
1600 // #define X(1
1601 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1602 return true;
1603 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001604
1605 // If this is already used as an argument, it is used multiple times (e.g.
1606 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001607 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001608 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1609 return true;
1610 }
1611
1612 // Add the argument to the macro info.
1613 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001614
1615 // Lex the token after the identifier.
1616 LexUnexpandedToken(Tok);
1617
1618 switch (Tok.getKind()) {
1619 default: // #define X(A B
1620 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1621 return true;
1622 case tok::r_paren: // #define X(A)
1623 return false;
1624 case tok::comma: // #define X(A,
1625 break;
1626 case tok::ellipsis: // #define X(A... -> GCC extension
1627 // Diagnose extension.
1628 Diag(Tok, diag::ext_named_variadic_macro);
1629
1630 // Lex the token after the identifier.
1631 LexUnexpandedToken(Tok);
1632 if (Tok.getKind() != tok::r_paren) {
1633 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1634 return true;
1635 }
1636
1637 MI->setIsGNUVarargs();
1638 return false;
1639 }
1640 }
1641 }
1642}
1643
Chris Lattner22eb9722006-06-18 05:43:12 +00001644/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001645/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1646/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001647///
Chris Lattner81278c62006-10-14 19:03:49 +00001648void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1649 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001650 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001651
Chris Lattner22eb9722006-06-18 05:43:12 +00001652 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001653 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001654
1655 // Error reading macro name? If so, diagnostic already issued.
1656 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001657 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001658
Chris Lattner457fc152006-07-29 06:30:25 +00001659 // If we are supposed to keep comments in #defines, reenable comment saving
1660 // mode.
1661 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1662
Chris Lattner063400e2006-10-14 19:54:15 +00001663 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001664 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001665 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001666
Chris Lattner063400e2006-10-14 19:54:15 +00001667 // If the identifier is an 'other target' macro, clear this bit.
1668 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1669
1670
Chris Lattner22eb9722006-06-18 05:43:12 +00001671 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001672 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001673
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001674 // If this is a function-like macro definition, parse the argument list,
1675 // marking each of the identifiers as being used as macro arguments. Also,
1676 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001677 if (Tok.getKind() == tok::eom) {
1678 // If there is no body to this macro, we have no special handling here.
1679 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001680 // This is a function-like macro definition. Read the argument list.
1681 MI->setIsFunctionLike();
1682 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001683 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001684 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001685 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001686 if (CurLexer->ParsingPreprocessorDirective)
1687 DiscardUntilEndOfDirective();
1688 return;
1689 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001690
Chris Lattner815a1f92006-07-08 20:48:04 +00001691 // Read the first token after the arg list for down below.
1692 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001693 } else if (!Tok.hasLeadingSpace()) {
1694 // C99 requires whitespace between the macro definition and the body. Emit
1695 // a diagnostic for something like "#define X+".
1696 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001697 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001698 } else {
1699 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1700 // one in some cases!
1701 }
1702 } else {
1703 // This is a normal token with leading space. Clear the leading space
1704 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001705 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001706 }
1707
Chris Lattner7e374832006-07-29 03:46:57 +00001708 // If this is a definition of a variadic C99 function-like macro, not using
1709 // the GNU named varargs extension, enabled __VA_ARGS__.
1710
1711 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1712 // This gets unpoisoned where it is allowed.
1713 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1714 if (MI->isC99Varargs())
1715 Ident__VA_ARGS__->setIsPoisoned(false);
1716
Chris Lattner22eb9722006-06-18 05:43:12 +00001717 // Read the rest of the macro body.
1718 while (Tok.getKind() != tok::eom) {
1719 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001720
1721 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001722 // parameters in function-like macro expansions.
1723 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001724 // Get the next token of the macro.
1725 LexUnexpandedToken(Tok);
1726 continue;
1727 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001728
Chris Lattner815a1f92006-07-08 20:48:04 +00001729 // Get the next token of the macro.
1730 LexUnexpandedToken(Tok);
1731
1732 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001733 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001734 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001735 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001736 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001737
1738 // Disable __VA_ARGS__ again.
1739 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001740 return;
1741 }
1742
1743 // Things look ok, add the param name token to the macro.
1744 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001745
Chris Lattner22eb9722006-06-18 05:43:12 +00001746 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001747 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001748 }
Chris Lattner7e374832006-07-29 03:46:57 +00001749
1750 // Disable __VA_ARGS__ again.
1751 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001752
Chris Lattnerbff18d52006-07-06 04:49:18 +00001753 // Check that there is no paste (##) operator at the begining or end of the
1754 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001755 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001756 if (NumTokens != 0) {
1757 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001758 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001759 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001760 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001761 }
1762 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001763 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001764 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001765 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001766 }
1767 }
1768
Chris Lattner13044d92006-07-03 05:16:44 +00001769 // If this is the primary source file, remember that this macro hasn't been
1770 // used yet.
1771 if (isInPrimaryFile())
1772 MI->setIsUsed(false);
1773
Chris Lattner22eb9722006-06-18 05:43:12 +00001774 // Finally, if this identifier already had a macro defined for it, verify that
1775 // the macro bodies are identical and free the old definition.
1776 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001777 if (!OtherMI->isUsed())
1778 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1779
Chris Lattner22eb9722006-06-18 05:43:12 +00001780 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001781 // must be the same. C99 6.10.3.2.
1782 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001783 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1784 MacroNameTok.getIdentifierInfo()->getName());
1785 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1786 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001787 delete OtherMI;
1788 }
1789
1790 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001791}
1792
Chris Lattner063400e2006-10-14 19:54:15 +00001793/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1794void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1795 LexerToken MacroNameTok;
1796 ReadMacroName(MacroNameTok, 1);
1797
1798 // Error reading macro name? If so, diagnostic already issued.
1799 if (MacroNameTok.getKind() == tok::eom)
1800 return;
1801
1802 // Check to see if this is the last token on the #undef line.
1803 CheckEndOfDirective("#define_other_target");
1804
1805 // If there is already a macro defined by this name, turn it into a
1806 // target-specific define.
1807 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1808 MI->setIsTargetSpecific(true);
1809 return;
1810 }
1811
1812 // Mark the identifier as being a macro on some other target.
1813 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1814}
1815
Chris Lattner22eb9722006-06-18 05:43:12 +00001816
1817/// HandleUndefDirective - Implements #undef.
1818///
Chris Lattnercb283342006-06-18 06:48:37 +00001819void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001820 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001821
Chris Lattner22eb9722006-06-18 05:43:12 +00001822 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001823 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001824
1825 // Error reading macro name? If so, diagnostic already issued.
1826 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001827 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001828
1829 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001830 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001831
1832 // Okay, we finally have a valid identifier to undef.
1833 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1834
Chris Lattner063400e2006-10-14 19:54:15 +00001835 // #undef untaints an identifier if it were marked by define_other_target.
1836 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1837
Chris Lattner22eb9722006-06-18 05:43:12 +00001838 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001839 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001840
Chris Lattner13044d92006-07-03 05:16:44 +00001841 if (!MI->isUsed())
1842 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001843
1844 // Free macro definition.
1845 delete MI;
1846 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001847}
1848
1849
Chris Lattnerb8761832006-06-24 21:31:03 +00001850//===----------------------------------------------------------------------===//
1851// Preprocessor Conditional Directive Handling.
1852//===----------------------------------------------------------------------===//
1853
Chris Lattner22eb9722006-06-18 05:43:12 +00001854/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001855/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1856/// if any tokens have been returned or pp-directives activated before this
1857/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001858///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001859void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1860 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001861 ++NumIf;
1862 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001863
Chris Lattner22eb9722006-06-18 05:43:12 +00001864 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001865 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001866
1867 // Error reading macro name? If so, diagnostic already issued.
1868 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001869 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001870
1871 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001872 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1873
1874 // If the start of a top-level #ifdef, inform MIOpt.
1875 if (!ReadAnyTokensBeforeDirective &&
1876 CurLexer->getConditionalStackDepth() == 0) {
1877 assert(isIfndef && "#ifdef shouldn't reach here");
1878 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1879 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001880
Chris Lattner063400e2006-10-14 19:54:15 +00001881 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1882 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001883
Chris Lattner81278c62006-10-14 19:03:49 +00001884 // If there is a macro, process it.
1885 if (MI) {
1886 // Mark it used.
1887 MI->setIsUsed(true);
1888
1889 // If this is the first use of a target-specific macro, warn about it.
1890 if (MI->isTargetSpecific()) {
1891 MI->setIsTargetSpecific(false); // Don't warn on second use.
1892 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1893 diag::port_target_macro_use);
1894 }
Chris Lattner063400e2006-10-14 19:54:15 +00001895 } else {
1896 // Use of a target-specific macro for some other target? If so, warn.
1897 if (MII->isOtherTargetMacro()) {
1898 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1899 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1900 diag::port_target_macro_use);
1901 }
Chris Lattner81278c62006-10-14 19:03:49 +00001902 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001903
Chris Lattner22eb9722006-06-18 05:43:12 +00001904 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001905 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001906 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001907 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001908 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001909 } else {
1910 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001911 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001912 /*Foundnonskip*/false,
1913 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001914 }
1915}
1916
1917/// HandleIfDirective - Implements the #if directive.
1918///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001919void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1920 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001921 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001922
Chris Lattner371ac8a2006-07-04 07:11:10 +00001923 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001924 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001925 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001926
1927 // Should we include the stuff contained by this directive?
1928 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001929 // If this condition is equivalent to #ifndef X, and if this is the first
1930 // directive seen, handle it for the multiple-include optimization.
1931 if (!ReadAnyTokensBeforeDirective &&
1932 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1933 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1934
Chris Lattner22eb9722006-06-18 05:43:12 +00001935 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001936 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001937 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001938 } else {
1939 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001940 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001941 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001942 }
1943}
1944
1945/// HandleEndifDirective - Implements the #endif directive.
1946///
Chris Lattnercb283342006-06-18 06:48:37 +00001947void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001948 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001949
Chris Lattner22eb9722006-06-18 05:43:12 +00001950 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001951 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001952
1953 PPConditionalInfo CondInfo;
1954 if (CurLexer->popConditionalLevel(CondInfo)) {
1955 // No conditionals on the stack: this is an #endif without an #if.
1956 return Diag(EndifToken, diag::err_pp_endif_without_if);
1957 }
1958
Chris Lattner371ac8a2006-07-04 07:11:10 +00001959 // If this the end of a top-level #endif, inform MIOpt.
1960 if (CurLexer->getConditionalStackDepth() == 0)
1961 CurLexer->MIOpt.ExitTopLevelConditional();
1962
Chris Lattner538d7f32006-07-20 04:31:52 +00001963 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001964 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001965}
1966
1967
Chris Lattnercb283342006-06-18 06:48:37 +00001968void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001969 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001970
Chris Lattner22eb9722006-06-18 05:43:12 +00001971 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001972 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001973
1974 PPConditionalInfo CI;
1975 if (CurLexer->popConditionalLevel(CI))
1976 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001977
1978 // If this is a top-level #else, inform the MIOpt.
1979 if (CurLexer->getConditionalStackDepth() == 0)
1980 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001981
1982 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001983 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001984
1985 // Finally, skip the rest of the contents of this block and return the first
1986 // token after it.
1987 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1988 /*FoundElse*/true);
1989}
1990
Chris Lattnercb283342006-06-18 06:48:37 +00001991void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001992 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001993
Chris Lattner22eb9722006-06-18 05:43:12 +00001994 // #elif directive in a non-skipping conditional... start skipping.
1995 // We don't care what the condition is, because we will always skip it (since
1996 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001997 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001998
1999 PPConditionalInfo CI;
2000 if (CurLexer->popConditionalLevel(CI))
2001 return Diag(ElifToken, diag::pp_err_elif_without_if);
2002
Chris Lattner371ac8a2006-07-04 07:11:10 +00002003 // If this is a top-level #elif, inform the MIOpt.
2004 if (CurLexer->getConditionalStackDepth() == 0)
2005 CurLexer->MIOpt.FoundTopLevelElse();
2006
Chris Lattner22eb9722006-06-18 05:43:12 +00002007 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002008 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002009
2010 // Finally, skip the rest of the contents of this block and return the first
2011 // token after it.
2012 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2013 /*FoundElse*/CI.FoundElse);
2014}
Chris Lattnerb8761832006-06-24 21:31:03 +00002015