blob: 4a57a0fd6312a2a4c30ec817d67f68a6c1a1d1ee [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 Lattnerb8b94f12006-10-30 05:38:06 +0000254const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
255 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000256 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000257 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000258 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000259 // If the header lookup mechanism may be relative to the current file, pass in
260 // info about where the current file is.
261 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000262 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000263 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000264 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000265 }
266
Chris Lattner63dd32b2006-10-20 04:42:40 +0000267 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000268 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000269 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000270 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
271 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000272 if (FE) return FE;
273
274 // Otherwise, see if this is a subframework header. If so, this is relative
275 // to one of the headers on the #include stack. Walk the list of the current
276 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000277 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000278 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000279 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
280 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000281 return FE;
282 }
283
284 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
285 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000286 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000287 CurFileEnt =
288 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000289 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
290 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000291 return FE;
292 }
293 }
294
295 // Otherwise, we really couldn't find the file.
296 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000297}
298
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000299/// isInPrimaryFile - Return true if we're in the top-level file, not in a
300/// #include.
301bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000302 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000303 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000304
Chris Lattner13044d92006-07-03 05:16:44 +0000305 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000306 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000307 if (IncludeMacroStack[i].TheLexer &&
308 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
309 return IncludeMacroStack[i].TheLexer->isMainFile();
310 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000311}
312
313/// getCurrentLexer - Return the current file lexer being lexed from. Note
314/// that this ignores any potentially active macro expansions and _Pragma
315/// expansions going on at the time.
316Lexer *Preprocessor::getCurrentFileLexer() const {
317 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
318
319 // Look for a stacked lexer.
320 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000321 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000322 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
323 return L;
324 }
325 return 0;
326}
327
328
Chris Lattner22eb9722006-06-18 05:43:12 +0000329/// EnterSourceFile - Add a source file to the top of the include stack and
330/// start lexing tokens from it instead of the current buffer. Return true
331/// on failure.
332void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000333 const DirectoryLookup *CurDir,
334 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000335 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000336 ++NumEnteredSourceFiles;
337
Chris Lattner69772b02006-07-02 20:34:39 +0000338 if (MaxIncludeStackDepth < IncludeMacroStack.size())
339 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000340
Chris Lattner22eb9722006-06-18 05:43:12 +0000341 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000342 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000343 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000344 EnterSourceFileWithLexer(TheLexer, CurDir);
345}
Chris Lattner22eb9722006-06-18 05:43:12 +0000346
Chris Lattner69772b02006-07-02 20:34:39 +0000347/// EnterSourceFile - Add a source file to the top of the include stack and
348/// start lexing tokens from it instead of the current buffer.
349void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
350 const DirectoryLookup *CurDir) {
351
352 // Add the current lexer to the include stack.
353 if (CurLexer || CurMacroExpander)
354 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
355 CurMacroExpander));
356
357 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000358 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000359 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000360
361 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000362 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000363 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
364
365 // Get the file entry for the current file.
366 if (const FileEntry *FE =
367 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000368 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000369
Chris Lattner1840e492006-07-02 22:30:01 +0000370 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000371 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000372 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000373}
374
Chris Lattner69772b02006-07-02 20:34:39 +0000375
376
Chris Lattner22eb9722006-06-18 05:43:12 +0000377/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000378/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000379void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000380 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
381 CurMacroExpander));
382 CurLexer = 0;
383 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000384
Chris Lattneree8760b2006-07-15 07:42:55 +0000385 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000386}
387
Chris Lattner7667d0d2006-07-16 18:16:58 +0000388/// EnterTokenStream - Add a "macro" context to the top of the include stack,
389/// which will cause the lexer to start returning the specified tokens. Note
390/// that these tokens will be re-macro-expanded when/if expansion is enabled.
391/// This method assumes that the specified stream of tokens has a permanent
392/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000393void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000394 // Save our current state.
395 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
396 CurMacroExpander));
397 CurLexer = 0;
398 CurDirLookup = 0;
399
400 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000401 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000402}
403
404/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
405/// lexer stack. This should only be used in situations where the current
406/// state of the top-of-stack lexer is known.
407void Preprocessor::RemoveTopOfLexerStack() {
408 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
409 delete CurLexer;
410 delete CurMacroExpander;
411 CurLexer = IncludeMacroStack.back().TheLexer;
412 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
413 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
414 IncludeMacroStack.pop_back();
415}
416
Chris Lattner22eb9722006-06-18 05:43:12 +0000417//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000418// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000419//===----------------------------------------------------------------------===//
420
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000421/// RegisterBuiltinMacro - Register the specified identifier in the identifier
422/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000423IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000424 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000425 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000426
427 // Mark it as being a macro that is builtin.
428 MacroInfo *MI = new MacroInfo(SourceLocation());
429 MI->setIsBuiltinMacro();
430 Id->setMacroInfo(MI);
431 return Id;
432}
433
434
Chris Lattner677757a2006-06-28 05:26:32 +0000435/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
436/// identifier table.
437void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000438 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000439 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000440 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
441 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000442 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000443
444 // GCC Extensions.
445 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
446 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000447 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000448}
449
Chris Lattnerc2395832006-07-09 00:57:04 +0000450/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
451/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000452static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
453 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000454 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
455
456 // If the token isn't an identifier, it's always literally expanded.
457 if (II == 0) return true;
458
459 // If the identifier is a macro, and if that macro is enabled, it may be
460 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000461 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
462 // Fast expanding "#define X X" is ok, because X would be disabled.
463 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000464 return false;
465
466 // If this is an object-like macro invocation, it is safe to trivially expand
467 // it.
468 if (MI->isObjectLike()) return true;
469
470 // If this is a function-like macro invocation, it's safe to trivially expand
471 // as long as the identifier is not a macro argument.
472 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
473 I != E; ++I)
474 if (*I == II)
475 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000476
Chris Lattnerc2395832006-07-09 00:57:04 +0000477 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000478}
479
Chris Lattnerc2395832006-07-09 00:57:04 +0000480
Chris Lattnerafe603f2006-07-11 04:02:46 +0000481/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
482/// lexed is a '('. If so, consume the token and return true, if not, this
483/// method should have no observable side-effect on the lexed tokens.
484bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000485 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000486 unsigned Val;
487 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000488 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000489 else
490 Val = CurMacroExpander->isNextTokenLParen();
491
492 if (Val == 2) {
493 // If we ran off the end of the lexer or macro expander, walk the include
494 // stack, looking for whatever will return the next token.
495 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
496 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
497 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000498 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000499 else
500 Val = Entry.TheMacroExpander->isNextTokenLParen();
501 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000502 }
503
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000504 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
505 // have found something that isn't a '(' or we found the end of the
506 // translation unit. In either case, return false.
507 if (Val != 1)
508 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000509
510 LexerToken Tok;
511 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000512 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
513 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000514}
Chris Lattner677757a2006-06-28 05:26:32 +0000515
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000516/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
517/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000518bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000519 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000520
521 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
522 if (MI->isBuiltinMacro()) {
523 ExpandBuiltinMacro(Identifier);
524 return false;
525 }
526
Chris Lattner81278c62006-10-14 19:03:49 +0000527 // If this is the first use of a target-specific macro, warn about it.
528 if (MI->isTargetSpecific()) {
529 MI->setIsTargetSpecific(false); // Don't warn on second use.
530 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
531 diag::port_target_macro_use);
532 }
533
Chris Lattneree8760b2006-07-15 07:42:55 +0000534 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000535 /// for each macro argument, the list of tokens that were provided to the
536 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000537 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000538
539 // If this is a function-like macro, read the arguments.
540 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000541 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
542 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000543 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000544 return true;
545
Chris Lattner78186052006-07-09 00:45:31 +0000546 // Remember that we are now parsing the arguments to a macro invocation.
547 // Preprocessor directives used inside macro arguments are not portable, and
548 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000549 InMacroArgs = true;
550 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000551
552 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000553 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000554
555 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000556 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000557
558 ++NumFnMacroExpanded;
559 } else {
560 ++NumMacroExpanded;
561 }
Chris Lattner13044d92006-07-03 05:16:44 +0000562
563 // Notice that this macro has been used.
564 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000565
566 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000567
568 // If this macro expands to no tokens, don't bother to push it onto the
569 // expansion stack, only to take it right back off.
570 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000571 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000572 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000573
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000574 // Ignore this macro use, just return the next token in the current
575 // buffer.
576 bool HadLeadingSpace = Identifier.hasLeadingSpace();
577 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
578
579 Lex(Identifier);
580
581 // If the identifier isn't on some OTHER line, inherit the leading
582 // whitespace/first-on-a-line property of this token. This handles
583 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
584 // empty.
585 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000586 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
587 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000588 }
589 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000590 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000591
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000592 } else if (MI->getNumTokens() == 1 &&
593 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000594 // Otherwise, if this macro expands into a single trivially-expanded
595 // token: expand it now. This handles common cases like
596 // "#define VAL 42".
597
598 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
599 // identifier to the expanded token.
600 bool isAtStartOfLine = Identifier.isAtStartOfLine();
601 bool hasLeadingSpace = Identifier.hasLeadingSpace();
602
603 // Remember where the token is instantiated.
604 SourceLocation InstantiateLoc = Identifier.getLocation();
605
606 // Replace the result token.
607 Identifier = MI->getReplacementToken(0);
608
609 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000610 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
611 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000612
613 // Update the tokens location to include both its logical and physical
614 // locations.
615 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000616 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000617 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000618
Chris Lattner6e4bf522006-07-27 06:59:25 +0000619 // If this is #define X X, we must mark the result as unexpandible.
620 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
621 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000622 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000623
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000624 // Since this is not an identifier token, it can't be macro expanded, so
625 // we're done.
626 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000627 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000628 }
629
Chris Lattner78186052006-07-09 00:45:31 +0000630 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000631 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000632
633 // Now that the macro is at the top of the include stack, ask the
634 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000635 Lex(Identifier);
636 return false;
637}
638
Chris Lattneree8760b2006-07-15 07:42:55 +0000639/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000640/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000641/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000642MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
643 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000644 // The number of fixed arguments to parse.
645 unsigned NumFixedArgsLeft = MI->getNumArgs();
646 bool isVariadic = MI->isVariadic();
647
Chris Lattner78186052006-07-09 00:45:31 +0000648 // Outer loop, while there are more arguments, keep reading them.
649 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000650 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000651 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000652
653 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000654 // argument is separated by an EOF token. Use a SmallVector so we can avoid
655 // heap allocations in the common case.
656 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000657
658 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000659 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000660 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
661 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000662
Chris Lattner78186052006-07-09 00:45:31 +0000663 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000664 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
665 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000666 LexUnexpandedToken(Tok);
667
668 if (Tok.getKind() == tok::eof) {
669 Diag(MacroName, diag::err_unterm_macro_invoc);
670 // Do not lose the EOF. Return it to the client.
671 MacroName = Tok;
672 return 0;
673 } else if (Tok.getKind() == tok::r_paren) {
674 // If we found the ) token, the macro arg list is done.
675 if (NumParens-- == 0)
676 break;
677 } else if (Tok.getKind() == tok::l_paren) {
678 ++NumParens;
679 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
680 // Comma ends this argument if there are more fixed arguments expected.
681 if (NumFixedArgsLeft)
682 break;
683
Chris Lattner2ada5d32006-07-15 07:51:24 +0000684 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000685 if (!isVariadic) {
686 // Emit the diagnostic at the macro name in case there is a missing ).
687 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000688 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000689 return 0;
690 }
691 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000692 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
693 // If this is a comment token in the argument list and we're just in
694 // -C mode (not -CC mode), discard the comment.
695 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000696 }
697
698 ArgTokens.push_back(Tok);
699 }
700
Chris Lattnera12dd152006-07-11 04:09:02 +0000701 // Empty arguments are standard in C99 and supported as an extension in
702 // other modes.
703 if (ArgTokens.empty() && !Features.C99)
704 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000705
Chris Lattner36b6e812006-07-21 06:38:30 +0000706 // Add a marker EOF token to the end of the token list for this argument.
707 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000708 EOFTok.startToken();
709 EOFTok.setKind(tok::eof);
710 EOFTok.setLocation(Tok.getLocation());
711 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000712 ArgTokens.push_back(EOFTok);
713 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000714 --NumFixedArgsLeft;
715 };
716
717 // Okay, we either found the r_paren. Check to see if we parsed too few
718 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000719 unsigned MinArgsExpected = MI->getNumArgs();
720
Chris Lattner775d8322006-07-29 04:39:41 +0000721 // See MacroArgs instance var for description of this.
722 bool isVarargsElided = false;
723
Chris Lattner2ada5d32006-07-15 07:51:24 +0000724 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000725 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000726 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000727 // Varargs where the named vararg parameter is missing: ok as extension.
728 // #define A(x, ...)
729 // A("blah")
730 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000731
732 // Remember this occurred if this is a C99 macro invocation with at least
733 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000734 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000735 } else if (MI->getNumArgs() == 1) {
736 // #define A(x)
737 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000738 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000739
740 // Empty arguments are standard in C99 and supported as an extension in
741 // other modes.
742 if (ArgTokens.empty() && !Features.C99)
743 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000744 } else {
745 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000746 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000747 return 0;
748 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000749
750 // Add a marker EOF token to the end of the token list for this argument.
751 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000752 Tok.startToken();
753 Tok.setKind(tok::eof);
754 Tok.setLocation(EndLoc);
755 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000756 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000757 }
758
Chris Lattner775d8322006-07-29 04:39:41 +0000759 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000760}
761
Chris Lattnerc673f902006-06-30 06:10:41 +0000762/// ComputeDATE_TIME - Compute the current time, enter it into the specified
763/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
764/// the identifier tokens inserted.
765static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000766 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000767 time_t TT = time(0);
768 struct tm *TM = localtime(&TT);
769
770 static const char * const Months[] = {
771 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
772 };
773
774 char TmpBuffer[100];
775 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
776 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000777 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000778
779 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000780 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000781}
782
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000783/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
784/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000785void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000786 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000787 IdentifierInfo *II = Tok.getIdentifierInfo();
788 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000789
790 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
791 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000792 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000793 return Handle_Pragma(Tok);
794
Chris Lattner78186052006-07-09 00:45:31 +0000795 ++NumBuiltinMacroExpanded;
796
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000797 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000798
799 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000800 Tok.setIdentifierInfo(0);
801 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000802
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000803 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000804 // __LINE__ expands to a simple numeric value.
805 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
806 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000807 Tok.setKind(tok::numeric_constant);
808 Tok.setLength(Length);
809 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000810 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000811 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000812 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000813 Diag(Tok, diag::ext_pp_base_file);
814 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
815 while (NextLoc.getFileID() != 0) {
816 Loc = NextLoc;
817 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
818 }
819 }
820
Chris Lattner0766e592006-07-03 01:07:01 +0000821 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
822 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000823 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000824 Tok.setKind(tok::string_literal);
825 Tok.setLength(FN.size());
826 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000827 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000828 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000829 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000830 Tok.setKind(tok::string_literal);
831 Tok.setLength(strlen("\"Mmm dd yyyy\""));
832 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000833 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000834 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000835 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000836 Tok.setKind(tok::string_literal);
837 Tok.setLength(strlen("\"hh:mm:ss\""));
838 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000839 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000840 Diag(Tok, diag::ext_pp_include_level);
841
842 // Compute the include depth of this token.
843 unsigned Depth = 0;
844 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
845 for (; Loc.getFileID() != 0; ++Depth)
846 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
847
848 // __INCLUDE_LEVEL__ expands to a simple numeric value.
849 sprintf(TmpBuffer, "%u", Depth);
850 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000851 Tok.setKind(tok::numeric_constant);
852 Tok.setLength(Length);
853 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000854 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000855 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
856 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
857 Diag(Tok, diag::ext_pp_timestamp);
858
859 // Get the file that we are lexing out of. If we're currently lexing from
860 // a macro, dig into the include stack.
861 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000862 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000863
864 if (TheLexer)
865 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
866
867 // If this file is older than the file it depends on, emit a diagnostic.
868 const char *Result;
869 if (CurFile) {
870 time_t TT = CurFile->getModificationTime();
871 struct tm *TM = localtime(&TT);
872 Result = asctime(TM);
873 } else {
874 Result = "??? ??? ?? ??:??:?? ????\n";
875 }
876 TmpBuffer[0] = '"';
877 strcpy(TmpBuffer+1, Result);
878 unsigned Len = strlen(TmpBuffer);
879 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000880 Tok.setKind(tok::string_literal);
881 Tok.setLength(Len);
882 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000883 } else {
884 assert(0 && "Unknown identifier!");
885 }
886}
Chris Lattner677757a2006-06-28 05:26:32 +0000887
Chris Lattner13044d92006-07-03 05:16:44 +0000888namespace {
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000889struct UnusedIdentifierReporter : public CStringMapVisitor {
Chris Lattner13044d92006-07-03 05:16:44 +0000890 Preprocessor &PP;
891 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
892
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000893 void Visit(const char *Key, void *Value) const {
894 IdentifierInfo &II = *static_cast<IdentifierInfo*>(Value);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000895 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
896 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000897 }
898};
899}
900
Chris Lattner677757a2006-06-28 05:26:32 +0000901//===----------------------------------------------------------------------===//
902// Lexer Event Handling.
903//===----------------------------------------------------------------------===//
904
Chris Lattnercefc7682006-07-08 08:28:12 +0000905/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
906/// identifier information for the token and install it into the token.
907IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
908 const char *BufPtr) {
909 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
910 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
911
912 // Look up this token, see if it is a macro, or if it is a language keyword.
913 IdentifierInfo *II;
914 if (BufPtr && !Identifier.needsCleaning()) {
915 // No cleaning needed, just use the characters from the lexed buffer.
916 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
917 } else {
918 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
919 const char *TmpBuf = (char*)alloca(Identifier.getLength());
920 unsigned Size = getSpelling(Identifier, TmpBuf);
921 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
922 }
Chris Lattner8c204872006-10-14 05:19:21 +0000923 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000924 return II;
925}
926
927
Chris Lattner677757a2006-06-28 05:26:32 +0000928/// HandleIdentifier - This callback is invoked when the lexer reads an
929/// identifier. This callback looks up the identifier in the map and/or
930/// potentially macro expands it or turns it into a named token (like 'for').
931void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000932 assert(Identifier.getIdentifierInfo() &&
933 "Can't handle identifiers without identifier info!");
934
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000935 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000936
937 // If this identifier was poisoned, and if it was not produced from a macro
938 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000939 if (II.isPoisoned() && CurLexer) {
940 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
941 Diag(Identifier, diag::err_pp_used_poisoned_id);
942 else
943 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
944 }
Chris Lattner677757a2006-06-28 05:26:32 +0000945
Chris Lattner78186052006-07-09 00:45:31 +0000946 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000947 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000948 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
949 if (MI->isEnabled()) {
950 if (!HandleMacroExpandedIdentifier(Identifier, MI))
951 return;
952 } else {
953 // C99 6.10.3.4p2 says that a disabled macro may never again be
954 // expanded, even if it's in a context where it could be expanded in the
955 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000956 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000957 }
958 }
Chris Lattner063400e2006-10-14 19:54:15 +0000959 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
960 // If this identifier is a macro on some other target, emit a diagnostic.
961 // This diagnosic is only emitted when macro expansion is enabled, because
962 // the macro would not have been expanded for the other target either.
963 II.setIsOtherTargetMacro(false); // Don't warn on second use.
964 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
965 diag::port_target_macro_use);
966
967 }
Chris Lattner677757a2006-06-28 05:26:32 +0000968
969 // Change the kind of this identifier to the appropriate token kind, e.g.
970 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000971 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000972
973 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000974 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000975}
976
Chris Lattner22eb9722006-06-18 05:43:12 +0000977/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
978/// the current file. This either returns the EOF token or pops a level off
979/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000980bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000981 assert(!CurMacroExpander &&
982 "Ending a file when currently in a macro!");
983
Chris Lattner371ac8a2006-07-04 07:11:10 +0000984 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000985 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000986 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000987 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000988 // Okay, this has a controlling macro, remember in PerFileInfo.
989 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000990 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
991 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000992 }
993 }
994
Chris Lattner22eb9722006-06-18 05:43:12 +0000995 // If this is a #include'd file, pop it off the include stack and continue
996 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000997 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000998 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000999 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001000
1001 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001002 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001003 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1004
1005 // Get the file entry for the current file.
1006 if (const FileEntry *FE =
1007 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001008 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001009
Chris Lattner0c885f52006-06-21 06:50:18 +00001010 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001011 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001012 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001013
1014 // Client should lex another token.
1015 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001016 }
1017
Chris Lattner8c204872006-10-14 05:19:21 +00001018 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001019 CurLexer->BufferPtr = CurLexer->BufferEnd;
1020 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001021 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001022
1023 // We're done with the #included file.
1024 delete CurLexer;
1025 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001026
Chris Lattner03f83482006-07-10 06:16:26 +00001027 // This is the end of the top-level file. If the diag::pp_macro_not_used
1028 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1029 // have not been used.
1030 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1031 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001032
1033 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001034}
1035
1036/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001037/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001038bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001039 assert(CurMacroExpander && !CurLexer &&
1040 "Ending a macro when currently in a #include file!");
1041
Chris Lattner22eb9722006-06-18 05:43:12 +00001042 delete CurMacroExpander;
1043
Chris Lattner69772b02006-07-02 20:34:39 +00001044 // Handle this like a #include file being popped off the stack.
1045 CurMacroExpander = 0;
1046 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001047}
1048
1049
1050//===----------------------------------------------------------------------===//
1051// Utility Methods for Preprocessor Directive Handling.
1052//===----------------------------------------------------------------------===//
1053
1054/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1055/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001056void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001057 LexerToken Tmp;
1058 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001059 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001060 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001061}
1062
1063/// ReadMacroName - Lex and validate a macro name, which occurs after a
1064/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001065/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1066/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001067/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001068void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001069 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001070 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001071
1072 // Missing macro name?
1073 if (MacroNameTok.getKind() == tok::eom)
1074 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1075
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001076 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1077 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001078 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001079 // Fall through on error.
1080 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001081 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001082
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001083 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1084 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001085 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001086 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001087 } else if (isDefineUndef && II->getMacroInfo() &&
1088 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001089 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001090 if (isDefineUndef == 1)
1091 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1092 else
1093 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001094 } else {
1095 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001096 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 }
1098
Chris Lattner22eb9722006-06-18 05:43:12 +00001099 // Invalid macro name, read and discard the rest of the line. Then set the
1100 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001101 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001102 return DiscardUntilEndOfDirective();
1103}
1104
1105/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1106/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001107void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001108 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001109 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001110 // There should be no tokens after the directive, but we allow them as an
1111 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001112 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1113 Lex(Tmp);
1114
Chris Lattner22eb9722006-06-18 05:43:12 +00001115 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001116 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1117 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001118 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001119}
1120
1121
1122
1123/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1124/// decided that the subsequent tokens are in the #if'd out portion of the
1125/// file. Lex the rest of the file, until we see an #endif. If
1126/// FoundNonSkipPortion is true, then we have already emitted code for part of
1127/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1128/// is true, then #else directives are ok, if not, then we have already seen one
1129/// so a #else directive is a duplicate. When this returns, the caller can lex
1130/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001131void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001132 bool FoundNonSkipPortion,
1133 bool FoundElse) {
1134 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001135 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001136 "Lexing a macro, not a file?");
1137
1138 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1139 FoundNonSkipPortion, FoundElse);
1140
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001141 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1142 // disabling warnings, etc.
1143 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001144 LexerToken Tok;
1145 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001146 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001147
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001148 // If this is the end of the buffer, we have an error.
1149 if (Tok.getKind() == tok::eof) {
1150 // Emit errors for each unterminated conditional on the stack, including
1151 // the current one.
1152 while (!CurLexer->ConditionalStack.empty()) {
1153 Diag(CurLexer->ConditionalStack.back().IfLoc,
1154 diag::err_pp_unterminated_conditional);
1155 CurLexer->ConditionalStack.pop_back();
1156 }
1157
1158 // Just return and let the caller lex after this #include.
1159 break;
1160 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001161
1162 // If this token is not a preprocessor directive, just skip it.
1163 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1164 continue;
1165
1166 // We just parsed a # character at the start of a line, so we're in
1167 // directive mode. Tell the lexer this so any newlines we see will be
1168 // converted into an EOM token (this terminates the macro).
1169 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001170 CurLexer->KeepCommentMode = false;
1171
Chris Lattner22eb9722006-06-18 05:43:12 +00001172
1173 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001174 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001175
1176 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1177 // something bogus), skip it.
1178 if (Tok.getKind() != tok::identifier) {
1179 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001180 // Restore comment saving mode.
1181 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001182 continue;
1183 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001184
Chris Lattner22eb9722006-06-18 05:43:12 +00001185 // If the first letter isn't i or e, it isn't intesting to us. We know that
1186 // this is safe in the face of spelling differences, because there is no way
1187 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001188 // allows us to avoid looking up the identifier info for #define/#undef and
1189 // other common directives.
1190 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1191 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001192 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1193 FirstChar != 'i' && FirstChar != 'e') {
1194 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001195 // Restore comment saving mode.
1196 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001197 continue;
1198 }
1199
Chris Lattnere60165f2006-06-22 06:36:29 +00001200 // Get the identifier name without trigraphs or embedded newlines. Note
1201 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1202 // when skipping.
1203 // TODO: could do this with zero copies in the no-clean case by using
1204 // strncmp below.
1205 char Directive[20];
1206 unsigned IdLen;
1207 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1208 IdLen = Tok.getLength();
1209 memcpy(Directive, RawCharData, IdLen);
1210 Directive[IdLen] = 0;
1211 } else {
1212 std::string DirectiveStr = getSpelling(Tok);
1213 IdLen = DirectiveStr.size();
1214 if (IdLen >= 20) {
1215 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001216 // Restore comment saving mode.
1217 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001218 continue;
1219 }
1220 memcpy(Directive, &DirectiveStr[0], IdLen);
1221 Directive[IdLen] = 0;
1222 }
1223
Chris Lattner22eb9722006-06-18 05:43:12 +00001224 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001225 if ((IdLen == 2) || // "if"
1226 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1227 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001228 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1229 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001230 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001231 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001232 /*foundnonskip*/false,
1233 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001234 }
1235 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001236 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001237 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001238 PPConditionalInfo CondInfo;
1239 CondInfo.WasSkipping = true; // Silence bogus warning.
1240 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001241 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001242 assert(!InCond && "Can't be skipping if not in a conditional!");
1243
1244 // If we popped the outermost skipping block, we're done skipping!
1245 if (!CondInfo.WasSkipping)
1246 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001247 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001248 // #else directive in a skipping conditional. If not in some other
1249 // skipping conditional, and if #else hasn't already been seen, enter it
1250 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001251 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001252 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1253
1254 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001255 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001256
1257 // Note that we've seen a #else in this conditional.
1258 CondInfo.FoundElse = true;
1259
1260 // If the conditional is at the top level, and the #if block wasn't
1261 // entered, enter the #else block now.
1262 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1263 CondInfo.FoundNonSkip = true;
1264 break;
1265 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001266 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001267 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1268
1269 bool ShouldEnter;
1270 // If this is in a skipping block or if we're already handled this #if
1271 // block, don't bother parsing the condition.
1272 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001273 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001274 ShouldEnter = false;
1275 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001276 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001277 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001278 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1279 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001280 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001281 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001282 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001283 }
1284
1285 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001286 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001287
1288 // If this condition is true, enter it!
1289 if (ShouldEnter) {
1290 CondInfo.FoundNonSkip = true;
1291 break;
1292 }
1293 }
1294 }
1295
1296 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001297 // Restore comment saving mode.
1298 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001299 }
1300
1301 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1302 // of the file, just stop skipping and return to lexing whatever came after
1303 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001304 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001305}
1306
1307//===----------------------------------------------------------------------===//
1308// Preprocessor Directive Handling.
1309//===----------------------------------------------------------------------===//
1310
1311/// HandleDirective - This callback is invoked when the lexer sees a # token
1312/// at the start of a line. This consumes the directive, modifies the
1313/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1314/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001315void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001316 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001317
1318 // We just parsed a # character at the start of a line, so we're in directive
1319 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001320 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001321 CurLexer->ParsingPreprocessorDirective = true;
1322
1323 ++NumDirectives;
1324
Chris Lattner371ac8a2006-07-04 07:11:10 +00001325 // We are about to read a token. For the multiple-include optimization FA to
1326 // work, we have to remember if we had read any tokens *before* this
1327 // pp-directive.
1328 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1329
Chris Lattner78186052006-07-09 00:45:31 +00001330 // Read the next token, the directive flavor. This isn't expanded due to
1331 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001332 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001333
Chris Lattner78186052006-07-09 00:45:31 +00001334 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1335 // #define A(x) #x
1336 // A(abc
1337 // #warning blah
1338 // def)
1339 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001340 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001341 Diag(Result, diag::ext_embedded_directive);
1342
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001343TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001344 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001346 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001347 case tok::comment:
1348 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1349 LexUnexpandedToken(Result);
1350 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001351
Chris Lattner22eb9722006-06-18 05:43:12 +00001352 case tok::numeric_constant:
1353 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001354 DiscardUntilEndOfDirective();
1355 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001356 default:
1357 IdentifierInfo *II = Result.getIdentifierInfo();
1358 if (II == 0) break; // Not an identifier.
1359
1360 // Ask what the preprocessor keyword ID is.
1361 switch (II->getPPKeywordID()) {
1362 default: break;
1363 // C99 6.10.1 - Conditional Inclusion.
1364 case tok::pp_if:
1365 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1366 case tok::pp_ifdef:
1367 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1368 case tok::pp_ifndef:
1369 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1370 case tok::pp_elif:
1371 return HandleElifDirective(Result);
1372 case tok::pp_else:
1373 return HandleElseDirective(Result);
1374 case tok::pp_endif:
1375 return HandleEndifDirective(Result);
1376
1377 // C99 6.10.2 - Source File Inclusion.
1378 case tok::pp_include:
1379 return HandleIncludeDirective(Result); // Handle #include.
1380
1381 // C99 6.10.3 - Macro Replacement.
1382 case tok::pp_define:
1383 return HandleDefineDirective(Result, false);
1384 case tok::pp_undef:
1385 return HandleUndefDirective(Result);
1386
1387 // C99 6.10.4 - Line Control.
1388 case tok::pp_line:
1389 // FIXME: implement #line
1390 DiscardUntilEndOfDirective();
1391 return;
1392
1393 // C99 6.10.5 - Error Directive.
1394 case tok::pp_error:
1395 return HandleUserDiagnosticDirective(Result, false);
1396
1397 // C99 6.10.6 - Pragma Directive.
1398 case tok::pp_pragma:
1399 return HandlePragmaDirective();
1400
1401 // GNU Extensions.
1402 case tok::pp_import:
1403 return HandleImportDirective(Result);
1404 case tok::pp_include_next:
1405 return HandleIncludeNextDirective(Result);
1406
1407 case tok::pp_warning:
1408 Diag(Result, diag::ext_pp_warning_directive);
1409 return HandleUserDiagnosticDirective(Result, true);
1410 case tok::pp_ident:
1411 return HandleIdentSCCSDirective(Result);
1412 case tok::pp_sccs:
1413 return HandleIdentSCCSDirective(Result);
1414 case tok::pp_assert:
1415 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001416 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001417 case tok::pp_unassert:
1418 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001419 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001420
1421 // clang extensions.
1422 case tok::pp_define_target:
1423 return HandleDefineDirective(Result, true);
1424 case tok::pp_define_other_target:
1425 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001426 }
1427 break;
1428 }
1429
1430 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001431 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001432
1433 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001434 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001435
1436 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001437}
1438
Chris Lattner01d66cc2006-07-03 22:16:27 +00001439void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001440 bool isWarning) {
1441 // Read the rest of the line raw. We do this because we don't want macros
1442 // to be expanded and we don't require that the tokens be valid preprocessing
1443 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1444 // collapse multiple consequtive white space between tokens, but this isn't
1445 // specified by the standard.
1446 std::string Message = CurLexer->ReadToEndOfLine();
1447
1448 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001449 return Diag(Tok, DiagID, Message);
1450}
1451
1452/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1453///
1454void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001455 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001456 Diag(Tok, diag::ext_pp_ident_directive);
1457
Chris Lattner371ac8a2006-07-04 07:11:10 +00001458 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001459 LexerToken StrTok;
1460 Lex(StrTok);
1461
1462 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001463 if (StrTok.getKind() != tok::string_literal &&
1464 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001465 return Diag(StrTok, diag::err_pp_malformed_ident);
1466
1467 // Verify that there is nothing after the string, other than EOM.
1468 CheckEndOfDirective("#ident");
1469
1470 if (IdentHandler)
1471 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001472}
1473
Chris Lattnerb8761832006-06-24 21:31:03 +00001474//===----------------------------------------------------------------------===//
1475// Preprocessor Include Directive Handling.
1476//===----------------------------------------------------------------------===//
1477
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001478/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1479/// checked and spelled filename, e.g. as an operand of #include. This returns
1480/// true if the input filename was in <>'s or false if it were in ""'s. The
1481/// caller is expected to provide a buffer that is large enough to hold the
1482/// spelling of the filename, but is also expected to handle the case when
1483/// this method decides to use a different buffer.
1484bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1485 const char *&BufStart,
1486 const char *&BufEnd) {
1487 // Get the text form of the filename.
1488 unsigned Len = getSpelling(FilenameTok, BufStart);
1489 BufEnd = BufStart+Len;
1490 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1491
1492 // Make sure the filename is <x> or "x".
1493 bool isAngled;
1494 if (BufStart[0] == '<') {
1495 if (BufEnd[-1] != '>') {
1496 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1497 BufStart = 0;
1498 return true;
1499 }
1500 isAngled = true;
1501 } else if (BufStart[0] == '"') {
1502 if (BufEnd[-1] != '"') {
1503 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1504 BufStart = 0;
1505 return true;
1506 }
1507 isAngled = false;
1508 } else {
1509 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1510 BufStart = 0;
1511 return true;
1512 }
1513
1514 // Diagnose #include "" as invalid.
1515 if (BufEnd-BufStart <= 2) {
1516 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1517 BufStart = 0;
1518 return "";
1519 }
1520
1521 // Skip the brackets.
1522 ++BufStart;
1523 --BufEnd;
1524 return isAngled;
1525}
1526
Chris Lattner22eb9722006-06-18 05:43:12 +00001527/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1528/// file to be included from the lexer, then include it! This is a common
1529/// routine with functionality shared between #include, #include_next and
1530/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001531void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001532 const DirectoryLookup *LookupFrom,
1533 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001534
Chris Lattner22eb9722006-06-18 05:43:12 +00001535 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001536 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001537
1538 // If the token kind is EOM, the error has already been diagnosed.
1539 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001540 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001541
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001542 // Reserve a buffer to get the spelling.
1543 SmallVector<char, 128> FilenameBuffer;
1544 FilenameBuffer.resize(FilenameTok.getLength());
1545
1546 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1547 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1548 FilenameStart, FilenameEnd);
1549 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1550 // error.
1551 if (FilenameStart == 0)
1552 return;
1553
Chris Lattner269c2322006-06-25 06:23:00 +00001554 // Verify that there is nothing after the filename, other than EOM. Use the
1555 // preprocessor to lex this in case lexing the filename entered a macro.
1556 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001557
1558 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001559 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001560 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1561
Chris Lattner22eb9722006-06-18 05:43:12 +00001562 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001563 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001564 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001565 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001566 if (File == 0)
1567 return Diag(FilenameTok, diag::err_pp_file_not_found);
1568
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001569 // Ask HeaderInfo if we should enter this #include file.
1570 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1571 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001572 return;
1573 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001574
1575 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001576 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001577 if (FileID == 0)
1578 return Diag(FilenameTok, diag::err_pp_file_not_found);
1579
1580 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001581 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001582}
1583
1584/// HandleIncludeNextDirective - Implements #include_next.
1585///
Chris Lattnercb283342006-06-18 06:48:37 +00001586void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1587 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001588
1589 // #include_next is like #include, except that we start searching after
1590 // the current found directory. If we can't do this, issue a
1591 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001592 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001593 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001594 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001595 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001596 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001597 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001598 } else {
1599 // Start looking up in the next directory.
1600 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001601 }
1602
1603 return HandleIncludeDirective(IncludeNextTok, Lookup);
1604}
1605
1606/// HandleImportDirective - Implements #import.
1607///
Chris Lattnercb283342006-06-18 06:48:37 +00001608void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1609 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001610
1611 return HandleIncludeDirective(ImportTok, 0, true);
1612}
1613
Chris Lattnerb8761832006-06-24 21:31:03 +00001614//===----------------------------------------------------------------------===//
1615// Preprocessor Macro Directive Handling.
1616//===----------------------------------------------------------------------===//
1617
Chris Lattnercefc7682006-07-08 08:28:12 +00001618/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1619/// definition has just been read. Lex the rest of the arguments and the
1620/// closing ), updating MI with what we learn. Return true if an error occurs
1621/// parsing the arg list.
1622bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1623 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001624 while (1) {
1625 LexUnexpandedToken(Tok);
1626 switch (Tok.getKind()) {
1627 case tok::r_paren:
1628 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001629 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001630 // Otherwise we have #define FOO(A,)
1631 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1632 return true;
1633 case tok::ellipsis: // #define X(... -> C99 varargs
1634 // Warn if use of C99 feature in non-C99 mode.
1635 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1636
1637 // Lex the token after the identifier.
1638 LexUnexpandedToken(Tok);
1639 if (Tok.getKind() != tok::r_paren) {
1640 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1641 return true;
1642 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001643 // Add the __VA_ARGS__ identifier as an argument.
1644 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001645 MI->setIsC99Varargs();
1646 return false;
1647 case tok::eom: // #define X(
1648 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1649 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001650 default:
1651 // Handle keywords and identifiers here to accept things like
1652 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001653 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001654 if (II == 0) {
1655 // #define X(1
1656 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1657 return true;
1658 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001659
1660 // If this is already used as an argument, it is used multiple times (e.g.
1661 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001662 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001663 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1664 return true;
1665 }
1666
1667 // Add the argument to the macro info.
1668 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001669
1670 // Lex the token after the identifier.
1671 LexUnexpandedToken(Tok);
1672
1673 switch (Tok.getKind()) {
1674 default: // #define X(A B
1675 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1676 return true;
1677 case tok::r_paren: // #define X(A)
1678 return false;
1679 case tok::comma: // #define X(A,
1680 break;
1681 case tok::ellipsis: // #define X(A... -> GCC extension
1682 // Diagnose extension.
1683 Diag(Tok, diag::ext_named_variadic_macro);
1684
1685 // Lex the token after the identifier.
1686 LexUnexpandedToken(Tok);
1687 if (Tok.getKind() != tok::r_paren) {
1688 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1689 return true;
1690 }
1691
1692 MI->setIsGNUVarargs();
1693 return false;
1694 }
1695 }
1696 }
1697}
1698
Chris Lattner22eb9722006-06-18 05:43:12 +00001699/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001700/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1701/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001702///
Chris Lattner81278c62006-10-14 19:03:49 +00001703void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1704 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001705 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001706
Chris Lattner22eb9722006-06-18 05:43:12 +00001707 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001708 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001709
1710 // Error reading macro name? If so, diagnostic already issued.
1711 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001712 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001713
Chris Lattner457fc152006-07-29 06:30:25 +00001714 // If we are supposed to keep comments in #defines, reenable comment saving
1715 // mode.
1716 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1717
Chris Lattner063400e2006-10-14 19:54:15 +00001718 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001719 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001720 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001721
Chris Lattner063400e2006-10-14 19:54:15 +00001722 // If the identifier is an 'other target' macro, clear this bit.
1723 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1724
1725
Chris Lattner22eb9722006-06-18 05:43:12 +00001726 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001727 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001728
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001729 // If this is a function-like macro definition, parse the argument list,
1730 // marking each of the identifiers as being used as macro arguments. Also,
1731 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001732 if (Tok.getKind() == tok::eom) {
1733 // If there is no body to this macro, we have no special handling here.
1734 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001735 // This is a function-like macro definition. Read the argument list.
1736 MI->setIsFunctionLike();
1737 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001738 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001739 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001740 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001741 if (CurLexer->ParsingPreprocessorDirective)
1742 DiscardUntilEndOfDirective();
1743 return;
1744 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001745
Chris Lattner815a1f92006-07-08 20:48:04 +00001746 // Read the first token after the arg list for down below.
1747 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001748 } else if (!Tok.hasLeadingSpace()) {
1749 // C99 requires whitespace between the macro definition and the body. Emit
1750 // a diagnostic for something like "#define X+".
1751 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001752 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001753 } else {
1754 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1755 // one in some cases!
1756 }
1757 } else {
1758 // This is a normal token with leading space. Clear the leading space
1759 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001760 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001761 }
1762
Chris Lattner7e374832006-07-29 03:46:57 +00001763 // If this is a definition of a variadic C99 function-like macro, not using
1764 // the GNU named varargs extension, enabled __VA_ARGS__.
1765
1766 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1767 // This gets unpoisoned where it is allowed.
1768 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1769 if (MI->isC99Varargs())
1770 Ident__VA_ARGS__->setIsPoisoned(false);
1771
Chris Lattner22eb9722006-06-18 05:43:12 +00001772 // Read the rest of the macro body.
1773 while (Tok.getKind() != tok::eom) {
1774 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001775
1776 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001777 // parameters in function-like macro expansions.
1778 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001779 // Get the next token of the macro.
1780 LexUnexpandedToken(Tok);
1781 continue;
1782 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001783
Chris Lattner815a1f92006-07-08 20:48:04 +00001784 // Get the next token of the macro.
1785 LexUnexpandedToken(Tok);
1786
1787 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001788 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001789 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001790 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001791 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001792
1793 // Disable __VA_ARGS__ again.
1794 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001795 return;
1796 }
1797
1798 // Things look ok, add the param name token to the macro.
1799 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001800
Chris Lattner22eb9722006-06-18 05:43:12 +00001801 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001802 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001803 }
Chris Lattner7e374832006-07-29 03:46:57 +00001804
1805 // Disable __VA_ARGS__ again.
1806 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001807
Chris Lattnerbff18d52006-07-06 04:49:18 +00001808 // Check that there is no paste (##) operator at the begining or end of the
1809 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001810 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001811 if (NumTokens != 0) {
1812 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001813 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001814 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001815 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001816 }
1817 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001818 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001819 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001820 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001821 }
1822 }
1823
Chris Lattner13044d92006-07-03 05:16:44 +00001824 // If this is the primary source file, remember that this macro hasn't been
1825 // used yet.
1826 if (isInPrimaryFile())
1827 MI->setIsUsed(false);
1828
Chris Lattner22eb9722006-06-18 05:43:12 +00001829 // Finally, if this identifier already had a macro defined for it, verify that
1830 // the macro bodies are identical and free the old definition.
1831 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001832 if (!OtherMI->isUsed())
1833 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1834
Chris Lattner22eb9722006-06-18 05:43:12 +00001835 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001836 // must be the same. C99 6.10.3.2.
1837 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001838 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1839 MacroNameTok.getIdentifierInfo()->getName());
1840 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1841 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001842 delete OtherMI;
1843 }
1844
1845 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001846}
1847
Chris Lattner063400e2006-10-14 19:54:15 +00001848/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1849void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1850 LexerToken MacroNameTok;
1851 ReadMacroName(MacroNameTok, 1);
1852
1853 // Error reading macro name? If so, diagnostic already issued.
1854 if (MacroNameTok.getKind() == tok::eom)
1855 return;
1856
1857 // Check to see if this is the last token on the #undef line.
1858 CheckEndOfDirective("#define_other_target");
1859
1860 // If there is already a macro defined by this name, turn it into a
1861 // target-specific define.
1862 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1863 MI->setIsTargetSpecific(true);
1864 return;
1865 }
1866
1867 // Mark the identifier as being a macro on some other target.
1868 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1869}
1870
Chris Lattner22eb9722006-06-18 05:43:12 +00001871
1872/// HandleUndefDirective - Implements #undef.
1873///
Chris Lattnercb283342006-06-18 06:48:37 +00001874void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001875 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001876
Chris Lattner22eb9722006-06-18 05:43:12 +00001877 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001878 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001879
1880 // Error reading macro name? If so, diagnostic already issued.
1881 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001882 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001883
1884 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001885 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001886
1887 // Okay, we finally have a valid identifier to undef.
1888 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1889
Chris Lattner063400e2006-10-14 19:54:15 +00001890 // #undef untaints an identifier if it were marked by define_other_target.
1891 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1892
Chris Lattner22eb9722006-06-18 05:43:12 +00001893 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001894 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001895
Chris Lattner13044d92006-07-03 05:16:44 +00001896 if (!MI->isUsed())
1897 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001898
1899 // Free macro definition.
1900 delete MI;
1901 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001902}
1903
1904
Chris Lattnerb8761832006-06-24 21:31:03 +00001905//===----------------------------------------------------------------------===//
1906// Preprocessor Conditional Directive Handling.
1907//===----------------------------------------------------------------------===//
1908
Chris Lattner22eb9722006-06-18 05:43:12 +00001909/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001910/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1911/// if any tokens have been returned or pp-directives activated before this
1912/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001913///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001914void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1915 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001916 ++NumIf;
1917 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001918
Chris Lattner22eb9722006-06-18 05:43:12 +00001919 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001920 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001921
1922 // Error reading macro name? If so, diagnostic already issued.
1923 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001924 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001925
1926 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001927 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1928
1929 // If the start of a top-level #ifdef, inform MIOpt.
1930 if (!ReadAnyTokensBeforeDirective &&
1931 CurLexer->getConditionalStackDepth() == 0) {
1932 assert(isIfndef && "#ifdef shouldn't reach here");
1933 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1934 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001935
Chris Lattner063400e2006-10-14 19:54:15 +00001936 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1937 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001938
Chris Lattner81278c62006-10-14 19:03:49 +00001939 // If there is a macro, process it.
1940 if (MI) {
1941 // Mark it used.
1942 MI->setIsUsed(true);
1943
1944 // If this is the first use of a target-specific macro, warn about it.
1945 if (MI->isTargetSpecific()) {
1946 MI->setIsTargetSpecific(false); // Don't warn on second use.
1947 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1948 diag::port_target_macro_use);
1949 }
Chris Lattner063400e2006-10-14 19:54:15 +00001950 } else {
1951 // Use of a target-specific macro for some other target? If so, warn.
1952 if (MII->isOtherTargetMacro()) {
1953 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1954 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1955 diag::port_target_macro_use);
1956 }
Chris Lattner81278c62006-10-14 19:03:49 +00001957 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001958
Chris Lattner22eb9722006-06-18 05:43:12 +00001959 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001960 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001961 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001962 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001963 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001964 } else {
1965 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001966 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001967 /*Foundnonskip*/false,
1968 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001969 }
1970}
1971
1972/// HandleIfDirective - Implements the #if directive.
1973///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001974void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1975 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001976 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001977
Chris Lattner371ac8a2006-07-04 07:11:10 +00001978 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001979 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001980 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001981
1982 // Should we include the stuff contained by this directive?
1983 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001984 // If this condition is equivalent to #ifndef X, and if this is the first
1985 // directive seen, handle it for the multiple-include optimization.
1986 if (!ReadAnyTokensBeforeDirective &&
1987 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1988 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1989
Chris Lattner22eb9722006-06-18 05:43:12 +00001990 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001991 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001992 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001993 } else {
1994 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001995 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001996 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001997 }
1998}
1999
2000/// HandleEndifDirective - Implements the #endif directive.
2001///
Chris Lattnercb283342006-06-18 06:48:37 +00002002void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002003 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002004
Chris Lattner22eb9722006-06-18 05:43:12 +00002005 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002006 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002007
2008 PPConditionalInfo CondInfo;
2009 if (CurLexer->popConditionalLevel(CondInfo)) {
2010 // No conditionals on the stack: this is an #endif without an #if.
2011 return Diag(EndifToken, diag::err_pp_endif_without_if);
2012 }
2013
Chris Lattner371ac8a2006-07-04 07:11:10 +00002014 // If this the end of a top-level #endif, inform MIOpt.
2015 if (CurLexer->getConditionalStackDepth() == 0)
2016 CurLexer->MIOpt.ExitTopLevelConditional();
2017
Chris Lattner538d7f32006-07-20 04:31:52 +00002018 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002019 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002020}
2021
2022
Chris Lattnercb283342006-06-18 06:48:37 +00002023void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002024 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002025
Chris Lattner22eb9722006-06-18 05:43:12 +00002026 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002027 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002028
2029 PPConditionalInfo CI;
2030 if (CurLexer->popConditionalLevel(CI))
2031 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002032
2033 // If this is a top-level #else, inform the MIOpt.
2034 if (CurLexer->getConditionalStackDepth() == 0)
2035 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002036
2037 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002038 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002039
2040 // Finally, skip the rest of the contents of this block and return the first
2041 // token after it.
2042 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2043 /*FoundElse*/true);
2044}
2045
Chris Lattnercb283342006-06-18 06:48:37 +00002046void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002047 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002048
Chris Lattner22eb9722006-06-18 05:43:12 +00002049 // #elif directive in a non-skipping conditional... start skipping.
2050 // We don't care what the condition is, because we will always skip it (since
2051 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002052 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002053
2054 PPConditionalInfo CI;
2055 if (CurLexer->popConditionalLevel(CI))
2056 return Diag(ElifToken, diag::pp_err_elif_without_if);
2057
Chris Lattner371ac8a2006-07-04 07:11:10 +00002058 // If this is a top-level #elif, inform the MIOpt.
2059 if (CurLexer->getConditionalStackDepth() == 0)
2060 CurLexer->MIOpt.FoundTopLevelElse();
2061
Chris Lattner22eb9722006-06-18 05:43:12 +00002062 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002063 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002064
2065 // Finally, skip the rest of the contents of this block and return the first
2066 // token after it.
2067 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2068 /*FoundElse*/CI.FoundElse);
2069}
Chris Lattnerb8761832006-06-24 21:31:03 +00002070