blob: 57cdbe944070d705101b51333c61f50f38779081 [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 Lattnerb8d6d5a2006-11-21 04:09:30 +000031#include "clang/Lex/PPCallbacks.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000032#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000033#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000034#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000037#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000038#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000039#include <iostream>
40using namespace llvm;
41using namespace clang;
42
43//===----------------------------------------------------------------------===//
44
Chris Lattner02dffbd2006-10-14 07:50:21 +000045Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000046 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000047 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000048 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
49 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000050 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(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 Lattnerb352e3e2006-11-21 06:17:10 +000061
62 // Default to discarding comments.
63 KeepComments = false;
64 KeepMacroComments = false;
65
Chris Lattner22eb9722006-06-18 05:43:12 +000066 // Macro expansion is enabled.
67 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000068 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +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 Lattnerb8d6d5a2006-11-21 04:09:30 +000099PPCallbacks::~PPCallbacks() {
100}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000101
Chris Lattner22eb9722006-06-18 05:43:12 +0000102/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
103/// the specified LexerToken's location, translating the token's start
104/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000105void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000106 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000107 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000108}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000109
110void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
111 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
112 << getSpelling(Tok) << "'";
113
114 if (!DumpFlags) return;
115 std::cerr << "\t";
116 if (Tok.isAtStartOfLine())
117 std::cerr << " [StartOfLine]";
118 if (Tok.hasLeadingSpace())
119 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000120 if (Tok.isExpandDisabled())
121 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000122 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000123 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000124 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
125 << "']";
126 }
127}
128
129void Preprocessor::DumpMacro(const MacroInfo &MI) const {
130 std::cerr << "MACRO: ";
131 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
132 DumpToken(MI.getReplacementToken(i));
133 std::cerr << " ";
134 }
135 std::cerr << "\n";
136}
137
Chris Lattner22eb9722006-06-18 05:43:12 +0000138void Preprocessor::PrintStats() {
139 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000140 std::cerr << NumDirectives << " directives found:\n";
141 std::cerr << " " << NumDefined << " #define.\n";
142 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000143 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000144 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
145 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
146 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
147 std::cerr << " " << NumElse << " #else/#elif.\n";
148 std::cerr << " " << NumEndif << " #endif.\n";
149 std::cerr << " " << NumPragma << " #pragma.\n";
150 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
151
Chris Lattner78186052006-07-09 00:45:31 +0000152 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
153 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000154 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000155 std::cerr << (NumFastTokenPaste+NumTokenPaste)
156 << " token paste (##) operations performed, "
157 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000158}
159
160//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000161// Token Spelling
162//===----------------------------------------------------------------------===//
163
164
165/// getSpelling() - Return the 'spelling' of this token. The spelling of a
166/// token are the characters used to represent the token in the source file
167/// after trigraph expansion and escaped-newline folding. In particular, this
168/// wants to get the true, uncanonicalized, spelling of things like digraphs
169/// UCNs, etc.
170std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
171 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
172
173 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000174 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000175 if (!Tok.needsCleaning())
176 return std::string(TokStart, TokStart+Tok.getLength());
177
Chris Lattnerd01e2912006-06-18 16:22:51 +0000178 std::string Result;
179 Result.reserve(Tok.getLength());
180
Chris Lattneref9eae12006-07-04 22:33:12 +0000181 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000182 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
183 Ptr != End; ) {
184 unsigned CharSize;
185 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
186 Ptr += CharSize;
187 }
188 assert(Result.size() != unsigned(Tok.getLength()) &&
189 "NeedsCleaning flag set on something that didn't need cleaning!");
190 return Result;
191}
192
193/// getSpelling - This method is used to get the spelling of a token into a
194/// preallocated buffer, instead of as an std::string. The caller is required
195/// to allocate enough space for the token, which is guaranteed to be at least
196/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000197///
198/// Note that this method may do two possible things: it may either fill in
199/// the buffer specified with characters, or it may *change the input pointer*
200/// to point to a constant buffer with the data already in it (avoiding a
201/// copy). The caller is not allowed to modify the returned buffer pointer
202/// if an internal buffer is returned.
203unsigned Preprocessor::getSpelling(const LexerToken &Tok,
204 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000205 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
206
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000207 // If this token is an identifier, just return the string from the identifier
208 // table, which is very quick.
209 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
210 Buffer = II->getName();
211 return Tok.getLength();
212 }
213
214 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000215 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000216
217 // If this token contains nothing interesting, return it directly.
218 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000219 Buffer = TokStart;
220 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 }
222 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000223 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
225 Ptr != End; ) {
226 unsigned CharSize;
227 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
228 Ptr += CharSize;
229 }
230 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
231 "NeedsCleaning flag set on something that didn't need cleaning!");
232
233 return OutBuf-Buffer;
234}
235
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000236
237/// CreateString - Plop the specified string into a scratch buffer and return a
238/// location for it. If specified, the source location provides a source
239/// location for the token.
240SourceLocation Preprocessor::
241CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
242 if (SLoc.isValid())
243 return ScratchBuf->getToken(Buf, Len, SLoc);
244 return ScratchBuf->getToken(Buf, Len);
245}
246
247
Chris Lattnerd01e2912006-06-18 16:22:51 +0000248//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000249// Source File Location Methods.
250//===----------------------------------------------------------------------===//
251
Chris Lattner22eb9722006-06-18 05:43:12 +0000252/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
253/// return null on failure. isAngled indicates whether the file reference is
254/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000255const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
256 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000257 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000258 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000259 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000260 // If the header lookup mechanism may be relative to the current file, pass in
261 // info about where the current file is.
262 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000263 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000264 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000265 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000266 }
267
Chris Lattner63dd32b2006-10-20 04:42:40 +0000268 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000269 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000270 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000271 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
272 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000273 if (FE) return FE;
274
275 // Otherwise, see if this is a subframework header. If so, this is relative
276 // to one of the headers on the #include stack. Walk the list of the current
277 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000278 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000279 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000280 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
281 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000282 return FE;
283 }
284
285 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
286 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000287 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000288 CurFileEnt =
289 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000290 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
291 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000292 return FE;
293 }
294 }
295
296 // Otherwise, we really couldn't find the file.
297 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000298}
299
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000300/// isInPrimaryFile - Return true if we're in the top-level file, not in a
301/// #include.
302bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000303 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000304 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000305
Chris Lattner13044d92006-07-03 05:16:44 +0000306 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000307 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000308 if (IncludeMacroStack[i].TheLexer &&
309 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
310 return IncludeMacroStack[i].TheLexer->isMainFile();
311 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000312}
313
314/// getCurrentLexer - Return the current file lexer being lexed from. Note
315/// that this ignores any potentially active macro expansions and _Pragma
316/// expansions going on at the time.
317Lexer *Preprocessor::getCurrentFileLexer() const {
318 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
319
320 // Look for a stacked lexer.
321 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000322 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000323 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
324 return L;
325 }
326 return 0;
327}
328
329
Chris Lattner22eb9722006-06-18 05:43:12 +0000330/// EnterSourceFile - Add a source file to the top of the include stack and
331/// start lexing tokens from it instead of the current buffer. Return true
332/// on failure.
333void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000334 const DirectoryLookup *CurDir,
335 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000336 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000337 ++NumEnteredSourceFiles;
338
Chris Lattner69772b02006-07-02 20:34:39 +0000339 if (MaxIncludeStackDepth < IncludeMacroStack.size())
340 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000341
Chris Lattner22eb9722006-06-18 05:43:12 +0000342 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000343 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000344 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000345 EnterSourceFileWithLexer(TheLexer, CurDir);
346}
Chris Lattner22eb9722006-06-18 05:43:12 +0000347
Chris Lattner69772b02006-07-02 20:34:39 +0000348/// EnterSourceFile - Add a source file to the top of the include stack and
349/// start lexing tokens from it instead of the current buffer.
350void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
351 const DirectoryLookup *CurDir) {
352
353 // Add the current lexer to the include stack.
354 if (CurLexer || CurMacroExpander)
355 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
356 CurMacroExpander));
357
358 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000359 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000360 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000361
362 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000363 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000364 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
365
366 // Get the file entry for the current file.
367 if (const FileEntry *FE =
368 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000369 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000370
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000371 Callbacks->FileChanged(SourceLocation(CurLexer->getCurFileID(), 0),
372 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000373 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000374}
375
Chris Lattner69772b02006-07-02 20:34:39 +0000376
377
Chris Lattner22eb9722006-06-18 05:43:12 +0000378/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000379/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000380void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000381 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
382 CurMacroExpander));
383 CurLexer = 0;
384 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000385
Chris Lattneree8760b2006-07-15 07:42:55 +0000386 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000387}
388
Chris Lattner7667d0d2006-07-16 18:16:58 +0000389/// EnterTokenStream - Add a "macro" context to the top of the include stack,
390/// which will cause the lexer to start returning the specified tokens. Note
391/// that these tokens will be re-macro-expanded when/if expansion is enabled.
392/// This method assumes that the specified stream of tokens has a permanent
393/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000394void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000395 // Save our current state.
396 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
397 CurMacroExpander));
398 CurLexer = 0;
399 CurDirLookup = 0;
400
401 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000402 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000403}
404
405/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
406/// lexer stack. This should only be used in situations where the current
407/// state of the top-of-stack lexer is known.
408void Preprocessor::RemoveTopOfLexerStack() {
409 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
410 delete CurLexer;
411 delete CurMacroExpander;
412 CurLexer = IncludeMacroStack.back().TheLexer;
413 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
414 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
415 IncludeMacroStack.pop_back();
416}
417
Chris Lattner22eb9722006-06-18 05:43:12 +0000418//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000419// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000420//===----------------------------------------------------------------------===//
421
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000422/// RegisterBuiltinMacro - Register the specified identifier in the identifier
423/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000424IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000425 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000426 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000427
428 // Mark it as being a macro that is builtin.
429 MacroInfo *MI = new MacroInfo(SourceLocation());
430 MI->setIsBuiltinMacro();
431 Id->setMacroInfo(MI);
432 return Id;
433}
434
435
Chris Lattner677757a2006-06-28 05:26:32 +0000436/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
437/// identifier table.
438void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000439 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000440 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000441 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
442 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000443 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000444
445 // GCC Extensions.
446 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
447 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000448 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000449}
450
Chris Lattnerc2395832006-07-09 00:57:04 +0000451/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
452/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000453static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
454 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000455 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
456
457 // If the token isn't an identifier, it's always literally expanded.
458 if (II == 0) return true;
459
460 // If the identifier is a macro, and if that macro is enabled, it may be
461 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000462 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
463 // Fast expanding "#define X X" is ok, because X would be disabled.
464 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000465 return false;
466
467 // If this is an object-like macro invocation, it is safe to trivially expand
468 // it.
469 if (MI->isObjectLike()) return true;
470
471 // If this is a function-like macro invocation, it's safe to trivially expand
472 // as long as the identifier is not a macro argument.
473 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
474 I != E; ++I)
475 if (*I == II)
476 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000477
Chris Lattnerc2395832006-07-09 00:57:04 +0000478 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000479}
480
Chris Lattnerc2395832006-07-09 00:57:04 +0000481
Chris Lattnerafe603f2006-07-11 04:02:46 +0000482/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
483/// lexed is a '('. If so, consume the token and return true, if not, this
484/// method should have no observable side-effect on the lexed tokens.
485bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000486 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000487 unsigned Val;
488 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000489 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000490 else
491 Val = CurMacroExpander->isNextTokenLParen();
492
493 if (Val == 2) {
494 // If we ran off the end of the lexer or macro expander, walk the include
495 // stack, looking for whatever will return the next token.
496 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
497 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
498 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000499 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000500 else
501 Val = Entry.TheMacroExpander->isNextTokenLParen();
502 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000503 }
504
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000505 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
506 // have found something that isn't a '(' or we found the end of the
507 // translation unit. In either case, return false.
508 if (Val != 1)
509 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000510
511 LexerToken Tok;
512 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000513 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
514 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000515}
Chris Lattner677757a2006-06-28 05:26:32 +0000516
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000517/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
518/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000519bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000520 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000521
522 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
523 if (MI->isBuiltinMacro()) {
524 ExpandBuiltinMacro(Identifier);
525 return false;
526 }
527
Chris Lattner81278c62006-10-14 19:03:49 +0000528 // If this is the first use of a target-specific macro, warn about it.
529 if (MI->isTargetSpecific()) {
530 MI->setIsTargetSpecific(false); // Don't warn on second use.
531 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
532 diag::port_target_macro_use);
533 }
534
Chris Lattneree8760b2006-07-15 07:42:55 +0000535 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000536 /// for each macro argument, the list of tokens that were provided to the
537 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000538 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000539
540 // If this is a function-like macro, read the arguments.
541 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000542 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
543 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000544 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000545 return true;
546
Chris Lattner78186052006-07-09 00:45:31 +0000547 // Remember that we are now parsing the arguments to a macro invocation.
548 // Preprocessor directives used inside macro arguments are not portable, and
549 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000550 InMacroArgs = true;
551 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000552
553 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000554 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000555
556 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000557 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000558
559 ++NumFnMacroExpanded;
560 } else {
561 ++NumMacroExpanded;
562 }
Chris Lattner13044d92006-07-03 05:16:44 +0000563
564 // Notice that this macro has been used.
565 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000566
567 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000568
569 // If this macro expands to no tokens, don't bother to push it onto the
570 // expansion stack, only to take it right back off.
571 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000572 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000573 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000574
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000575 // Ignore this macro use, just return the next token in the current
576 // buffer.
577 bool HadLeadingSpace = Identifier.hasLeadingSpace();
578 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
579
580 Lex(Identifier);
581
582 // If the identifier isn't on some OTHER line, inherit the leading
583 // whitespace/first-on-a-line property of this token. This handles
584 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
585 // empty.
586 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000587 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
588 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000589 }
590 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000591 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000592
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000593 } else if (MI->getNumTokens() == 1 &&
594 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000595 // Otherwise, if this macro expands into a single trivially-expanded
596 // token: expand it now. This handles common cases like
597 // "#define VAL 42".
598
599 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
600 // identifier to the expanded token.
601 bool isAtStartOfLine = Identifier.isAtStartOfLine();
602 bool hasLeadingSpace = Identifier.hasLeadingSpace();
603
604 // Remember where the token is instantiated.
605 SourceLocation InstantiateLoc = Identifier.getLocation();
606
607 // Replace the result token.
608 Identifier = MI->getReplacementToken(0);
609
610 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000611 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
612 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000613
614 // Update the tokens location to include both its logical and physical
615 // locations.
616 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000617 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000618 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000619
Chris Lattner6e4bf522006-07-27 06:59:25 +0000620 // If this is #define X X, we must mark the result as unexpandible.
621 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
622 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000623 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000624
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000625 // Since this is not an identifier token, it can't be macro expanded, so
626 // we're done.
627 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000628 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000629 }
630
Chris Lattner78186052006-07-09 00:45:31 +0000631 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000632 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000633
634 // Now that the macro is at the top of the include stack, ask the
635 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000636 Lex(Identifier);
637 return false;
638}
639
Chris Lattneree8760b2006-07-15 07:42:55 +0000640/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000641/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000642/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000643MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
644 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000645 // The number of fixed arguments to parse.
646 unsigned NumFixedArgsLeft = MI->getNumArgs();
647 bool isVariadic = MI->isVariadic();
648
Chris Lattner78186052006-07-09 00:45:31 +0000649 // Outer loop, while there are more arguments, keep reading them.
650 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000651 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000652 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000653
654 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000655 // argument is separated by an EOF token. Use a SmallVector so we can avoid
656 // heap allocations in the common case.
657 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000658
659 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000660 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000661 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
662 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000663
Chris Lattner78186052006-07-09 00:45:31 +0000664 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000665 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
666 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000667 LexUnexpandedToken(Tok);
668
669 if (Tok.getKind() == tok::eof) {
670 Diag(MacroName, diag::err_unterm_macro_invoc);
671 // Do not lose the EOF. Return it to the client.
672 MacroName = Tok;
673 return 0;
674 } else if (Tok.getKind() == tok::r_paren) {
675 // If we found the ) token, the macro arg list is done.
676 if (NumParens-- == 0)
677 break;
678 } else if (Tok.getKind() == tok::l_paren) {
679 ++NumParens;
680 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
681 // Comma ends this argument if there are more fixed arguments expected.
682 if (NumFixedArgsLeft)
683 break;
684
Chris Lattner2ada5d32006-07-15 07:51:24 +0000685 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000686 if (!isVariadic) {
687 // Emit the diagnostic at the macro name in case there is a missing ).
688 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000689 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000690 return 0;
691 }
692 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000693 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000694 // If this is a comment token in the argument list and we're just in
695 // -C mode (not -CC mode), discard the comment.
696 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000697 }
698
699 ArgTokens.push_back(Tok);
700 }
701
Chris Lattnera12dd152006-07-11 04:09:02 +0000702 // Empty arguments are standard in C99 and supported as an extension in
703 // other modes.
704 if (ArgTokens.empty() && !Features.C99)
705 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000706
Chris Lattner36b6e812006-07-21 06:38:30 +0000707 // Add a marker EOF token to the end of the token list for this argument.
708 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000709 EOFTok.startToken();
710 EOFTok.setKind(tok::eof);
711 EOFTok.setLocation(Tok.getLocation());
712 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000713 ArgTokens.push_back(EOFTok);
714 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000715 --NumFixedArgsLeft;
716 };
717
718 // Okay, we either found the r_paren. Check to see if we parsed too few
719 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000720 unsigned MinArgsExpected = MI->getNumArgs();
721
Chris Lattner775d8322006-07-29 04:39:41 +0000722 // See MacroArgs instance var for description of this.
723 bool isVarargsElided = false;
724
Chris Lattner2ada5d32006-07-15 07:51:24 +0000725 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000726 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000727 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000728 // Varargs where the named vararg parameter is missing: ok as extension.
729 // #define A(x, ...)
730 // A("blah")
731 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000732
733 // Remember this occurred if this is a C99 macro invocation with at least
734 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000735 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000736 } else if (MI->getNumArgs() == 1) {
737 // #define A(x)
738 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000739 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000740
741 // Empty arguments are standard in C99 and supported as an extension in
742 // other modes.
743 if (ArgTokens.empty() && !Features.C99)
744 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000745 } else {
746 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000747 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000748 return 0;
749 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000750
751 // Add a marker EOF token to the end of the token list for this argument.
752 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000753 Tok.startToken();
754 Tok.setKind(tok::eof);
755 Tok.setLocation(EndLoc);
756 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000757 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000758 }
759
Chris Lattner775d8322006-07-29 04:39:41 +0000760 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000761}
762
Chris Lattnerc673f902006-06-30 06:10:41 +0000763/// ComputeDATE_TIME - Compute the current time, enter it into the specified
764/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
765/// the identifier tokens inserted.
766static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000767 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000768 time_t TT = time(0);
769 struct tm *TM = localtime(&TT);
770
771 static const char * const Months[] = {
772 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
773 };
774
775 char TmpBuffer[100];
776 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
777 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000778 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000779
780 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000781 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000782}
783
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000784/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
785/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000786void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000787 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000788 IdentifierInfo *II = Tok.getIdentifierInfo();
789 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000790
791 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
792 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000793 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000794 return Handle_Pragma(Tok);
795
Chris Lattner78186052006-07-09 00:45:31 +0000796 ++NumBuiltinMacroExpanded;
797
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000798 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000799
800 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000801 Tok.setIdentifierInfo(0);
802 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000803
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000804 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000805 // __LINE__ expands to a simple numeric value.
806 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
807 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000808 Tok.setKind(tok::numeric_constant);
809 Tok.setLength(Length);
810 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000811 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000812 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000813 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000814 Diag(Tok, diag::ext_pp_base_file);
815 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
816 while (NextLoc.getFileID() != 0) {
817 Loc = NextLoc;
818 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
819 }
820 }
821
Chris Lattner0766e592006-07-03 01:07:01 +0000822 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
823 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000824 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000825 Tok.setKind(tok::string_literal);
826 Tok.setLength(FN.size());
827 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000828 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000829 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000830 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000831 Tok.setKind(tok::string_literal);
832 Tok.setLength(strlen("\"Mmm dd yyyy\""));
833 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000834 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000835 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000836 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000837 Tok.setKind(tok::string_literal);
838 Tok.setLength(strlen("\"hh:mm:ss\""));
839 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000840 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000841 Diag(Tok, diag::ext_pp_include_level);
842
843 // Compute the include depth of this token.
844 unsigned Depth = 0;
845 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
846 for (; Loc.getFileID() != 0; ++Depth)
847 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
848
849 // __INCLUDE_LEVEL__ expands to a simple numeric value.
850 sprintf(TmpBuffer, "%u", Depth);
851 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000852 Tok.setKind(tok::numeric_constant);
853 Tok.setLength(Length);
854 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000855 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000856 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
857 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
858 Diag(Tok, diag::ext_pp_timestamp);
859
860 // Get the file that we are lexing out of. If we're currently lexing from
861 // a macro, dig into the include stack.
862 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000863 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000864
865 if (TheLexer)
866 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
867
868 // If this file is older than the file it depends on, emit a diagnostic.
869 const char *Result;
870 if (CurFile) {
871 time_t TT = CurFile->getModificationTime();
872 struct tm *TM = localtime(&TT);
873 Result = asctime(TM);
874 } else {
875 Result = "??? ??? ?? ??:??:?? ????\n";
876 }
877 TmpBuffer[0] = '"';
878 strcpy(TmpBuffer+1, Result);
879 unsigned Len = strlen(TmpBuffer);
880 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000881 Tok.setKind(tok::string_literal);
882 Tok.setLength(Len);
883 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000884 } else {
885 assert(0 && "Unknown identifier!");
886 }
887}
Chris Lattner677757a2006-06-28 05:26:32 +0000888
Chris Lattner13044d92006-07-03 05:16:44 +0000889namespace {
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000890struct UnusedIdentifierReporter : public CStringMapVisitor {
Chris Lattner13044d92006-07-03 05:16:44 +0000891 Preprocessor &PP;
892 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
893
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000894 void Visit(const char *Key, void *Value) const {
895 IdentifierInfo &II = *static_cast<IdentifierInfo*>(Value);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000896 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
897 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000898 }
899};
900}
901
Chris Lattner677757a2006-06-28 05:26:32 +0000902//===----------------------------------------------------------------------===//
903// Lexer Event Handling.
904//===----------------------------------------------------------------------===//
905
Chris Lattnercefc7682006-07-08 08:28:12 +0000906/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
907/// identifier information for the token and install it into the token.
908IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
909 const char *BufPtr) {
910 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
911 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
912
913 // Look up this token, see if it is a macro, or if it is a language keyword.
914 IdentifierInfo *II;
915 if (BufPtr && !Identifier.needsCleaning()) {
916 // No cleaning needed, just use the characters from the lexed buffer.
917 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
918 } else {
919 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
920 const char *TmpBuf = (char*)alloca(Identifier.getLength());
921 unsigned Size = getSpelling(Identifier, TmpBuf);
922 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
923 }
Chris Lattner8c204872006-10-14 05:19:21 +0000924 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000925 return II;
926}
927
928
Chris Lattner677757a2006-06-28 05:26:32 +0000929/// HandleIdentifier - This callback is invoked when the lexer reads an
930/// identifier. This callback looks up the identifier in the map and/or
931/// potentially macro expands it or turns it into a named token (like 'for').
932void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000933 assert(Identifier.getIdentifierInfo() &&
934 "Can't handle identifiers without identifier info!");
935
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000936 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000937
938 // If this identifier was poisoned, and if it was not produced from a macro
939 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000940 if (II.isPoisoned() && CurLexer) {
941 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
942 Diag(Identifier, diag::err_pp_used_poisoned_id);
943 else
944 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
945 }
Chris Lattner677757a2006-06-28 05:26:32 +0000946
Chris Lattner78186052006-07-09 00:45:31 +0000947 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000948 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000949 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
950 if (MI->isEnabled()) {
951 if (!HandleMacroExpandedIdentifier(Identifier, MI))
952 return;
953 } else {
954 // C99 6.10.3.4p2 says that a disabled macro may never again be
955 // expanded, even if it's in a context where it could be expanded in the
956 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000957 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000958 }
959 }
Chris Lattner063400e2006-10-14 19:54:15 +0000960 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
961 // If this identifier is a macro on some other target, emit a diagnostic.
962 // This diagnosic is only emitted when macro expansion is enabled, because
963 // the macro would not have been expanded for the other target either.
964 II.setIsOtherTargetMacro(false); // Don't warn on second use.
965 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
966 diag::port_target_macro_use);
967
968 }
Chris Lattner677757a2006-06-28 05:26:32 +0000969
Chris Lattner5b9f4892006-11-21 17:23:33 +0000970 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
971 // then we act as if it is the actual operator and not the textual
972 // representation of it.
973 if (II.isCPlusPlusOperatorKeyword())
974 Identifier.setIdentifierInfo(0);
975
Chris Lattner677757a2006-06-28 05:26:32 +0000976 // Change the kind of this identifier to the appropriate token kind, e.g.
977 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000978 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000979
980 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000981 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000982}
983
Chris Lattner22eb9722006-06-18 05:43:12 +0000984/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
985/// the current file. This either returns the EOF token or pops a level off
986/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000987bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000988 assert(!CurMacroExpander &&
989 "Ending a file when currently in a macro!");
990
Chris Lattner371ac8a2006-07-04 07:11:10 +0000991 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000992 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000993 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000994 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000995 // Okay, this has a controlling macro, remember in PerFileInfo.
996 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000997 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
998 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000999 }
1000 }
1001
Chris Lattner22eb9722006-06-18 05:43:12 +00001002 // If this is a #include'd file, pop it off the include stack and continue
1003 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001004 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001005 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001006 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001007
1008 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001009 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001010 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1011
1012 // Get the file entry for the current file.
1013 if (const FileEntry *FE =
1014 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001015 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001016
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001017 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1018 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001019 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001020
1021 // Client should lex another token.
1022 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001023 }
1024
Chris Lattner8c204872006-10-14 05:19:21 +00001025 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001026 CurLexer->BufferPtr = CurLexer->BufferEnd;
1027 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001028 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001029
1030 // We're done with the #included file.
1031 delete CurLexer;
1032 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001033
Chris Lattner03f83482006-07-10 06:16:26 +00001034 // This is the end of the top-level file. If the diag::pp_macro_not_used
1035 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1036 // have not been used.
1037 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1038 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001039
1040 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001041}
1042
1043/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001044/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001045bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001046 assert(CurMacroExpander && !CurLexer &&
1047 "Ending a macro when currently in a #include file!");
1048
Chris Lattner22eb9722006-06-18 05:43:12 +00001049 delete CurMacroExpander;
1050
Chris Lattner69772b02006-07-02 20:34:39 +00001051 // Handle this like a #include file being popped off the stack.
1052 CurMacroExpander = 0;
1053 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001054}
1055
1056
1057//===----------------------------------------------------------------------===//
1058// Utility Methods for Preprocessor Directive Handling.
1059//===----------------------------------------------------------------------===//
1060
1061/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1062/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001063void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001064 LexerToken Tmp;
1065 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001066 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001067 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001068}
1069
1070/// ReadMacroName - Lex and validate a macro name, which occurs after a
1071/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001072/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1073/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001074/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001075void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001076 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001077 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001078
1079 // Missing macro name?
1080 if (MacroNameTok.getKind() == tok::eom)
1081 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1082
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001083 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1084 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001085 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001086 // Fall through on error.
1087 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001088 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001089
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001090 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1091 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001092 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001093 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001094 } else if (isDefineUndef && II->getMacroInfo() &&
1095 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001096 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001097 if (isDefineUndef == 1)
1098 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1099 else
1100 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001101 } else {
1102 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001103 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001104 }
1105
Chris Lattner22eb9722006-06-18 05:43:12 +00001106 // Invalid macro name, read and discard the rest of the line. Then set the
1107 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001108 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001109 return DiscardUntilEndOfDirective();
1110}
1111
1112/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1113/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001114void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001115 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001116 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001117 // There should be no tokens after the directive, but we allow them as an
1118 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001119 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1120 Lex(Tmp);
1121
Chris Lattner22eb9722006-06-18 05:43:12 +00001122 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001123 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1124 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001125 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001126}
1127
1128
1129
1130/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1131/// decided that the subsequent tokens are in the #if'd out portion of the
1132/// file. Lex the rest of the file, until we see an #endif. If
1133/// FoundNonSkipPortion is true, then we have already emitted code for part of
1134/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1135/// is true, then #else directives are ok, if not, then we have already seen one
1136/// so a #else directive is a duplicate. When this returns, the caller can lex
1137/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001138void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001139 bool FoundNonSkipPortion,
1140 bool FoundElse) {
1141 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001142 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001143 "Lexing a macro, not a file?");
1144
1145 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1146 FoundNonSkipPortion, FoundElse);
1147
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001148 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1149 // disabling warnings, etc.
1150 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001151 LexerToken Tok;
1152 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001153 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001154
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001155 // If this is the end of the buffer, we have an error.
1156 if (Tok.getKind() == tok::eof) {
1157 // Emit errors for each unterminated conditional on the stack, including
1158 // the current one.
1159 while (!CurLexer->ConditionalStack.empty()) {
1160 Diag(CurLexer->ConditionalStack.back().IfLoc,
1161 diag::err_pp_unterminated_conditional);
1162 CurLexer->ConditionalStack.pop_back();
1163 }
1164
1165 // Just return and let the caller lex after this #include.
1166 break;
1167 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001168
1169 // If this token is not a preprocessor directive, just skip it.
1170 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1171 continue;
1172
1173 // We just parsed a # character at the start of a line, so we're in
1174 // directive mode. Tell the lexer this so any newlines we see will be
1175 // converted into an EOM token (this terminates the macro).
1176 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001177 CurLexer->KeepCommentMode = false;
1178
Chris Lattner22eb9722006-06-18 05:43:12 +00001179
1180 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001181 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001182
1183 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1184 // something bogus), skip it.
1185 if (Tok.getKind() != tok::identifier) {
1186 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001187 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001188 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001189 continue;
1190 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001191
Chris Lattner22eb9722006-06-18 05:43:12 +00001192 // If the first letter isn't i or e, it isn't intesting to us. We know that
1193 // this is safe in the face of spelling differences, because there is no way
1194 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001195 // allows us to avoid looking up the identifier info for #define/#undef and
1196 // other common directives.
1197 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1198 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001199 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1200 FirstChar != 'i' && FirstChar != 'e') {
1201 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001202 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001203 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001204 continue;
1205 }
1206
Chris Lattnere60165f2006-06-22 06:36:29 +00001207 // Get the identifier name without trigraphs or embedded newlines. Note
1208 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1209 // when skipping.
1210 // TODO: could do this with zero copies in the no-clean case by using
1211 // strncmp below.
1212 char Directive[20];
1213 unsigned IdLen;
1214 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1215 IdLen = Tok.getLength();
1216 memcpy(Directive, RawCharData, IdLen);
1217 Directive[IdLen] = 0;
1218 } else {
1219 std::string DirectiveStr = getSpelling(Tok);
1220 IdLen = DirectiveStr.size();
1221 if (IdLen >= 20) {
1222 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001223 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001224 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001225 continue;
1226 }
1227 memcpy(Directive, &DirectiveStr[0], IdLen);
1228 Directive[IdLen] = 0;
1229 }
1230
Chris Lattner22eb9722006-06-18 05:43:12 +00001231 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001232 if ((IdLen == 2) || // "if"
1233 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1234 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001235 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1236 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001237 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001238 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001239 /*foundnonskip*/false,
1240 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001241 }
1242 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001243 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001244 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001245 PPConditionalInfo CondInfo;
1246 CondInfo.WasSkipping = true; // Silence bogus warning.
1247 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001248 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001249 assert(!InCond && "Can't be skipping if not in a conditional!");
1250
1251 // If we popped the outermost skipping block, we're done skipping!
1252 if (!CondInfo.WasSkipping)
1253 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001254 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001255 // #else directive in a skipping conditional. If not in some other
1256 // skipping conditional, and if #else hasn't already been seen, enter it
1257 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001258 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001259 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1260
1261 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001262 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001263
1264 // Note that we've seen a #else in this conditional.
1265 CondInfo.FoundElse = true;
1266
1267 // If the conditional is at the top level, and the #if block wasn't
1268 // entered, enter the #else block now.
1269 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1270 CondInfo.FoundNonSkip = true;
1271 break;
1272 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001273 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001274 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1275
1276 bool ShouldEnter;
1277 // If this is in a skipping block or if we're already handled this #if
1278 // block, don't bother parsing the condition.
1279 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001280 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001281 ShouldEnter = false;
1282 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001283 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001284 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001285 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1286 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001287 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001288 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001289 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001290 }
1291
1292 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001293 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001294
1295 // If this condition is true, enter it!
1296 if (ShouldEnter) {
1297 CondInfo.FoundNonSkip = true;
1298 break;
1299 }
1300 }
1301 }
1302
1303 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001304 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001305 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001306 }
1307
1308 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1309 // of the file, just stop skipping and return to lexing whatever came after
1310 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001311 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001312}
1313
1314//===----------------------------------------------------------------------===//
1315// Preprocessor Directive Handling.
1316//===----------------------------------------------------------------------===//
1317
1318/// HandleDirective - This callback is invoked when the lexer sees a # token
1319/// at the start of a line. This consumes the directive, modifies the
1320/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1321/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001322void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001323 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001324
1325 // We just parsed a # character at the start of a line, so we're in directive
1326 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001327 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001328 CurLexer->ParsingPreprocessorDirective = true;
1329
1330 ++NumDirectives;
1331
Chris Lattner371ac8a2006-07-04 07:11:10 +00001332 // We are about to read a token. For the multiple-include optimization FA to
1333 // work, we have to remember if we had read any tokens *before* this
1334 // pp-directive.
1335 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1336
Chris Lattner78186052006-07-09 00:45:31 +00001337 // Read the next token, the directive flavor. This isn't expanded due to
1338 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001339 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001340
Chris Lattner78186052006-07-09 00:45:31 +00001341 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1342 // #define A(x) #x
1343 // A(abc
1344 // #warning blah
1345 // def)
1346 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001347 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001348 Diag(Result, diag::ext_embedded_directive);
1349
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001350TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001351 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001352 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001353 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001354 case tok::comment:
1355 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1356 LexUnexpandedToken(Result);
1357 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001358
Chris Lattner22eb9722006-06-18 05:43:12 +00001359 case tok::numeric_constant:
1360 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001361 DiscardUntilEndOfDirective();
1362 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001363 default:
1364 IdentifierInfo *II = Result.getIdentifierInfo();
1365 if (II == 0) break; // Not an identifier.
1366
1367 // Ask what the preprocessor keyword ID is.
1368 switch (II->getPPKeywordID()) {
1369 default: break;
1370 // C99 6.10.1 - Conditional Inclusion.
1371 case tok::pp_if:
1372 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1373 case tok::pp_ifdef:
1374 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1375 case tok::pp_ifndef:
1376 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1377 case tok::pp_elif:
1378 return HandleElifDirective(Result);
1379 case tok::pp_else:
1380 return HandleElseDirective(Result);
1381 case tok::pp_endif:
1382 return HandleEndifDirective(Result);
1383
1384 // C99 6.10.2 - Source File Inclusion.
1385 case tok::pp_include:
1386 return HandleIncludeDirective(Result); // Handle #include.
1387
1388 // C99 6.10.3 - Macro Replacement.
1389 case tok::pp_define:
1390 return HandleDefineDirective(Result, false);
1391 case tok::pp_undef:
1392 return HandleUndefDirective(Result);
1393
1394 // C99 6.10.4 - Line Control.
1395 case tok::pp_line:
1396 // FIXME: implement #line
1397 DiscardUntilEndOfDirective();
1398 return;
1399
1400 // C99 6.10.5 - Error Directive.
1401 case tok::pp_error:
1402 return HandleUserDiagnosticDirective(Result, false);
1403
1404 // C99 6.10.6 - Pragma Directive.
1405 case tok::pp_pragma:
1406 return HandlePragmaDirective();
1407
1408 // GNU Extensions.
1409 case tok::pp_import:
1410 return HandleImportDirective(Result);
1411 case tok::pp_include_next:
1412 return HandleIncludeNextDirective(Result);
1413
1414 case tok::pp_warning:
1415 Diag(Result, diag::ext_pp_warning_directive);
1416 return HandleUserDiagnosticDirective(Result, true);
1417 case tok::pp_ident:
1418 return HandleIdentSCCSDirective(Result);
1419 case tok::pp_sccs:
1420 return HandleIdentSCCSDirective(Result);
1421 case tok::pp_assert:
1422 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001423 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001424 case tok::pp_unassert:
1425 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001426 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001427
1428 // clang extensions.
1429 case tok::pp_define_target:
1430 return HandleDefineDirective(Result, true);
1431 case tok::pp_define_other_target:
1432 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001433 }
1434 break;
1435 }
1436
1437 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001438 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001439
1440 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001441 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001442
1443 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001444}
1445
Chris Lattner01d66cc2006-07-03 22:16:27 +00001446void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001447 bool isWarning) {
1448 // Read the rest of the line raw. We do this because we don't want macros
1449 // to be expanded and we don't require that the tokens be valid preprocessing
1450 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1451 // collapse multiple consequtive white space between tokens, but this isn't
1452 // specified by the standard.
1453 std::string Message = CurLexer->ReadToEndOfLine();
1454
1455 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001456 return Diag(Tok, DiagID, Message);
1457}
1458
1459/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1460///
1461void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001462 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001463 Diag(Tok, diag::ext_pp_ident_directive);
1464
Chris Lattner371ac8a2006-07-04 07:11:10 +00001465 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001466 LexerToken StrTok;
1467 Lex(StrTok);
1468
1469 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001470 if (StrTok.getKind() != tok::string_literal &&
1471 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001472 return Diag(StrTok, diag::err_pp_malformed_ident);
1473
1474 // Verify that there is nothing after the string, other than EOM.
1475 CheckEndOfDirective("#ident");
1476
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001477 if (Callbacks)
1478 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001479}
1480
Chris Lattnerb8761832006-06-24 21:31:03 +00001481//===----------------------------------------------------------------------===//
1482// Preprocessor Include Directive Handling.
1483//===----------------------------------------------------------------------===//
1484
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001485/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1486/// checked and spelled filename, e.g. as an operand of #include. This returns
1487/// true if the input filename was in <>'s or false if it were in ""'s. The
1488/// caller is expected to provide a buffer that is large enough to hold the
1489/// spelling of the filename, but is also expected to handle the case when
1490/// this method decides to use a different buffer.
1491bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1492 const char *&BufStart,
1493 const char *&BufEnd) {
1494 // Get the text form of the filename.
1495 unsigned Len = getSpelling(FilenameTok, BufStart);
1496 BufEnd = BufStart+Len;
1497 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1498
1499 // Make sure the filename is <x> or "x".
1500 bool isAngled;
1501 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 = true;
1508 } else if (BufStart[0] == '"') {
1509 if (BufEnd[-1] != '"') {
1510 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1511 BufStart = 0;
1512 return true;
1513 }
1514 isAngled = false;
1515 } else {
1516 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1517 BufStart = 0;
1518 return true;
1519 }
1520
1521 // Diagnose #include "" as invalid.
1522 if (BufEnd-BufStart <= 2) {
1523 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1524 BufStart = 0;
1525 return "";
1526 }
1527
1528 // Skip the brackets.
1529 ++BufStart;
1530 --BufEnd;
1531 return isAngled;
1532}
1533
Chris Lattner22eb9722006-06-18 05:43:12 +00001534/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1535/// file to be included from the lexer, then include it! This is a common
1536/// routine with functionality shared between #include, #include_next and
1537/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001538void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001539 const DirectoryLookup *LookupFrom,
1540 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001541
Chris Lattner22eb9722006-06-18 05:43:12 +00001542 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001543 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001544
1545 // If the token kind is EOM, the error has already been diagnosed.
1546 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001547 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001548
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001549 // Reserve a buffer to get the spelling.
1550 SmallVector<char, 128> FilenameBuffer;
1551 FilenameBuffer.resize(FilenameTok.getLength());
1552
1553 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1554 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1555 FilenameStart, FilenameEnd);
1556 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1557 // error.
1558 if (FilenameStart == 0)
1559 return;
1560
Chris Lattner269c2322006-06-25 06:23:00 +00001561 // Verify that there is nothing after the filename, other than EOM. Use the
1562 // preprocessor to lex this in case lexing the filename entered a macro.
1563 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001564
1565 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001566 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001567 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1568
Chris Lattner22eb9722006-06-18 05:43:12 +00001569 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001570 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001571 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001572 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001573 if (File == 0)
1574 return Diag(FilenameTok, diag::err_pp_file_not_found);
1575
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001576 // Ask HeaderInfo if we should enter this #include file.
1577 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1578 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001579 return;
1580 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001581
1582 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001583 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001584 if (FileID == 0)
1585 return Diag(FilenameTok, diag::err_pp_file_not_found);
1586
1587 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001588 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001589}
1590
1591/// HandleIncludeNextDirective - Implements #include_next.
1592///
Chris Lattnercb283342006-06-18 06:48:37 +00001593void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1594 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001595
1596 // #include_next is like #include, except that we start searching after
1597 // the current found directory. If we can't do this, issue a
1598 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001599 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001600 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001601 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001602 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001603 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001604 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001605 } else {
1606 // Start looking up in the next directory.
1607 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001608 }
1609
1610 return HandleIncludeDirective(IncludeNextTok, Lookup);
1611}
1612
1613/// HandleImportDirective - Implements #import.
1614///
Chris Lattnercb283342006-06-18 06:48:37 +00001615void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1616 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001617
1618 return HandleIncludeDirective(ImportTok, 0, true);
1619}
1620
Chris Lattnerb8761832006-06-24 21:31:03 +00001621//===----------------------------------------------------------------------===//
1622// Preprocessor Macro Directive Handling.
1623//===----------------------------------------------------------------------===//
1624
Chris Lattnercefc7682006-07-08 08:28:12 +00001625/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1626/// definition has just been read. Lex the rest of the arguments and the
1627/// closing ), updating MI with what we learn. Return true if an error occurs
1628/// parsing the arg list.
1629bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1630 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001631 while (1) {
1632 LexUnexpandedToken(Tok);
1633 switch (Tok.getKind()) {
1634 case tok::r_paren:
1635 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001636 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001637 // Otherwise we have #define FOO(A,)
1638 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1639 return true;
1640 case tok::ellipsis: // #define X(... -> C99 varargs
1641 // Warn if use of C99 feature in non-C99 mode.
1642 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1643
1644 // Lex the token after the identifier.
1645 LexUnexpandedToken(Tok);
1646 if (Tok.getKind() != tok::r_paren) {
1647 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1648 return true;
1649 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001650 // Add the __VA_ARGS__ identifier as an argument.
1651 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001652 MI->setIsC99Varargs();
1653 return false;
1654 case tok::eom: // #define X(
1655 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1656 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001657 default:
1658 // Handle keywords and identifiers here to accept things like
1659 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001660 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001661 if (II == 0) {
1662 // #define X(1
1663 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1664 return true;
1665 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001666
1667 // If this is already used as an argument, it is used multiple times (e.g.
1668 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001669 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001670 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1671 return true;
1672 }
1673
1674 // Add the argument to the macro info.
1675 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001676
1677 // Lex the token after the identifier.
1678 LexUnexpandedToken(Tok);
1679
1680 switch (Tok.getKind()) {
1681 default: // #define X(A B
1682 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1683 return true;
1684 case tok::r_paren: // #define X(A)
1685 return false;
1686 case tok::comma: // #define X(A,
1687 break;
1688 case tok::ellipsis: // #define X(A... -> GCC extension
1689 // Diagnose extension.
1690 Diag(Tok, diag::ext_named_variadic_macro);
1691
1692 // Lex the token after the identifier.
1693 LexUnexpandedToken(Tok);
1694 if (Tok.getKind() != tok::r_paren) {
1695 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1696 return true;
1697 }
1698
1699 MI->setIsGNUVarargs();
1700 return false;
1701 }
1702 }
1703 }
1704}
1705
Chris Lattner22eb9722006-06-18 05:43:12 +00001706/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001707/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1708/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001709///
Chris Lattner81278c62006-10-14 19:03:49 +00001710void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1711 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001712 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001713
Chris Lattner22eb9722006-06-18 05:43:12 +00001714 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001715 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001716
1717 // Error reading macro name? If so, diagnostic already issued.
1718 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001719 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001720
Chris Lattner457fc152006-07-29 06:30:25 +00001721 // If we are supposed to keep comments in #defines, reenable comment saving
1722 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001723 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001724
Chris Lattner063400e2006-10-14 19:54:15 +00001725 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001726 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001727 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001728
Chris Lattner063400e2006-10-14 19:54:15 +00001729 // If the identifier is an 'other target' macro, clear this bit.
1730 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1731
1732
Chris Lattner22eb9722006-06-18 05:43:12 +00001733 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001734 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001735
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001736 // If this is a function-like macro definition, parse the argument list,
1737 // marking each of the identifiers as being used as macro arguments. Also,
1738 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001739 if (Tok.getKind() == tok::eom) {
1740 // If there is no body to this macro, we have no special handling here.
1741 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001742 // This is a function-like macro definition. Read the argument list.
1743 MI->setIsFunctionLike();
1744 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001745 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001746 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001747 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001748 if (CurLexer->ParsingPreprocessorDirective)
1749 DiscardUntilEndOfDirective();
1750 return;
1751 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001752
Chris Lattner815a1f92006-07-08 20:48:04 +00001753 // Read the first token after the arg list for down below.
1754 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001755 } else if (!Tok.hasLeadingSpace()) {
1756 // C99 requires whitespace between the macro definition and the body. Emit
1757 // a diagnostic for something like "#define X+".
1758 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001759 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001760 } else {
1761 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1762 // one in some cases!
1763 }
1764 } else {
1765 // This is a normal token with leading space. Clear the leading space
1766 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001767 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001768 }
1769
Chris Lattner7e374832006-07-29 03:46:57 +00001770 // If this is a definition of a variadic C99 function-like macro, not using
1771 // the GNU named varargs extension, enabled __VA_ARGS__.
1772
1773 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1774 // This gets unpoisoned where it is allowed.
1775 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1776 if (MI->isC99Varargs())
1777 Ident__VA_ARGS__->setIsPoisoned(false);
1778
Chris Lattner22eb9722006-06-18 05:43:12 +00001779 // Read the rest of the macro body.
1780 while (Tok.getKind() != tok::eom) {
1781 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001782
1783 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001784 // parameters in function-like macro expansions.
1785 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001786 // Get the next token of the macro.
1787 LexUnexpandedToken(Tok);
1788 continue;
1789 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001790
Chris Lattner815a1f92006-07-08 20:48:04 +00001791 // Get the next token of the macro.
1792 LexUnexpandedToken(Tok);
1793
1794 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001795 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001796 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001797 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001798 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001799
1800 // Disable __VA_ARGS__ again.
1801 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001802 return;
1803 }
1804
1805 // Things look ok, add the param name token to the macro.
1806 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001807
Chris Lattner22eb9722006-06-18 05:43:12 +00001808 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001809 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001810 }
Chris Lattner7e374832006-07-29 03:46:57 +00001811
1812 // Disable __VA_ARGS__ again.
1813 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001814
Chris Lattnerbff18d52006-07-06 04:49:18 +00001815 // Check that there is no paste (##) operator at the begining or end of the
1816 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001817 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001818 if (NumTokens != 0) {
1819 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001820 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001821 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001822 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001823 }
1824 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001825 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001826 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001827 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001828 }
1829 }
1830
Chris Lattner13044d92006-07-03 05:16:44 +00001831 // If this is the primary source file, remember that this macro hasn't been
1832 // used yet.
1833 if (isInPrimaryFile())
1834 MI->setIsUsed(false);
1835
Chris Lattner22eb9722006-06-18 05:43:12 +00001836 // Finally, if this identifier already had a macro defined for it, verify that
1837 // the macro bodies are identical and free the old definition.
1838 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001839 if (!OtherMI->isUsed())
1840 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1841
Chris Lattner22eb9722006-06-18 05:43:12 +00001842 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001843 // must be the same. C99 6.10.3.2.
1844 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001845 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1846 MacroNameTok.getIdentifierInfo()->getName());
1847 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1848 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001849 delete OtherMI;
1850 }
1851
1852 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001853}
1854
Chris Lattner063400e2006-10-14 19:54:15 +00001855/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1856void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1857 LexerToken MacroNameTok;
1858 ReadMacroName(MacroNameTok, 1);
1859
1860 // Error reading macro name? If so, diagnostic already issued.
1861 if (MacroNameTok.getKind() == tok::eom)
1862 return;
1863
1864 // Check to see if this is the last token on the #undef line.
1865 CheckEndOfDirective("#define_other_target");
1866
1867 // If there is already a macro defined by this name, turn it into a
1868 // target-specific define.
1869 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1870 MI->setIsTargetSpecific(true);
1871 return;
1872 }
1873
1874 // Mark the identifier as being a macro on some other target.
1875 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1876}
1877
Chris Lattner22eb9722006-06-18 05:43:12 +00001878
1879/// HandleUndefDirective - Implements #undef.
1880///
Chris Lattnercb283342006-06-18 06:48:37 +00001881void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001882 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001883
Chris Lattner22eb9722006-06-18 05:43:12 +00001884 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001885 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001886
1887 // Error reading macro name? If so, diagnostic already issued.
1888 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001889 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001890
1891 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001892 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001893
1894 // Okay, we finally have a valid identifier to undef.
1895 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1896
Chris Lattner063400e2006-10-14 19:54:15 +00001897 // #undef untaints an identifier if it were marked by define_other_target.
1898 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1899
Chris Lattner22eb9722006-06-18 05:43:12 +00001900 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001901 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001902
Chris Lattner13044d92006-07-03 05:16:44 +00001903 if (!MI->isUsed())
1904 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001905
1906 // Free macro definition.
1907 delete MI;
1908 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001909}
1910
1911
Chris Lattnerb8761832006-06-24 21:31:03 +00001912//===----------------------------------------------------------------------===//
1913// Preprocessor Conditional Directive Handling.
1914//===----------------------------------------------------------------------===//
1915
Chris Lattner22eb9722006-06-18 05:43:12 +00001916/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001917/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1918/// if any tokens have been returned or pp-directives activated before this
1919/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001920///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001921void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1922 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001923 ++NumIf;
1924 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001925
Chris Lattner22eb9722006-06-18 05:43:12 +00001926 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001927 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001928
1929 // Error reading macro name? If so, diagnostic already issued.
1930 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001931 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001932
1933 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001934 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1935
1936 // If the start of a top-level #ifdef, inform MIOpt.
1937 if (!ReadAnyTokensBeforeDirective &&
1938 CurLexer->getConditionalStackDepth() == 0) {
1939 assert(isIfndef && "#ifdef shouldn't reach here");
1940 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1941 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001942
Chris Lattner063400e2006-10-14 19:54:15 +00001943 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1944 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001945
Chris Lattner81278c62006-10-14 19:03:49 +00001946 // If there is a macro, process it.
1947 if (MI) {
1948 // Mark it used.
1949 MI->setIsUsed(true);
1950
1951 // If this is the first use of a target-specific macro, warn about it.
1952 if (MI->isTargetSpecific()) {
1953 MI->setIsTargetSpecific(false); // Don't warn on second use.
1954 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1955 diag::port_target_macro_use);
1956 }
Chris Lattner063400e2006-10-14 19:54:15 +00001957 } else {
1958 // Use of a target-specific macro for some other target? If so, warn.
1959 if (MII->isOtherTargetMacro()) {
1960 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1961 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1962 diag::port_target_macro_use);
1963 }
Chris Lattner81278c62006-10-14 19:03:49 +00001964 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001965
Chris Lattner22eb9722006-06-18 05:43:12 +00001966 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001967 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001968 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001969 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001970 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001971 } else {
1972 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001973 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001974 /*Foundnonskip*/false,
1975 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001976 }
1977}
1978
1979/// HandleIfDirective - Implements the #if directive.
1980///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001981void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1982 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001983 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001984
Chris Lattner371ac8a2006-07-04 07:11:10 +00001985 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001986 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001987 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001988
1989 // Should we include the stuff contained by this directive?
1990 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001991 // If this condition is equivalent to #ifndef X, and if this is the first
1992 // directive seen, handle it for the multiple-include optimization.
1993 if (!ReadAnyTokensBeforeDirective &&
1994 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1995 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1996
Chris Lattner22eb9722006-06-18 05:43:12 +00001997 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001998 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001999 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002000 } else {
2001 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002002 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002003 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002004 }
2005}
2006
2007/// HandleEndifDirective - Implements the #endif directive.
2008///
Chris Lattnercb283342006-06-18 06:48:37 +00002009void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002010 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002011
Chris Lattner22eb9722006-06-18 05:43:12 +00002012 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002013 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002014
2015 PPConditionalInfo CondInfo;
2016 if (CurLexer->popConditionalLevel(CondInfo)) {
2017 // No conditionals on the stack: this is an #endif without an #if.
2018 return Diag(EndifToken, diag::err_pp_endif_without_if);
2019 }
2020
Chris Lattner371ac8a2006-07-04 07:11:10 +00002021 // If this the end of a top-level #endif, inform MIOpt.
2022 if (CurLexer->getConditionalStackDepth() == 0)
2023 CurLexer->MIOpt.ExitTopLevelConditional();
2024
Chris Lattner538d7f32006-07-20 04:31:52 +00002025 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002026 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002027}
2028
2029
Chris Lattnercb283342006-06-18 06:48:37 +00002030void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002031 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002032
Chris Lattner22eb9722006-06-18 05:43:12 +00002033 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002034 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002035
2036 PPConditionalInfo CI;
2037 if (CurLexer->popConditionalLevel(CI))
2038 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002039
2040 // If this is a top-level #else, inform the MIOpt.
2041 if (CurLexer->getConditionalStackDepth() == 0)
2042 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002043
2044 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002045 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002046
2047 // Finally, skip the rest of the contents of this block and return the first
2048 // token after it.
2049 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2050 /*FoundElse*/true);
2051}
2052
Chris Lattnercb283342006-06-18 06:48:37 +00002053void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002054 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002055
Chris Lattner22eb9722006-06-18 05:43:12 +00002056 // #elif directive in a non-skipping conditional... start skipping.
2057 // We don't care what the condition is, because we will always skip it (since
2058 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002059 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002060
2061 PPConditionalInfo CI;
2062 if (CurLexer->popConditionalLevel(CI))
2063 return Diag(ElifToken, diag::pp_err_elif_without_if);
2064
Chris Lattner371ac8a2006-07-04 07:11:10 +00002065 // If this is a top-level #elif, inform the MIOpt.
2066 if (CurLexer->getConditionalStackDepth() == 0)
2067 CurLexer->MIOpt.FoundTopLevelElse();
2068
Chris Lattner22eb9722006-06-18 05:43:12 +00002069 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002070 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002071
2072 // Finally, skip the rest of the contents of this block and return the first
2073 // token after it.
2074 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2075 /*FoundElse*/CI.FoundElse);
2076}
Chris Lattnerb8761832006-06-24 21:31:03 +00002077