blob: bcb345601bcc562fc032babf54c98a292e8ccc26 [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
889//===----------------------------------------------------------------------===//
890// Lexer Event Handling.
891//===----------------------------------------------------------------------===//
892
Chris Lattnercefc7682006-07-08 08:28:12 +0000893/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
894/// identifier information for the token and install it into the token.
895IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
896 const char *BufPtr) {
897 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
898 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
899
900 // Look up this token, see if it is a macro, or if it is a language keyword.
901 IdentifierInfo *II;
902 if (BufPtr && !Identifier.needsCleaning()) {
903 // No cleaning needed, just use the characters from the lexed buffer.
904 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
905 } else {
906 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
907 const char *TmpBuf = (char*)alloca(Identifier.getLength());
908 unsigned Size = getSpelling(Identifier, TmpBuf);
909 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
910 }
Chris Lattner8c204872006-10-14 05:19:21 +0000911 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000912 return II;
913}
914
915
Chris Lattner677757a2006-06-28 05:26:32 +0000916/// HandleIdentifier - This callback is invoked when the lexer reads an
917/// identifier. This callback looks up the identifier in the map and/or
918/// potentially macro expands it or turns it into a named token (like 'for').
919void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000920 assert(Identifier.getIdentifierInfo() &&
921 "Can't handle identifiers without identifier info!");
922
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000923 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000924
925 // If this identifier was poisoned, and if it was not produced from a macro
926 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000927 if (II.isPoisoned() && CurLexer) {
928 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
929 Diag(Identifier, diag::err_pp_used_poisoned_id);
930 else
931 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
932 }
Chris Lattner677757a2006-06-28 05:26:32 +0000933
Chris Lattner78186052006-07-09 00:45:31 +0000934 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000935 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000936 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
937 if (MI->isEnabled()) {
938 if (!HandleMacroExpandedIdentifier(Identifier, MI))
939 return;
940 } else {
941 // C99 6.10.3.4p2 says that a disabled macro may never again be
942 // expanded, even if it's in a context where it could be expanded in the
943 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000944 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000945 }
946 }
Chris Lattner063400e2006-10-14 19:54:15 +0000947 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
948 // If this identifier is a macro on some other target, emit a diagnostic.
949 // This diagnosic is only emitted when macro expansion is enabled, because
950 // the macro would not have been expanded for the other target either.
951 II.setIsOtherTargetMacro(false); // Don't warn on second use.
952 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
953 diag::port_target_macro_use);
954
955 }
Chris Lattner677757a2006-06-28 05:26:32 +0000956
Chris Lattner5b9f4892006-11-21 17:23:33 +0000957 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
958 // then we act as if it is the actual operator and not the textual
959 // representation of it.
960 if (II.isCPlusPlusOperatorKeyword())
961 Identifier.setIdentifierInfo(0);
962
Chris Lattner677757a2006-06-28 05:26:32 +0000963 // Change the kind of this identifier to the appropriate token kind, e.g.
964 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000965 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000966
967 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000968 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000969}
970
Chris Lattner22eb9722006-06-18 05:43:12 +0000971/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
972/// the current file. This either returns the EOF token or pops a level off
973/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000974bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000975 assert(!CurMacroExpander &&
976 "Ending a file when currently in a macro!");
977
Chris Lattner371ac8a2006-07-04 07:11:10 +0000978 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000979 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000980 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000981 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000982 // Okay, this has a controlling macro, remember in PerFileInfo.
983 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000984 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
985 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000986 }
987 }
988
Chris Lattner22eb9722006-06-18 05:43:12 +0000989 // If this is a #include'd file, pop it off the include stack and continue
990 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000991 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000992 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000993 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +0000994
995 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000996 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000997 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
998
999 // Get the file entry for the current file.
1000 if (const FileEntry *FE =
1001 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001002 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001003
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001004 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1005 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001006 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001007
1008 // Client should lex another token.
1009 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001010 }
1011
Chris Lattner8c204872006-10-14 05:19:21 +00001012 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001013 CurLexer->BufferPtr = CurLexer->BufferEnd;
1014 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001015 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001016
1017 // We're done with the #included file.
1018 delete CurLexer;
1019 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001020
Chris Lattner03f83482006-07-10 06:16:26 +00001021 // This is the end of the top-level file. If the diag::pp_macro_not_used
1022 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1023 // have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001024 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1025 for (IdentifierTable::iterator I = Identifiers.begin(),
1026 E = Identifiers.end(); I != E; ++I) {
1027 const IdentifierInfo &II = I->getValue();
1028 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1029 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1030 }
1031 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001032
1033 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001034}
1035
1036/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001037/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001038bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001039 assert(CurMacroExpander && !CurLexer &&
1040 "Ending a macro when currently in a #include file!");
1041
Chris Lattner22eb9722006-06-18 05:43:12 +00001042 delete CurMacroExpander;
1043
Chris Lattner69772b02006-07-02 20:34:39 +00001044 // Handle this like a #include file being popped off the stack.
1045 CurMacroExpander = 0;
1046 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001047}
1048
1049
1050//===----------------------------------------------------------------------===//
1051// Utility Methods for Preprocessor Directive Handling.
1052//===----------------------------------------------------------------------===//
1053
1054/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1055/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001056void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001057 LexerToken Tmp;
1058 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001059 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001060 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001061}
1062
Chris Lattner652c1692006-11-21 23:47:30 +00001063/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1064static bool isCXXNamedOperator(const std::string &Spelling) {
1065 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1066 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1067 Spelling == "or" || Spelling == "xor";
1068}
1069
Chris Lattner22eb9722006-06-18 05:43:12 +00001070/// 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 Lattner652c1692006-11-21 23:47:30 +00001085 std::string Spelling = getSpelling(MacroNameTok);
1086 if (isCXXNamedOperator(Spelling))
1087 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1088 // except for their spellings.
1089 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1090 else
1091 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001092 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001093 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001094 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001095 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001096 } else if (isDefineUndef && II->getMacroInfo() &&
1097 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001098 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001099 if (isDefineUndef == 1)
1100 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1101 else
1102 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001103 } else {
1104 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001105 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001106 }
1107
Chris Lattner22eb9722006-06-18 05:43:12 +00001108 // Invalid macro name, read and discard the rest of the line. Then set the
1109 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001110 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001111 return DiscardUntilEndOfDirective();
1112}
1113
1114/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1115/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001116void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001117 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001118 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001119 // There should be no tokens after the directive, but we allow them as an
1120 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001121 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1122 Lex(Tmp);
1123
Chris Lattner22eb9722006-06-18 05:43:12 +00001124 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001125 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1126 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001127 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001128}
1129
1130
1131
1132/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1133/// decided that the subsequent tokens are in the #if'd out portion of the
1134/// file. Lex the rest of the file, until we see an #endif. If
1135/// FoundNonSkipPortion is true, then we have already emitted code for part of
1136/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1137/// is true, then #else directives are ok, if not, then we have already seen one
1138/// so a #else directive is a duplicate. When this returns, the caller can lex
1139/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001140void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001141 bool FoundNonSkipPortion,
1142 bool FoundElse) {
1143 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001144 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001145 "Lexing a macro, not a file?");
1146
1147 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1148 FoundNonSkipPortion, FoundElse);
1149
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001150 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1151 // disabling warnings, etc.
1152 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001153 LexerToken Tok;
1154 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001155 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001156
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001157 // If this is the end of the buffer, we have an error.
1158 if (Tok.getKind() == tok::eof) {
1159 // Emit errors for each unterminated conditional on the stack, including
1160 // the current one.
1161 while (!CurLexer->ConditionalStack.empty()) {
1162 Diag(CurLexer->ConditionalStack.back().IfLoc,
1163 diag::err_pp_unterminated_conditional);
1164 CurLexer->ConditionalStack.pop_back();
1165 }
1166
1167 // Just return and let the caller lex after this #include.
1168 break;
1169 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001170
1171 // If this token is not a preprocessor directive, just skip it.
1172 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1173 continue;
1174
1175 // We just parsed a # character at the start of a line, so we're in
1176 // directive mode. Tell the lexer this so any newlines we see will be
1177 // converted into an EOM token (this terminates the macro).
1178 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001179 CurLexer->KeepCommentMode = false;
1180
Chris Lattner22eb9722006-06-18 05:43:12 +00001181
1182 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001183 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001184
1185 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1186 // something bogus), skip it.
1187 if (Tok.getKind() != tok::identifier) {
1188 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001189 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001190 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001191 continue;
1192 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001193
Chris Lattner22eb9722006-06-18 05:43:12 +00001194 // If the first letter isn't i or e, it isn't intesting to us. We know that
1195 // this is safe in the face of spelling differences, because there is no way
1196 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001197 // allows us to avoid looking up the identifier info for #define/#undef and
1198 // other common directives.
1199 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1200 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001201 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1202 FirstChar != 'i' && FirstChar != 'e') {
1203 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001204 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001205 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001206 continue;
1207 }
1208
Chris Lattnere60165f2006-06-22 06:36:29 +00001209 // Get the identifier name without trigraphs or embedded newlines. Note
1210 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1211 // when skipping.
1212 // TODO: could do this with zero copies in the no-clean case by using
1213 // strncmp below.
1214 char Directive[20];
1215 unsigned IdLen;
1216 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1217 IdLen = Tok.getLength();
1218 memcpy(Directive, RawCharData, IdLen);
1219 Directive[IdLen] = 0;
1220 } else {
1221 std::string DirectiveStr = getSpelling(Tok);
1222 IdLen = DirectiveStr.size();
1223 if (IdLen >= 20) {
1224 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001225 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001226 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001227 continue;
1228 }
1229 memcpy(Directive, &DirectiveStr[0], IdLen);
1230 Directive[IdLen] = 0;
1231 }
1232
Chris Lattner22eb9722006-06-18 05:43:12 +00001233 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001234 if ((IdLen == 2) || // "if"
1235 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1236 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001237 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1238 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001239 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001240 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001241 /*foundnonskip*/false,
1242 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001243 }
1244 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001245 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001246 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001247 PPConditionalInfo CondInfo;
1248 CondInfo.WasSkipping = true; // Silence bogus warning.
1249 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001250 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001251 assert(!InCond && "Can't be skipping if not in a conditional!");
1252
1253 // If we popped the outermost skipping block, we're done skipping!
1254 if (!CondInfo.WasSkipping)
1255 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001256 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001257 // #else directive in a skipping conditional. If not in some other
1258 // skipping conditional, and if #else hasn't already been seen, enter it
1259 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001260 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001261 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1262
1263 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001264 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001265
1266 // Note that we've seen a #else in this conditional.
1267 CondInfo.FoundElse = true;
1268
1269 // If the conditional is at the top level, and the #if block wasn't
1270 // entered, enter the #else block now.
1271 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1272 CondInfo.FoundNonSkip = true;
1273 break;
1274 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001275 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001276 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1277
1278 bool ShouldEnter;
1279 // If this is in a skipping block or if we're already handled this #if
1280 // block, don't bother parsing the condition.
1281 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001282 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001283 ShouldEnter = false;
1284 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001285 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001286 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001287 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1288 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001289 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001290 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001291 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001292 }
1293
1294 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001295 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001296
1297 // If this condition is true, enter it!
1298 if (ShouldEnter) {
1299 CondInfo.FoundNonSkip = true;
1300 break;
1301 }
1302 }
1303 }
1304
1305 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001306 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001307 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001308 }
1309
1310 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1311 // of the file, just stop skipping and return to lexing whatever came after
1312 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001313 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001314}
1315
1316//===----------------------------------------------------------------------===//
1317// Preprocessor Directive Handling.
1318//===----------------------------------------------------------------------===//
1319
1320/// HandleDirective - This callback is invoked when the lexer sees a # token
1321/// at the start of a line. This consumes the directive, modifies the
1322/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1323/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001324void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001325 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001326
1327 // We just parsed a # character at the start of a line, so we're in directive
1328 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001329 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001330 CurLexer->ParsingPreprocessorDirective = true;
1331
1332 ++NumDirectives;
1333
Chris Lattner371ac8a2006-07-04 07:11:10 +00001334 // We are about to read a token. For the multiple-include optimization FA to
1335 // work, we have to remember if we had read any tokens *before* this
1336 // pp-directive.
1337 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1338
Chris Lattner78186052006-07-09 00:45:31 +00001339 // Read the next token, the directive flavor. This isn't expanded due to
1340 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001341 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001342
Chris Lattner78186052006-07-09 00:45:31 +00001343 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1344 // #define A(x) #x
1345 // A(abc
1346 // #warning blah
1347 // def)
1348 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001349 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001350 Diag(Result, diag::ext_embedded_directive);
1351
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001352TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001353 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001354 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001355 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001356 case tok::comment:
1357 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1358 LexUnexpandedToken(Result);
1359 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001360
Chris Lattner22eb9722006-06-18 05:43:12 +00001361 case tok::numeric_constant:
1362 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001363 DiscardUntilEndOfDirective();
1364 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001365 default:
1366 IdentifierInfo *II = Result.getIdentifierInfo();
1367 if (II == 0) break; // Not an identifier.
1368
1369 // Ask what the preprocessor keyword ID is.
1370 switch (II->getPPKeywordID()) {
1371 default: break;
1372 // C99 6.10.1 - Conditional Inclusion.
1373 case tok::pp_if:
1374 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1375 case tok::pp_ifdef:
1376 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1377 case tok::pp_ifndef:
1378 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1379 case tok::pp_elif:
1380 return HandleElifDirective(Result);
1381 case tok::pp_else:
1382 return HandleElseDirective(Result);
1383 case tok::pp_endif:
1384 return HandleEndifDirective(Result);
1385
1386 // C99 6.10.2 - Source File Inclusion.
1387 case tok::pp_include:
1388 return HandleIncludeDirective(Result); // Handle #include.
1389
1390 // C99 6.10.3 - Macro Replacement.
1391 case tok::pp_define:
1392 return HandleDefineDirective(Result, false);
1393 case tok::pp_undef:
1394 return HandleUndefDirective(Result);
1395
1396 // C99 6.10.4 - Line Control.
1397 case tok::pp_line:
1398 // FIXME: implement #line
1399 DiscardUntilEndOfDirective();
1400 return;
1401
1402 // C99 6.10.5 - Error Directive.
1403 case tok::pp_error:
1404 return HandleUserDiagnosticDirective(Result, false);
1405
1406 // C99 6.10.6 - Pragma Directive.
1407 case tok::pp_pragma:
1408 return HandlePragmaDirective();
1409
1410 // GNU Extensions.
1411 case tok::pp_import:
1412 return HandleImportDirective(Result);
1413 case tok::pp_include_next:
1414 return HandleIncludeNextDirective(Result);
1415
1416 case tok::pp_warning:
1417 Diag(Result, diag::ext_pp_warning_directive);
1418 return HandleUserDiagnosticDirective(Result, true);
1419 case tok::pp_ident:
1420 return HandleIdentSCCSDirective(Result);
1421 case tok::pp_sccs:
1422 return HandleIdentSCCSDirective(Result);
1423 case tok::pp_assert:
1424 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001426 case tok::pp_unassert:
1427 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001428 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001429
1430 // clang extensions.
1431 case tok::pp_define_target:
1432 return HandleDefineDirective(Result, true);
1433 case tok::pp_define_other_target:
1434 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001435 }
1436 break;
1437 }
1438
1439 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001440 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001441
1442 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001443 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001444
1445 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001446}
1447
Chris Lattner01d66cc2006-07-03 22:16:27 +00001448void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001449 bool isWarning) {
1450 // Read the rest of the line raw. We do this because we don't want macros
1451 // to be expanded and we don't require that the tokens be valid preprocessing
1452 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1453 // collapse multiple consequtive white space between tokens, but this isn't
1454 // specified by the standard.
1455 std::string Message = CurLexer->ReadToEndOfLine();
1456
1457 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001458 return Diag(Tok, DiagID, Message);
1459}
1460
1461/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1462///
1463void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001464 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001465 Diag(Tok, diag::ext_pp_ident_directive);
1466
Chris Lattner371ac8a2006-07-04 07:11:10 +00001467 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001468 LexerToken StrTok;
1469 Lex(StrTok);
1470
1471 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001472 if (StrTok.getKind() != tok::string_literal &&
1473 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001474 return Diag(StrTok, diag::err_pp_malformed_ident);
1475
1476 // Verify that there is nothing after the string, other than EOM.
1477 CheckEndOfDirective("#ident");
1478
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001479 if (Callbacks)
1480 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001481}
1482
Chris Lattnerb8761832006-06-24 21:31:03 +00001483//===----------------------------------------------------------------------===//
1484// Preprocessor Include Directive Handling.
1485//===----------------------------------------------------------------------===//
1486
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001487/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1488/// checked and spelled filename, e.g. as an operand of #include. This returns
1489/// true if the input filename was in <>'s or false if it were in ""'s. The
1490/// caller is expected to provide a buffer that is large enough to hold the
1491/// spelling of the filename, but is also expected to handle the case when
1492/// this method decides to use a different buffer.
1493bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1494 const char *&BufStart,
1495 const char *&BufEnd) {
1496 // Get the text form of the filename.
1497 unsigned Len = getSpelling(FilenameTok, BufStart);
1498 BufEnd = BufStart+Len;
1499 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1500
1501 // Make sure the filename is <x> or "x".
1502 bool isAngled;
1503 if (BufStart[0] == '<') {
1504 if (BufEnd[-1] != '>') {
1505 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1506 BufStart = 0;
1507 return true;
1508 }
1509 isAngled = true;
1510 } else if (BufStart[0] == '"') {
1511 if (BufEnd[-1] != '"') {
1512 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1513 BufStart = 0;
1514 return true;
1515 }
1516 isAngled = false;
1517 } else {
1518 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1519 BufStart = 0;
1520 return true;
1521 }
1522
1523 // Diagnose #include "" as invalid.
1524 if (BufEnd-BufStart <= 2) {
1525 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1526 BufStart = 0;
1527 return "";
1528 }
1529
1530 // Skip the brackets.
1531 ++BufStart;
1532 --BufEnd;
1533 return isAngled;
1534}
1535
Chris Lattner22eb9722006-06-18 05:43:12 +00001536/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1537/// file to be included from the lexer, then include it! This is a common
1538/// routine with functionality shared between #include, #include_next and
1539/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001540void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001541 const DirectoryLookup *LookupFrom,
1542 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001543
Chris Lattner22eb9722006-06-18 05:43:12 +00001544 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001545 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001546
1547 // If the token kind is EOM, the error has already been diagnosed.
1548 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001549 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001550
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001551 // Reserve a buffer to get the spelling.
1552 SmallVector<char, 128> FilenameBuffer;
1553 FilenameBuffer.resize(FilenameTok.getLength());
1554
1555 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1556 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1557 FilenameStart, FilenameEnd);
1558 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1559 // error.
1560 if (FilenameStart == 0)
1561 return;
1562
Chris Lattner269c2322006-06-25 06:23:00 +00001563 // Verify that there is nothing after the filename, other than EOM. Use the
1564 // preprocessor to lex this in case lexing the filename entered a macro.
1565 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001566
1567 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001568 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001569 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1570
Chris Lattner22eb9722006-06-18 05:43:12 +00001571 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001572 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001573 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001574 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001575 if (File == 0)
1576 return Diag(FilenameTok, diag::err_pp_file_not_found);
1577
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001578 // Ask HeaderInfo if we should enter this #include file.
1579 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1580 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001581 return;
1582 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001583
1584 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001585 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001586 if (FileID == 0)
1587 return Diag(FilenameTok, diag::err_pp_file_not_found);
1588
1589 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001590 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001591}
1592
1593/// HandleIncludeNextDirective - Implements #include_next.
1594///
Chris Lattnercb283342006-06-18 06:48:37 +00001595void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1596 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001597
1598 // #include_next is like #include, except that we start searching after
1599 // the current found directory. If we can't do this, issue a
1600 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001601 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001602 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001603 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001604 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001605 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001606 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001607 } else {
1608 // Start looking up in the next directory.
1609 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001610 }
1611
1612 return HandleIncludeDirective(IncludeNextTok, Lookup);
1613}
1614
1615/// HandleImportDirective - Implements #import.
1616///
Chris Lattnercb283342006-06-18 06:48:37 +00001617void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1618 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001619
1620 return HandleIncludeDirective(ImportTok, 0, true);
1621}
1622
Chris Lattnerb8761832006-06-24 21:31:03 +00001623//===----------------------------------------------------------------------===//
1624// Preprocessor Macro Directive Handling.
1625//===----------------------------------------------------------------------===//
1626
Chris Lattnercefc7682006-07-08 08:28:12 +00001627/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1628/// definition has just been read. Lex the rest of the arguments and the
1629/// closing ), updating MI with what we learn. Return true if an error occurs
1630/// parsing the arg list.
1631bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1632 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001633 while (1) {
1634 LexUnexpandedToken(Tok);
1635 switch (Tok.getKind()) {
1636 case tok::r_paren:
1637 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001638 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001639 // Otherwise we have #define FOO(A,)
1640 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1641 return true;
1642 case tok::ellipsis: // #define X(... -> C99 varargs
1643 // Warn if use of C99 feature in non-C99 mode.
1644 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1645
1646 // Lex the token after the identifier.
1647 LexUnexpandedToken(Tok);
1648 if (Tok.getKind() != tok::r_paren) {
1649 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1650 return true;
1651 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001652 // Add the __VA_ARGS__ identifier as an argument.
1653 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001654 MI->setIsC99Varargs();
1655 return false;
1656 case tok::eom: // #define X(
1657 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1658 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001659 default:
1660 // Handle keywords and identifiers here to accept things like
1661 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001662 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001663 if (II == 0) {
1664 // #define X(1
1665 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1666 return true;
1667 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001668
1669 // If this is already used as an argument, it is used multiple times (e.g.
1670 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001671 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001672 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1673 return true;
1674 }
1675
1676 // Add the argument to the macro info.
1677 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001678
1679 // Lex the token after the identifier.
1680 LexUnexpandedToken(Tok);
1681
1682 switch (Tok.getKind()) {
1683 default: // #define X(A B
1684 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1685 return true;
1686 case tok::r_paren: // #define X(A)
1687 return false;
1688 case tok::comma: // #define X(A,
1689 break;
1690 case tok::ellipsis: // #define X(A... -> GCC extension
1691 // Diagnose extension.
1692 Diag(Tok, diag::ext_named_variadic_macro);
1693
1694 // Lex the token after the identifier.
1695 LexUnexpandedToken(Tok);
1696 if (Tok.getKind() != tok::r_paren) {
1697 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1698 return true;
1699 }
1700
1701 MI->setIsGNUVarargs();
1702 return false;
1703 }
1704 }
1705 }
1706}
1707
Chris Lattner22eb9722006-06-18 05:43:12 +00001708/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001709/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1710/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001711///
Chris Lattner81278c62006-10-14 19:03:49 +00001712void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1713 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001714 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001715
Chris Lattner22eb9722006-06-18 05:43:12 +00001716 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001717 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001718
1719 // Error reading macro name? If so, diagnostic already issued.
1720 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001721 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001722
Chris Lattner457fc152006-07-29 06:30:25 +00001723 // If we are supposed to keep comments in #defines, reenable comment saving
1724 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001725 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001726
Chris Lattner063400e2006-10-14 19:54:15 +00001727 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001728 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001729 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001730
Chris Lattner063400e2006-10-14 19:54:15 +00001731 // If the identifier is an 'other target' macro, clear this bit.
1732 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1733
1734
Chris Lattner22eb9722006-06-18 05:43:12 +00001735 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001736 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001737
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001738 // If this is a function-like macro definition, parse the argument list,
1739 // marking each of the identifiers as being used as macro arguments. Also,
1740 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001741 if (Tok.getKind() == tok::eom) {
1742 // If there is no body to this macro, we have no special handling here.
1743 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001744 // This is a function-like macro definition. Read the argument list.
1745 MI->setIsFunctionLike();
1746 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001747 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001748 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001749 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001750 if (CurLexer->ParsingPreprocessorDirective)
1751 DiscardUntilEndOfDirective();
1752 return;
1753 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001754
Chris Lattner815a1f92006-07-08 20:48:04 +00001755 // Read the first token after the arg list for down below.
1756 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001757 } else if (!Tok.hasLeadingSpace()) {
1758 // C99 requires whitespace between the macro definition and the body. Emit
1759 // a diagnostic for something like "#define X+".
1760 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001761 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001762 } else {
1763 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1764 // one in some cases!
1765 }
1766 } else {
1767 // This is a normal token with leading space. Clear the leading space
1768 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001769 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001770 }
1771
Chris Lattner7e374832006-07-29 03:46:57 +00001772 // If this is a definition of a variadic C99 function-like macro, not using
1773 // the GNU named varargs extension, enabled __VA_ARGS__.
1774
1775 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1776 // This gets unpoisoned where it is allowed.
1777 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1778 if (MI->isC99Varargs())
1779 Ident__VA_ARGS__->setIsPoisoned(false);
1780
Chris Lattner22eb9722006-06-18 05:43:12 +00001781 // Read the rest of the macro body.
1782 while (Tok.getKind() != tok::eom) {
1783 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001784
1785 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001786 // parameters in function-like macro expansions.
1787 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001788 // Get the next token of the macro.
1789 LexUnexpandedToken(Tok);
1790 continue;
1791 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001792
Chris Lattner815a1f92006-07-08 20:48:04 +00001793 // Get the next token of the macro.
1794 LexUnexpandedToken(Tok);
1795
1796 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001797 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001798 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001799 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001800 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001801
1802 // Disable __VA_ARGS__ again.
1803 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001804 return;
1805 }
1806
1807 // Things look ok, add the param name token to the macro.
1808 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001809
Chris Lattner22eb9722006-06-18 05:43:12 +00001810 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001811 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001812 }
Chris Lattner7e374832006-07-29 03:46:57 +00001813
1814 // Disable __VA_ARGS__ again.
1815 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001816
Chris Lattnerbff18d52006-07-06 04:49:18 +00001817 // Check that there is no paste (##) operator at the begining or end of the
1818 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001819 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001820 if (NumTokens != 0) {
1821 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001822 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001823 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001824 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001825 }
1826 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001827 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001828 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001829 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001830 }
1831 }
1832
Chris Lattner13044d92006-07-03 05:16:44 +00001833 // If this is the primary source file, remember that this macro hasn't been
1834 // used yet.
1835 if (isInPrimaryFile())
1836 MI->setIsUsed(false);
1837
Chris Lattner22eb9722006-06-18 05:43:12 +00001838 // Finally, if this identifier already had a macro defined for it, verify that
1839 // the macro bodies are identical and free the old definition.
1840 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001841 if (!OtherMI->isUsed())
1842 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1843
Chris Lattner22eb9722006-06-18 05:43:12 +00001844 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001845 // must be the same. C99 6.10.3.2.
1846 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001847 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1848 MacroNameTok.getIdentifierInfo()->getName());
1849 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1850 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001851 delete OtherMI;
1852 }
1853
1854 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001855}
1856
Chris Lattner063400e2006-10-14 19:54:15 +00001857/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1858void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1859 LexerToken MacroNameTok;
1860 ReadMacroName(MacroNameTok, 1);
1861
1862 // Error reading macro name? If so, diagnostic already issued.
1863 if (MacroNameTok.getKind() == tok::eom)
1864 return;
1865
1866 // Check to see if this is the last token on the #undef line.
1867 CheckEndOfDirective("#define_other_target");
1868
1869 // If there is already a macro defined by this name, turn it into a
1870 // target-specific define.
1871 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1872 MI->setIsTargetSpecific(true);
1873 return;
1874 }
1875
1876 // Mark the identifier as being a macro on some other target.
1877 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1878}
1879
Chris Lattner22eb9722006-06-18 05:43:12 +00001880
1881/// HandleUndefDirective - Implements #undef.
1882///
Chris Lattnercb283342006-06-18 06:48:37 +00001883void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001884 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001885
Chris Lattner22eb9722006-06-18 05:43:12 +00001886 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001887 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001888
1889 // Error reading macro name? If so, diagnostic already issued.
1890 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001891 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001892
1893 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001894 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001895
1896 // Okay, we finally have a valid identifier to undef.
1897 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1898
Chris Lattner063400e2006-10-14 19:54:15 +00001899 // #undef untaints an identifier if it were marked by define_other_target.
1900 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1901
Chris Lattner22eb9722006-06-18 05:43:12 +00001902 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001903 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001904
Chris Lattner13044d92006-07-03 05:16:44 +00001905 if (!MI->isUsed())
1906 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001907
1908 // Free macro definition.
1909 delete MI;
1910 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001911}
1912
1913
Chris Lattnerb8761832006-06-24 21:31:03 +00001914//===----------------------------------------------------------------------===//
1915// Preprocessor Conditional Directive Handling.
1916//===----------------------------------------------------------------------===//
1917
Chris Lattner22eb9722006-06-18 05:43:12 +00001918/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001919/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1920/// if any tokens have been returned or pp-directives activated before this
1921/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001922///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001923void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1924 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001925 ++NumIf;
1926 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001927
Chris Lattner22eb9722006-06-18 05:43:12 +00001928 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001929 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001930
1931 // Error reading macro name? If so, diagnostic already issued.
1932 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001933 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001934
1935 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001936 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1937
1938 // If the start of a top-level #ifdef, inform MIOpt.
1939 if (!ReadAnyTokensBeforeDirective &&
1940 CurLexer->getConditionalStackDepth() == 0) {
1941 assert(isIfndef && "#ifdef shouldn't reach here");
1942 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1943 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001944
Chris Lattner063400e2006-10-14 19:54:15 +00001945 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1946 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001947
Chris Lattner81278c62006-10-14 19:03:49 +00001948 // If there is a macro, process it.
1949 if (MI) {
1950 // Mark it used.
1951 MI->setIsUsed(true);
1952
1953 // If this is the first use of a target-specific macro, warn about it.
1954 if (MI->isTargetSpecific()) {
1955 MI->setIsTargetSpecific(false); // Don't warn on second use.
1956 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1957 diag::port_target_macro_use);
1958 }
Chris Lattner063400e2006-10-14 19:54:15 +00001959 } else {
1960 // Use of a target-specific macro for some other target? If so, warn.
1961 if (MII->isOtherTargetMacro()) {
1962 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1963 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1964 diag::port_target_macro_use);
1965 }
Chris Lattner81278c62006-10-14 19:03:49 +00001966 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001967
Chris Lattner22eb9722006-06-18 05:43:12 +00001968 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001969 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001970 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001971 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001972 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001973 } else {
1974 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001975 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001976 /*Foundnonskip*/false,
1977 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001978 }
1979}
1980
1981/// HandleIfDirective - Implements the #if directive.
1982///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001983void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1984 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001985 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001986
Chris Lattner371ac8a2006-07-04 07:11:10 +00001987 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001988 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001989 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001990
1991 // Should we include the stuff contained by this directive?
1992 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001993 // If this condition is equivalent to #ifndef X, and if this is the first
1994 // directive seen, handle it for the multiple-include optimization.
1995 if (!ReadAnyTokensBeforeDirective &&
1996 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1997 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1998
Chris Lattner22eb9722006-06-18 05:43:12 +00001999 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002000 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002001 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002002 } else {
2003 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002004 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002005 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002006 }
2007}
2008
2009/// HandleEndifDirective - Implements the #endif directive.
2010///
Chris Lattnercb283342006-06-18 06:48:37 +00002011void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002012 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002013
Chris Lattner22eb9722006-06-18 05:43:12 +00002014 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002015 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002016
2017 PPConditionalInfo CondInfo;
2018 if (CurLexer->popConditionalLevel(CondInfo)) {
2019 // No conditionals on the stack: this is an #endif without an #if.
2020 return Diag(EndifToken, diag::err_pp_endif_without_if);
2021 }
2022
Chris Lattner371ac8a2006-07-04 07:11:10 +00002023 // If this the end of a top-level #endif, inform MIOpt.
2024 if (CurLexer->getConditionalStackDepth() == 0)
2025 CurLexer->MIOpt.ExitTopLevelConditional();
2026
Chris Lattner538d7f32006-07-20 04:31:52 +00002027 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002028 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002029}
2030
2031
Chris Lattnercb283342006-06-18 06:48:37 +00002032void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002033 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002034
Chris Lattner22eb9722006-06-18 05:43:12 +00002035 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002036 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002037
2038 PPConditionalInfo CI;
2039 if (CurLexer->popConditionalLevel(CI))
2040 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002041
2042 // If this is a top-level #else, inform the MIOpt.
2043 if (CurLexer->getConditionalStackDepth() == 0)
2044 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002045
2046 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002047 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002048
2049 // Finally, skip the rest of the contents of this block and return the first
2050 // token after it.
2051 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2052 /*FoundElse*/true);
2053}
2054
Chris Lattnercb283342006-06-18 06:48:37 +00002055void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002056 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002057
Chris Lattner22eb9722006-06-18 05:43:12 +00002058 // #elif directive in a non-skipping conditional... start skipping.
2059 // We don't care what the condition is, because we will always skip it (since
2060 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002061 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002062
2063 PPConditionalInfo CI;
2064 if (CurLexer->popConditionalLevel(CI))
2065 return Diag(ElifToken, diag::pp_err_elif_without_if);
2066
Chris Lattner371ac8a2006-07-04 07:11:10 +00002067 // If this is a top-level #elif, inform the MIOpt.
2068 if (CurLexer->getConditionalStackDepth() == 0)
2069 CurLexer->MIOpt.FoundTopLevelElse();
2070
Chris Lattner22eb9722006-06-18 05:43:12 +00002071 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002072 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002073
2074 // Finally, skip the rest of the contents of this block and return the first
2075 // token after it.
2076 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2077 /*FoundElse*/CI.FoundElse);
2078}
Chris Lattnerb8761832006-06-24 21:31:03 +00002079