blob: e2648c97f50d515b218d253e4893bbc361274c66 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner22eb9722006-06-18 05:43:12 +000016// -d[MDNI] - Dump various things.
17// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000029#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000030#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000031#include "clang/Lex/PPCallbacks.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000032#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000033#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000034#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000037#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000038#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000039#include <iostream>
40using namespace llvm;
41using namespace clang;
42
43//===----------------------------------------------------------------------===//
44
Chris Lattner02dffbd2006-10-14 07:50:21 +000045Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000046 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000047 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000048 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
49 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000050 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000051 ScratchBuf = new ScratchBuffer(SourceMgr);
52
Chris Lattner22eb9722006-06-18 05:43:12 +000053 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000054 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000055 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000056 NumEnteredSourceFiles = 0;
57 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000058 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000059 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000061
62 // Default to discarding comments.
63 KeepComments = false;
64 KeepMacroComments = false;
65
Chris Lattner22eb9722006-06-18 05:43:12 +000066 // Macro expansion is enabled.
67 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000068 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000069
Chris Lattner8ff71992006-07-06 05:17:39 +000070 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
71 // This gets unpoisoned where it is allowed.
72 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
73
Chris Lattnerb8761832006-06-24 21:31:03 +000074 // Initialize the pragma handlers.
75 PragmaHandlers = new PragmaNamespace(0);
76 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000077
78 // Initialize builtin macros like __LINE__ and friends.
79 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000080}
81
82Preprocessor::~Preprocessor() {
83 // Free any active lexers.
84 delete CurLexer;
85
Chris Lattner69772b02006-07-02 20:34:39 +000086 while (!IncludeMacroStack.empty()) {
87 delete IncludeMacroStack.back().TheLexer;
88 delete IncludeMacroStack.back().TheMacroExpander;
89 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000090 }
Chris Lattnerb8761832006-06-24 21:31:03 +000091
92 // Release pragma information.
93 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000094
95 // Delete the scratch buffer info.
96 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000097}
98
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000099PPCallbacks::~PPCallbacks() {
100}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000101
Chris Lattner22eb9722006-06-18 05:43:12 +0000102/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
103/// the specified LexerToken's location, translating the token's start
104/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000105void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000106 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000107 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000108}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000109
110void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
111 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
112 << getSpelling(Tok) << "'";
113
114 if (!DumpFlags) return;
115 std::cerr << "\t";
116 if (Tok.isAtStartOfLine())
117 std::cerr << " [StartOfLine]";
118 if (Tok.hasLeadingSpace())
119 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000120 if (Tok.isExpandDisabled())
121 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000122 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000123 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000124 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
125 << "']";
126 }
127}
128
129void Preprocessor::DumpMacro(const MacroInfo &MI) const {
130 std::cerr << "MACRO: ";
131 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
132 DumpToken(MI.getReplacementToken(i));
133 std::cerr << " ";
134 }
135 std::cerr << "\n";
136}
137
Chris Lattner22eb9722006-06-18 05:43:12 +0000138void Preprocessor::PrintStats() {
139 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000140 std::cerr << NumDirectives << " directives found:\n";
141 std::cerr << " " << NumDefined << " #define.\n";
142 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000143 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000144 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
145 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
146 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
147 std::cerr << " " << NumElse << " #else/#elif.\n";
148 std::cerr << " " << NumEndif << " #endif.\n";
149 std::cerr << " " << NumPragma << " #pragma.\n";
150 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
151
Chris Lattner78186052006-07-09 00:45:31 +0000152 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
153 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000154 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000155 std::cerr << (NumFastTokenPaste+NumTokenPaste)
156 << " token paste (##) operations performed, "
157 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000158}
159
160//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000161// Token Spelling
162//===----------------------------------------------------------------------===//
163
164
165/// getSpelling() - Return the 'spelling' of this token. The spelling of a
166/// token are the characters used to represent the token in the source file
167/// after trigraph expansion and escaped-newline folding. In particular, this
168/// wants to get the true, uncanonicalized, spelling of things like digraphs
169/// UCNs, etc.
170std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
171 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
172
173 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000174 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000175 if (!Tok.needsCleaning())
176 return std::string(TokStart, TokStart+Tok.getLength());
177
Chris Lattnerd01e2912006-06-18 16:22:51 +0000178 std::string Result;
179 Result.reserve(Tok.getLength());
180
Chris Lattneref9eae12006-07-04 22:33:12 +0000181 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000182 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
183 Ptr != End; ) {
184 unsigned CharSize;
185 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
186 Ptr += CharSize;
187 }
188 assert(Result.size() != unsigned(Tok.getLength()) &&
189 "NeedsCleaning flag set on something that didn't need cleaning!");
190 return Result;
191}
192
193/// getSpelling - This method is used to get the spelling of a token into a
194/// preallocated buffer, instead of as an std::string. The caller is required
195/// to allocate enough space for the token, which is guaranteed to be at least
196/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000197///
198/// Note that this method may do two possible things: it may either fill in
199/// the buffer specified with characters, or it may *change the input pointer*
200/// to point to a constant buffer with the data already in it (avoiding a
201/// copy). The caller is not allowed to modify the returned buffer pointer
202/// if an internal buffer is returned.
203unsigned Preprocessor::getSpelling(const LexerToken &Tok,
204 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000205 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
206
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000207 // If this token is an identifier, just return the string from the identifier
208 // table, which is very quick.
209 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
210 Buffer = II->getName();
211 return Tok.getLength();
212 }
213
214 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000215 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000216
217 // If this token contains nothing interesting, return it directly.
218 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000219 Buffer = TokStart;
220 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 }
222 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000223 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
225 Ptr != End; ) {
226 unsigned CharSize;
227 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
228 Ptr += CharSize;
229 }
230 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
231 "NeedsCleaning flag set on something that didn't need cleaning!");
232
233 return OutBuf-Buffer;
234}
235
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000236
237/// CreateString - Plop the specified string into a scratch buffer and return a
238/// location for it. If specified, the source location provides a source
239/// location for the token.
240SourceLocation Preprocessor::
241CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
242 if (SLoc.isValid())
243 return ScratchBuf->getToken(Buf, Len, SLoc);
244 return ScratchBuf->getToken(Buf, Len);
245}
246
247
Chris Lattnerd01e2912006-06-18 16:22:51 +0000248//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000249// Source File Location Methods.
250//===----------------------------------------------------------------------===//
251
Chris Lattner22eb9722006-06-18 05:43:12 +0000252/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
253/// return null on failure. isAngled indicates whether the file reference is
254/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000255const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
256 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000257 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000258 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000259 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000260 // If the header lookup mechanism may be relative to the current file, pass in
261 // info about where the current file is.
262 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000263 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000264 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000265 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000266 }
267
Chris Lattner63dd32b2006-10-20 04:42:40 +0000268 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000269 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000270 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000271 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
272 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000273 if (FE) return FE;
274
275 // Otherwise, see if this is a subframework header. If so, this is relative
276 // to one of the headers on the #include stack. Walk the list of the current
277 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000278 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000279 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000280 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
281 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000282 return FE;
283 }
284
285 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
286 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000287 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000288 CurFileEnt =
289 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000290 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
291 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000292 return FE;
293 }
294 }
295
296 // Otherwise, we really couldn't find the file.
297 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000298}
299
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000300/// isInPrimaryFile - Return true if we're in the top-level file, not in a
301/// #include.
302bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000303 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000304 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000305
Chris Lattner13044d92006-07-03 05:16:44 +0000306 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000307 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000308 if (IncludeMacroStack[i].TheLexer &&
309 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
310 return IncludeMacroStack[i].TheLexer->isMainFile();
311 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000312}
313
314/// getCurrentLexer - Return the current file lexer being lexed from. Note
315/// that this ignores any potentially active macro expansions and _Pragma
316/// expansions going on at the time.
317Lexer *Preprocessor::getCurrentFileLexer() const {
318 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
319
320 // Look for a stacked lexer.
321 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000322 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000323 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
324 return L;
325 }
326 return 0;
327}
328
329
Chris Lattner22eb9722006-06-18 05:43:12 +0000330/// EnterSourceFile - Add a source file to the top of the include stack and
331/// start lexing tokens from it instead of the current buffer. Return true
332/// on failure.
333void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000334 const DirectoryLookup *CurDir,
335 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000336 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000337 ++NumEnteredSourceFiles;
338
Chris Lattner69772b02006-07-02 20:34:39 +0000339 if (MaxIncludeStackDepth < IncludeMacroStack.size())
340 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000341
Chris Lattner22eb9722006-06-18 05:43:12 +0000342 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000343 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000344 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000345 EnterSourceFileWithLexer(TheLexer, CurDir);
346}
Chris Lattner22eb9722006-06-18 05:43:12 +0000347
Chris Lattner69772b02006-07-02 20:34:39 +0000348/// EnterSourceFile - Add a source file to the top of the include stack and
349/// start lexing tokens from it instead of the current buffer.
350void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
351 const DirectoryLookup *CurDir) {
352
353 // Add the current lexer to the include stack.
354 if (CurLexer || CurMacroExpander)
355 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
356 CurMacroExpander));
357
358 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000359 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000360 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000361
362 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000363 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000364 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
365
366 // Get the file entry for the current file.
367 if (const FileEntry *FE =
368 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000369 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000370
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000371 Callbacks->FileChanged(SourceLocation(CurLexer->getCurFileID(), 0),
372 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000373 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000374}
375
Chris Lattner69772b02006-07-02 20:34:39 +0000376
377
Chris Lattner22eb9722006-06-18 05:43:12 +0000378/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000379/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000380void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000381 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
382 CurMacroExpander));
383 CurLexer = 0;
384 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000385
Chris Lattneree8760b2006-07-15 07:42:55 +0000386 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000387}
388
Chris Lattner7667d0d2006-07-16 18:16:58 +0000389/// EnterTokenStream - Add a "macro" context to the top of the include stack,
390/// which will cause the lexer to start returning the specified tokens. Note
391/// that these tokens will be re-macro-expanded when/if expansion is enabled.
392/// This method assumes that the specified stream of tokens has a permanent
393/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000394void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000395 // Save our current state.
396 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
397 CurMacroExpander));
398 CurLexer = 0;
399 CurDirLookup = 0;
400
401 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000402 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000403}
404
405/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
406/// lexer stack. This should only be used in situations where the current
407/// state of the top-of-stack lexer is known.
408void Preprocessor::RemoveTopOfLexerStack() {
409 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
410 delete CurLexer;
411 delete CurMacroExpander;
412 CurLexer = IncludeMacroStack.back().TheLexer;
413 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
414 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
415 IncludeMacroStack.pop_back();
416}
417
Chris Lattner22eb9722006-06-18 05:43:12 +0000418//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000419// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000420//===----------------------------------------------------------------------===//
421
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000422/// RegisterBuiltinMacro - Register the specified identifier in the identifier
423/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000424IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000425 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000426 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000427
428 // Mark it as being a macro that is builtin.
429 MacroInfo *MI = new MacroInfo(SourceLocation());
430 MI->setIsBuiltinMacro();
431 Id->setMacroInfo(MI);
432 return Id;
433}
434
435
Chris Lattner677757a2006-06-28 05:26:32 +0000436/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
437/// identifier table.
438void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000439 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000440 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000441 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
442 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000443 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000444
445 // GCC Extensions.
446 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
447 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000448 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000449}
450
Chris Lattnerc2395832006-07-09 00:57:04 +0000451/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
452/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000453static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
454 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000455 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
456
457 // If the token isn't an identifier, it's always literally expanded.
458 if (II == 0) return true;
459
460 // If the identifier is a macro, and if that macro is enabled, it may be
461 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000462 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
463 // Fast expanding "#define X X" is ok, because X would be disabled.
464 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000465 return false;
466
467 // If this is an object-like macro invocation, it is safe to trivially expand
468 // it.
469 if (MI->isObjectLike()) return true;
470
471 // If this is a function-like macro invocation, it's safe to trivially expand
472 // as long as the identifier is not a macro argument.
473 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
474 I != E; ++I)
475 if (*I == II)
476 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000477
Chris Lattnerc2395832006-07-09 00:57:04 +0000478 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000479}
480
Chris Lattnerc2395832006-07-09 00:57:04 +0000481
Chris Lattnerafe603f2006-07-11 04:02:46 +0000482/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
483/// lexed is a '('. If so, consume the token and return true, if not, this
484/// method should have no observable side-effect on the lexed tokens.
485bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000486 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000487 unsigned Val;
488 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000489 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000490 else
491 Val = CurMacroExpander->isNextTokenLParen();
492
493 if (Val == 2) {
494 // If we ran off the end of the lexer or macro expander, walk the include
495 // stack, looking for whatever will return the next token.
496 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
497 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
498 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000499 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000500 else
501 Val = Entry.TheMacroExpander->isNextTokenLParen();
502 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000503 }
504
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000505 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
506 // have found something that isn't a '(' or we found the end of the
507 // translation unit. In either case, return false.
508 if (Val != 1)
509 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000510
511 LexerToken Tok;
512 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000513 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
514 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000515}
Chris Lattner677757a2006-06-28 05:26:32 +0000516
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000517/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
518/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000519bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000520 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000521
522 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
523 if (MI->isBuiltinMacro()) {
524 ExpandBuiltinMacro(Identifier);
525 return false;
526 }
527
Chris Lattner81278c62006-10-14 19:03:49 +0000528 // If this is the first use of a target-specific macro, warn about it.
529 if (MI->isTargetSpecific()) {
530 MI->setIsTargetSpecific(false); // Don't warn on second use.
531 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
532 diag::port_target_macro_use);
533 }
534
Chris Lattneree8760b2006-07-15 07:42:55 +0000535 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000536 /// for each macro argument, the list of tokens that were provided to the
537 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000538 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000539
540 // If this is a function-like macro, read the arguments.
541 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000542 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
543 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000544 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000545 return true;
546
Chris Lattner78186052006-07-09 00:45:31 +0000547 // Remember that we are now parsing the arguments to a macro invocation.
548 // Preprocessor directives used inside macro arguments are not portable, and
549 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000550 InMacroArgs = true;
551 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000552
553 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000554 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000555
556 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000557 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000558
559 ++NumFnMacroExpanded;
560 } else {
561 ++NumMacroExpanded;
562 }
Chris Lattner13044d92006-07-03 05:16:44 +0000563
564 // Notice that this macro has been used.
565 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000566
567 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000568
569 // If this macro expands to no tokens, don't bother to push it onto the
570 // expansion stack, only to take it right back off.
571 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000572 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000573 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000574
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000575 // Ignore this macro use, just return the next token in the current
576 // buffer.
577 bool HadLeadingSpace = Identifier.hasLeadingSpace();
578 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
579
580 Lex(Identifier);
581
582 // If the identifier isn't on some OTHER line, inherit the leading
583 // whitespace/first-on-a-line property of this token. This handles
584 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
585 // empty.
586 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000587 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
588 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000589 }
590 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000591 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000592
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000593 } else if (MI->getNumTokens() == 1 &&
594 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000595 // Otherwise, if this macro expands into a single trivially-expanded
596 // token: expand it now. This handles common cases like
597 // "#define VAL 42".
598
599 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
600 // identifier to the expanded token.
601 bool isAtStartOfLine = Identifier.isAtStartOfLine();
602 bool hasLeadingSpace = Identifier.hasLeadingSpace();
603
604 // Remember where the token is instantiated.
605 SourceLocation InstantiateLoc = Identifier.getLocation();
606
607 // Replace the result token.
608 Identifier = MI->getReplacementToken(0);
609
610 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000611 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
612 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000613
614 // Update the tokens location to include both its logical and physical
615 // locations.
616 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000617 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000618 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000619
Chris Lattner6e4bf522006-07-27 06:59:25 +0000620 // If this is #define X X, we must mark the result as unexpandible.
621 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
622 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000623 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000624
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000625 // Since this is not an identifier token, it can't be macro expanded, so
626 // we're done.
627 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000628 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000629 }
630
Chris Lattner78186052006-07-09 00:45:31 +0000631 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000632 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000633
634 // Now that the macro is at the top of the include stack, ask the
635 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000636 Lex(Identifier);
637 return false;
638}
639
Chris Lattneree8760b2006-07-15 07:42:55 +0000640/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000641/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000642/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000643MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
644 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000645 // The number of fixed arguments to parse.
646 unsigned NumFixedArgsLeft = MI->getNumArgs();
647 bool isVariadic = MI->isVariadic();
648
Chris Lattner78186052006-07-09 00:45:31 +0000649 // Outer loop, while there are more arguments, keep reading them.
650 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000651 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000652 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000653
654 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000655 // argument is separated by an EOF token. Use a SmallVector so we can avoid
656 // heap allocations in the common case.
657 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000658
659 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000660 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000661 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
662 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000663
Chris Lattner78186052006-07-09 00:45:31 +0000664 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000665 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
666 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000667 LexUnexpandedToken(Tok);
668
669 if (Tok.getKind() == tok::eof) {
670 Diag(MacroName, diag::err_unterm_macro_invoc);
671 // Do not lose the EOF. Return it to the client.
672 MacroName = Tok;
673 return 0;
674 } else if (Tok.getKind() == tok::r_paren) {
675 // If we found the ) token, the macro arg list is done.
676 if (NumParens-- == 0)
677 break;
678 } else if (Tok.getKind() == tok::l_paren) {
679 ++NumParens;
680 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
681 // Comma ends this argument if there are more fixed arguments expected.
682 if (NumFixedArgsLeft)
683 break;
684
Chris Lattner2ada5d32006-07-15 07:51:24 +0000685 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000686 if (!isVariadic) {
687 // Emit the diagnostic at the macro name in case there is a missing ).
688 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000689 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000690 return 0;
691 }
692 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000693 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000694 // If this is a comment token in the argument list and we're just in
695 // -C mode (not -CC mode), discard the comment.
696 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000697 }
698
699 ArgTokens.push_back(Tok);
700 }
701
Chris Lattnera12dd152006-07-11 04:09:02 +0000702 // Empty arguments are standard in C99 and supported as an extension in
703 // other modes.
704 if (ArgTokens.empty() && !Features.C99)
705 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000706
Chris Lattner36b6e812006-07-21 06:38:30 +0000707 // Add a marker EOF token to the end of the token list for this argument.
708 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000709 EOFTok.startToken();
710 EOFTok.setKind(tok::eof);
711 EOFTok.setLocation(Tok.getLocation());
712 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000713 ArgTokens.push_back(EOFTok);
714 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000715 --NumFixedArgsLeft;
716 };
717
718 // Okay, we either found the r_paren. Check to see if we parsed too few
719 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000720 unsigned MinArgsExpected = MI->getNumArgs();
721
Chris Lattner775d8322006-07-29 04:39:41 +0000722 // See MacroArgs instance var for description of this.
723 bool isVarargsElided = false;
724
Chris Lattner2ada5d32006-07-15 07:51:24 +0000725 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000726 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000727 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000728 // Varargs where the named vararg parameter is missing: ok as extension.
729 // #define A(x, ...)
730 // A("blah")
731 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000732
733 // Remember this occurred if this is a C99 macro invocation with at least
734 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000735 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000736 } else if (MI->getNumArgs() == 1) {
737 // #define A(x)
738 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000739 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000740
741 // Empty arguments are standard in C99 and supported as an extension in
742 // other modes.
743 if (ArgTokens.empty() && !Features.C99)
744 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000745 } else {
746 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000747 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000748 return 0;
749 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000750
751 // Add a marker EOF token to the end of the token list for this argument.
752 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000753 Tok.startToken();
754 Tok.setKind(tok::eof);
755 Tok.setLocation(EndLoc);
756 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000757 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000758 }
759
Chris Lattner775d8322006-07-29 04:39:41 +0000760 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000761}
762
Chris Lattnerc673f902006-06-30 06:10:41 +0000763/// ComputeDATE_TIME - Compute the current time, enter it into the specified
764/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
765/// the identifier tokens inserted.
766static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000767 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000768 time_t TT = time(0);
769 struct tm *TM = localtime(&TT);
770
771 static const char * const Months[] = {
772 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
773 };
774
775 char TmpBuffer[100];
776 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
777 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000778 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000779
780 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000781 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000782}
783
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000784/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
785/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000786void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000787 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000788 IdentifierInfo *II = Tok.getIdentifierInfo();
789 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000790
791 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
792 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000793 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000794 return Handle_Pragma(Tok);
795
Chris Lattner78186052006-07-09 00:45:31 +0000796 ++NumBuiltinMacroExpanded;
797
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000798 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000799
800 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000801 Tok.setIdentifierInfo(0);
802 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000803
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000804 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000805 // __LINE__ expands to a simple numeric value.
806 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
807 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000808 Tok.setKind(tok::numeric_constant);
809 Tok.setLength(Length);
810 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000811 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000812 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000813 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000814 Diag(Tok, diag::ext_pp_base_file);
815 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
816 while (NextLoc.getFileID() != 0) {
817 Loc = NextLoc;
818 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
819 }
820 }
821
Chris Lattner0766e592006-07-03 01:07:01 +0000822 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
823 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000824 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000825 Tok.setKind(tok::string_literal);
826 Tok.setLength(FN.size());
827 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000828 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000829 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000830 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000831 Tok.setKind(tok::string_literal);
832 Tok.setLength(strlen("\"Mmm dd yyyy\""));
833 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000834 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000835 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000836 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000837 Tok.setKind(tok::string_literal);
838 Tok.setLength(strlen("\"hh:mm:ss\""));
839 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000840 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000841 Diag(Tok, diag::ext_pp_include_level);
842
843 // Compute the include depth of this token.
844 unsigned Depth = 0;
845 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
846 for (; Loc.getFileID() != 0; ++Depth)
847 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
848
849 // __INCLUDE_LEVEL__ expands to a simple numeric value.
850 sprintf(TmpBuffer, "%u", Depth);
851 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000852 Tok.setKind(tok::numeric_constant);
853 Tok.setLength(Length);
854 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000855 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000856 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
857 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
858 Diag(Tok, diag::ext_pp_timestamp);
859
860 // Get the file that we are lexing out of. If we're currently lexing from
861 // a macro, dig into the include stack.
862 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000863 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000864
865 if (TheLexer)
866 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
867
868 // If this file is older than the file it depends on, emit a diagnostic.
869 const char *Result;
870 if (CurFile) {
871 time_t TT = CurFile->getModificationTime();
872 struct tm *TM = localtime(&TT);
873 Result = asctime(TM);
874 } else {
875 Result = "??? ??? ?? ??:??:?? ????\n";
876 }
877 TmpBuffer[0] = '"';
878 strcpy(TmpBuffer+1, Result);
879 unsigned Len = strlen(TmpBuffer);
880 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000881 Tok.setKind(tok::string_literal);
882 Tok.setLength(Len);
883 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000884 } else {
885 assert(0 && "Unknown identifier!");
886 }
887}
Chris Lattner677757a2006-06-28 05:26:32 +0000888
Chris Lattner13044d92006-07-03 05:16:44 +0000889namespace {
Chris Lattner54d032b2007-02-08 19:24:25 +0000890struct UnusedIdentifierReporter : public StringMapVisitor {
Chris Lattner13044d92006-07-03 05:16:44 +0000891 Preprocessor &PP;
892 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
893
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000894 void Visit(const char *Key, StringMapEntryBase *Value) const {
895 IdentifierInfo &II =
896 static_cast<StringMapEntry<IdentifierInfo>*>(Value)->getValue();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000897 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
898 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000899 }
900};
901}
902
Chris Lattner677757a2006-06-28 05:26:32 +0000903//===----------------------------------------------------------------------===//
904// Lexer Event Handling.
905//===----------------------------------------------------------------------===//
906
Chris Lattnercefc7682006-07-08 08:28:12 +0000907/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
908/// identifier information for the token and install it into the token.
909IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
910 const char *BufPtr) {
911 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
912 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
913
914 // Look up this token, see if it is a macro, or if it is a language keyword.
915 IdentifierInfo *II;
916 if (BufPtr && !Identifier.needsCleaning()) {
917 // No cleaning needed, just use the characters from the lexed buffer.
918 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
919 } else {
920 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
921 const char *TmpBuf = (char*)alloca(Identifier.getLength());
922 unsigned Size = getSpelling(Identifier, TmpBuf);
923 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
924 }
Chris Lattner8c204872006-10-14 05:19:21 +0000925 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000926 return II;
927}
928
929
Chris Lattner677757a2006-06-28 05:26:32 +0000930/// HandleIdentifier - This callback is invoked when the lexer reads an
931/// identifier. This callback looks up the identifier in the map and/or
932/// potentially macro expands it or turns it into a named token (like 'for').
933void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000934 assert(Identifier.getIdentifierInfo() &&
935 "Can't handle identifiers without identifier info!");
936
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000937 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000938
939 // If this identifier was poisoned, and if it was not produced from a macro
940 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000941 if (II.isPoisoned() && CurLexer) {
942 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
943 Diag(Identifier, diag::err_pp_used_poisoned_id);
944 else
945 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
946 }
Chris Lattner677757a2006-06-28 05:26:32 +0000947
Chris Lattner78186052006-07-09 00:45:31 +0000948 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000949 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000950 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
951 if (MI->isEnabled()) {
952 if (!HandleMacroExpandedIdentifier(Identifier, MI))
953 return;
954 } else {
955 // C99 6.10.3.4p2 says that a disabled macro may never again be
956 // expanded, even if it's in a context where it could be expanded in the
957 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000958 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000959 }
960 }
Chris Lattner063400e2006-10-14 19:54:15 +0000961 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
962 // If this identifier is a macro on some other target, emit a diagnostic.
963 // This diagnosic is only emitted when macro expansion is enabled, because
964 // the macro would not have been expanded for the other target either.
965 II.setIsOtherTargetMacro(false); // Don't warn on second use.
966 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
967 diag::port_target_macro_use);
968
969 }
Chris Lattner677757a2006-06-28 05:26:32 +0000970
Chris Lattner5b9f4892006-11-21 17:23:33 +0000971 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
972 // then we act as if it is the actual operator and not the textual
973 // representation of it.
974 if (II.isCPlusPlusOperatorKeyword())
975 Identifier.setIdentifierInfo(0);
976
Chris Lattner677757a2006-06-28 05:26:32 +0000977 // Change the kind of this identifier to the appropriate token kind, e.g.
978 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000979 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000980
981 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000982 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000983}
984
Chris Lattner22eb9722006-06-18 05:43:12 +0000985/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
986/// the current file. This either returns the EOF token or pops a level off
987/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000988bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000989 assert(!CurMacroExpander &&
990 "Ending a file when currently in a macro!");
991
Chris Lattner371ac8a2006-07-04 07:11:10 +0000992 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000993 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000994 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000995 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000996 // Okay, this has a controlling macro, remember in PerFileInfo.
997 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000998 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
999 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001000 }
1001 }
1002
Chris Lattner22eb9722006-06-18 05:43:12 +00001003 // If this is a #include'd file, pop it off the include stack and continue
1004 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001005 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001006 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001007 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001008
1009 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001010 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001011 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1012
1013 // Get the file entry for the current file.
1014 if (const FileEntry *FE =
1015 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001016 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001017
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001018 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1019 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001020 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001021
1022 // Client should lex another token.
1023 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001024 }
1025
Chris Lattner8c204872006-10-14 05:19:21 +00001026 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001027 CurLexer->BufferPtr = CurLexer->BufferEnd;
1028 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001029 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001030
1031 // We're done with the #included file.
1032 delete CurLexer;
1033 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001034
Chris Lattner03f83482006-07-10 06:16:26 +00001035 // This is the end of the top-level file. If the diag::pp_macro_not_used
1036 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1037 // have not been used.
1038 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1039 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001040
1041 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001042}
1043
1044/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001045/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001046bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001047 assert(CurMacroExpander && !CurLexer &&
1048 "Ending a macro when currently in a #include file!");
1049
Chris Lattner22eb9722006-06-18 05:43:12 +00001050 delete CurMacroExpander;
1051
Chris Lattner69772b02006-07-02 20:34:39 +00001052 // Handle this like a #include file being popped off the stack.
1053 CurMacroExpander = 0;
1054 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001055}
1056
1057
1058//===----------------------------------------------------------------------===//
1059// Utility Methods for Preprocessor Directive Handling.
1060//===----------------------------------------------------------------------===//
1061
1062/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1063/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001064void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001065 LexerToken Tmp;
1066 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001067 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001068 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001069}
1070
Chris Lattner652c1692006-11-21 23:47:30 +00001071/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1072static bool isCXXNamedOperator(const std::string &Spelling) {
1073 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1074 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1075 Spelling == "or" || Spelling == "xor";
1076}
1077
Chris Lattner22eb9722006-06-18 05:43:12 +00001078/// ReadMacroName - Lex and validate a macro name, which occurs after a
1079/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001080/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1081/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001082/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001083void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001084 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001085 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001086
1087 // Missing macro name?
1088 if (MacroNameTok.getKind() == tok::eom)
1089 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1090
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001091 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1092 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001093 std::string Spelling = getSpelling(MacroNameTok);
1094 if (isCXXNamedOperator(Spelling))
1095 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1096 // except for their spellings.
1097 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1098 else
1099 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001100 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001101 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001102 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001103 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001104 } else if (isDefineUndef && II->getMacroInfo() &&
1105 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001106 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001107 if (isDefineUndef == 1)
1108 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1109 else
1110 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001111 } else {
1112 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001113 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001114 }
1115
Chris Lattner22eb9722006-06-18 05:43:12 +00001116 // Invalid macro name, read and discard the rest of the line. Then set the
1117 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001118 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001119 return DiscardUntilEndOfDirective();
1120}
1121
1122/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1123/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001124void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001125 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001126 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001127 // There should be no tokens after the directive, but we allow them as an
1128 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001129 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1130 Lex(Tmp);
1131
Chris Lattner22eb9722006-06-18 05:43:12 +00001132 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001133 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1134 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001136}
1137
1138
1139
1140/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1141/// decided that the subsequent tokens are in the #if'd out portion of the
1142/// file. Lex the rest of the file, until we see an #endif. If
1143/// FoundNonSkipPortion is true, then we have already emitted code for part of
1144/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1145/// is true, then #else directives are ok, if not, then we have already seen one
1146/// so a #else directive is a duplicate. When this returns, the caller can lex
1147/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001148void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001149 bool FoundNonSkipPortion,
1150 bool FoundElse) {
1151 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001152 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001153 "Lexing a macro, not a file?");
1154
1155 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1156 FoundNonSkipPortion, FoundElse);
1157
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001158 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1159 // disabling warnings, etc.
1160 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001161 LexerToken Tok;
1162 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001163 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001164
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001165 // If this is the end of the buffer, we have an error.
1166 if (Tok.getKind() == tok::eof) {
1167 // Emit errors for each unterminated conditional on the stack, including
1168 // the current one.
1169 while (!CurLexer->ConditionalStack.empty()) {
1170 Diag(CurLexer->ConditionalStack.back().IfLoc,
1171 diag::err_pp_unterminated_conditional);
1172 CurLexer->ConditionalStack.pop_back();
1173 }
1174
1175 // Just return and let the caller lex after this #include.
1176 break;
1177 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001178
1179 // If this token is not a preprocessor directive, just skip it.
1180 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1181 continue;
1182
1183 // We just parsed a # character at the start of a line, so we're in
1184 // directive mode. Tell the lexer this so any newlines we see will be
1185 // converted into an EOM token (this terminates the macro).
1186 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001187 CurLexer->KeepCommentMode = false;
1188
Chris Lattner22eb9722006-06-18 05:43:12 +00001189
1190 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001191 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001192
1193 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1194 // something bogus), skip it.
1195 if (Tok.getKind() != tok::identifier) {
1196 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001197 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001198 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001199 continue;
1200 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001201
Chris Lattner22eb9722006-06-18 05:43:12 +00001202 // If the first letter isn't i or e, it isn't intesting to us. We know that
1203 // this is safe in the face of spelling differences, because there is no way
1204 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001205 // allows us to avoid looking up the identifier info for #define/#undef and
1206 // other common directives.
1207 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1208 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001209 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1210 FirstChar != 'i' && FirstChar != 'e') {
1211 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001212 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001213 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001214 continue;
1215 }
1216
Chris Lattnere60165f2006-06-22 06:36:29 +00001217 // Get the identifier name without trigraphs or embedded newlines. Note
1218 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1219 // when skipping.
1220 // TODO: could do this with zero copies in the no-clean case by using
1221 // strncmp below.
1222 char Directive[20];
1223 unsigned IdLen;
1224 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1225 IdLen = Tok.getLength();
1226 memcpy(Directive, RawCharData, IdLen);
1227 Directive[IdLen] = 0;
1228 } else {
1229 std::string DirectiveStr = getSpelling(Tok);
1230 IdLen = DirectiveStr.size();
1231 if (IdLen >= 20) {
1232 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001233 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001234 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001235 continue;
1236 }
1237 memcpy(Directive, &DirectiveStr[0], IdLen);
1238 Directive[IdLen] = 0;
1239 }
1240
Chris Lattner22eb9722006-06-18 05:43:12 +00001241 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001242 if ((IdLen == 2) || // "if"
1243 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1244 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001245 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1246 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001247 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001248 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001249 /*foundnonskip*/false,
1250 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001251 }
1252 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001253 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001254 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001255 PPConditionalInfo CondInfo;
1256 CondInfo.WasSkipping = true; // Silence bogus warning.
1257 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001258 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001259 assert(!InCond && "Can't be skipping if not in a conditional!");
1260
1261 // If we popped the outermost skipping block, we're done skipping!
1262 if (!CondInfo.WasSkipping)
1263 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001264 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001265 // #else directive in a skipping conditional. If not in some other
1266 // skipping conditional, and if #else hasn't already been seen, enter it
1267 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001268 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001269 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1270
1271 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001272 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001273
1274 // Note that we've seen a #else in this conditional.
1275 CondInfo.FoundElse = true;
1276
1277 // If the conditional is at the top level, and the #if block wasn't
1278 // entered, enter the #else block now.
1279 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1280 CondInfo.FoundNonSkip = true;
1281 break;
1282 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001283 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001284 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1285
1286 bool ShouldEnter;
1287 // If this is in a skipping block or if we're already handled this #if
1288 // block, don't bother parsing the condition.
1289 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001290 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001291 ShouldEnter = false;
1292 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001293 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001294 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001295 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1296 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001297 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001298 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001299 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001300 }
1301
1302 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001303 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001304
1305 // If this condition is true, enter it!
1306 if (ShouldEnter) {
1307 CondInfo.FoundNonSkip = true;
1308 break;
1309 }
1310 }
1311 }
1312
1313 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001314 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001315 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001316 }
1317
1318 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1319 // of the file, just stop skipping and return to lexing whatever came after
1320 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001321 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001322}
1323
1324//===----------------------------------------------------------------------===//
1325// Preprocessor Directive Handling.
1326//===----------------------------------------------------------------------===//
1327
1328/// HandleDirective - This callback is invoked when the lexer sees a # token
1329/// at the start of a line. This consumes the directive, modifies the
1330/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1331/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001332void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001333 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001334
1335 // We just parsed a # character at the start of a line, so we're in directive
1336 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001337 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001338 CurLexer->ParsingPreprocessorDirective = true;
1339
1340 ++NumDirectives;
1341
Chris Lattner371ac8a2006-07-04 07:11:10 +00001342 // We are about to read a token. For the multiple-include optimization FA to
1343 // work, we have to remember if we had read any tokens *before* this
1344 // pp-directive.
1345 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1346
Chris Lattner78186052006-07-09 00:45:31 +00001347 // Read the next token, the directive flavor. This isn't expanded due to
1348 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001349 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001350
Chris Lattner78186052006-07-09 00:45:31 +00001351 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1352 // #define A(x) #x
1353 // A(abc
1354 // #warning blah
1355 // def)
1356 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001357 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001358 Diag(Result, diag::ext_embedded_directive);
1359
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001360TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001361 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001362 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001363 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001364 case tok::comment:
1365 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1366 LexUnexpandedToken(Result);
1367 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001368
Chris Lattner22eb9722006-06-18 05:43:12 +00001369 case tok::numeric_constant:
1370 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001371 DiscardUntilEndOfDirective();
1372 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001373 default:
1374 IdentifierInfo *II = Result.getIdentifierInfo();
1375 if (II == 0) break; // Not an identifier.
1376
1377 // Ask what the preprocessor keyword ID is.
1378 switch (II->getPPKeywordID()) {
1379 default: break;
1380 // C99 6.10.1 - Conditional Inclusion.
1381 case tok::pp_if:
1382 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1383 case tok::pp_ifdef:
1384 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1385 case tok::pp_ifndef:
1386 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1387 case tok::pp_elif:
1388 return HandleElifDirective(Result);
1389 case tok::pp_else:
1390 return HandleElseDirective(Result);
1391 case tok::pp_endif:
1392 return HandleEndifDirective(Result);
1393
1394 // C99 6.10.2 - Source File Inclusion.
1395 case tok::pp_include:
1396 return HandleIncludeDirective(Result); // Handle #include.
1397
1398 // C99 6.10.3 - Macro Replacement.
1399 case tok::pp_define:
1400 return HandleDefineDirective(Result, false);
1401 case tok::pp_undef:
1402 return HandleUndefDirective(Result);
1403
1404 // C99 6.10.4 - Line Control.
1405 case tok::pp_line:
1406 // FIXME: implement #line
1407 DiscardUntilEndOfDirective();
1408 return;
1409
1410 // C99 6.10.5 - Error Directive.
1411 case tok::pp_error:
1412 return HandleUserDiagnosticDirective(Result, false);
1413
1414 // C99 6.10.6 - Pragma Directive.
1415 case tok::pp_pragma:
1416 return HandlePragmaDirective();
1417
1418 // GNU Extensions.
1419 case tok::pp_import:
1420 return HandleImportDirective(Result);
1421 case tok::pp_include_next:
1422 return HandleIncludeNextDirective(Result);
1423
1424 case tok::pp_warning:
1425 Diag(Result, diag::ext_pp_warning_directive);
1426 return HandleUserDiagnosticDirective(Result, true);
1427 case tok::pp_ident:
1428 return HandleIdentSCCSDirective(Result);
1429 case tok::pp_sccs:
1430 return HandleIdentSCCSDirective(Result);
1431 case tok::pp_assert:
1432 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001433 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001434 case tok::pp_unassert:
1435 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001436 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001437
1438 // clang extensions.
1439 case tok::pp_define_target:
1440 return HandleDefineDirective(Result, true);
1441 case tok::pp_define_other_target:
1442 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001443 }
1444 break;
1445 }
1446
1447 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001448 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001449
1450 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001451 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001452
1453 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001454}
1455
Chris Lattner01d66cc2006-07-03 22:16:27 +00001456void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001457 bool isWarning) {
1458 // Read the rest of the line raw. We do this because we don't want macros
1459 // to be expanded and we don't require that the tokens be valid preprocessing
1460 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1461 // collapse multiple consequtive white space between tokens, but this isn't
1462 // specified by the standard.
1463 std::string Message = CurLexer->ReadToEndOfLine();
1464
1465 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001466 return Diag(Tok, DiagID, Message);
1467}
1468
1469/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1470///
1471void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001472 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001473 Diag(Tok, diag::ext_pp_ident_directive);
1474
Chris Lattner371ac8a2006-07-04 07:11:10 +00001475 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001476 LexerToken StrTok;
1477 Lex(StrTok);
1478
1479 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001480 if (StrTok.getKind() != tok::string_literal &&
1481 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001482 return Diag(StrTok, diag::err_pp_malformed_ident);
1483
1484 // Verify that there is nothing after the string, other than EOM.
1485 CheckEndOfDirective("#ident");
1486
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001487 if (Callbacks)
1488 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001489}
1490
Chris Lattnerb8761832006-06-24 21:31:03 +00001491//===----------------------------------------------------------------------===//
1492// Preprocessor Include Directive Handling.
1493//===----------------------------------------------------------------------===//
1494
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001495/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1496/// checked and spelled filename, e.g. as an operand of #include. This returns
1497/// true if the input filename was in <>'s or false if it were in ""'s. The
1498/// caller is expected to provide a buffer that is large enough to hold the
1499/// spelling of the filename, but is also expected to handle the case when
1500/// this method decides to use a different buffer.
1501bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1502 const char *&BufStart,
1503 const char *&BufEnd) {
1504 // Get the text form of the filename.
1505 unsigned Len = getSpelling(FilenameTok, BufStart);
1506 BufEnd = BufStart+Len;
1507 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1508
1509 // Make sure the filename is <x> or "x".
1510 bool isAngled;
1511 if (BufStart[0] == '<') {
1512 if (BufEnd[-1] != '>') {
1513 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1514 BufStart = 0;
1515 return true;
1516 }
1517 isAngled = true;
1518 } else if (BufStart[0] == '"') {
1519 if (BufEnd[-1] != '"') {
1520 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1521 BufStart = 0;
1522 return true;
1523 }
1524 isAngled = false;
1525 } else {
1526 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1527 BufStart = 0;
1528 return true;
1529 }
1530
1531 // Diagnose #include "" as invalid.
1532 if (BufEnd-BufStart <= 2) {
1533 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1534 BufStart = 0;
1535 return "";
1536 }
1537
1538 // Skip the brackets.
1539 ++BufStart;
1540 --BufEnd;
1541 return isAngled;
1542}
1543
Chris Lattner22eb9722006-06-18 05:43:12 +00001544/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1545/// file to be included from the lexer, then include it! This is a common
1546/// routine with functionality shared between #include, #include_next and
1547/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001548void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001549 const DirectoryLookup *LookupFrom,
1550 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001551
Chris Lattner22eb9722006-06-18 05:43:12 +00001552 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001553 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001554
1555 // If the token kind is EOM, the error has already been diagnosed.
1556 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001557 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001558
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001559 // Reserve a buffer to get the spelling.
1560 SmallVector<char, 128> FilenameBuffer;
1561 FilenameBuffer.resize(FilenameTok.getLength());
1562
1563 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1564 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1565 FilenameStart, FilenameEnd);
1566 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1567 // error.
1568 if (FilenameStart == 0)
1569 return;
1570
Chris Lattner269c2322006-06-25 06:23:00 +00001571 // Verify that there is nothing after the filename, other than EOM. Use the
1572 // preprocessor to lex this in case lexing the filename entered a macro.
1573 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001574
1575 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001576 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001577 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1578
Chris Lattner22eb9722006-06-18 05:43:12 +00001579 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001580 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001581 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001582 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001583 if (File == 0)
1584 return Diag(FilenameTok, diag::err_pp_file_not_found);
1585
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001586 // Ask HeaderInfo if we should enter this #include file.
1587 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1588 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001589 return;
1590 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001591
1592 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001593 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001594 if (FileID == 0)
1595 return Diag(FilenameTok, diag::err_pp_file_not_found);
1596
1597 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001598 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001599}
1600
1601/// HandleIncludeNextDirective - Implements #include_next.
1602///
Chris Lattnercb283342006-06-18 06:48:37 +00001603void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1604 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001605
1606 // #include_next is like #include, except that we start searching after
1607 // the current found directory. If we can't do this, issue a
1608 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001609 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001610 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001611 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001612 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001613 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001614 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001615 } else {
1616 // Start looking up in the next directory.
1617 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001618 }
1619
1620 return HandleIncludeDirective(IncludeNextTok, Lookup);
1621}
1622
1623/// HandleImportDirective - Implements #import.
1624///
Chris Lattnercb283342006-06-18 06:48:37 +00001625void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1626 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001627
1628 return HandleIncludeDirective(ImportTok, 0, true);
1629}
1630
Chris Lattnerb8761832006-06-24 21:31:03 +00001631//===----------------------------------------------------------------------===//
1632// Preprocessor Macro Directive Handling.
1633//===----------------------------------------------------------------------===//
1634
Chris Lattnercefc7682006-07-08 08:28:12 +00001635/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1636/// definition has just been read. Lex the rest of the arguments and the
1637/// closing ), updating MI with what we learn. Return true if an error occurs
1638/// parsing the arg list.
1639bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1640 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001641 while (1) {
1642 LexUnexpandedToken(Tok);
1643 switch (Tok.getKind()) {
1644 case tok::r_paren:
1645 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001646 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001647 // Otherwise we have #define FOO(A,)
1648 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1649 return true;
1650 case tok::ellipsis: // #define X(... -> C99 varargs
1651 // Warn if use of C99 feature in non-C99 mode.
1652 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1653
1654 // Lex the token after the identifier.
1655 LexUnexpandedToken(Tok);
1656 if (Tok.getKind() != tok::r_paren) {
1657 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1658 return true;
1659 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001660 // Add the __VA_ARGS__ identifier as an argument.
1661 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001662 MI->setIsC99Varargs();
1663 return false;
1664 case tok::eom: // #define X(
1665 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1666 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001667 default:
1668 // Handle keywords and identifiers here to accept things like
1669 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001670 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001671 if (II == 0) {
1672 // #define X(1
1673 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1674 return true;
1675 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001676
1677 // If this is already used as an argument, it is used multiple times (e.g.
1678 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001679 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001680 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1681 return true;
1682 }
1683
1684 // Add the argument to the macro info.
1685 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001686
1687 // Lex the token after the identifier.
1688 LexUnexpandedToken(Tok);
1689
1690 switch (Tok.getKind()) {
1691 default: // #define X(A B
1692 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1693 return true;
1694 case tok::r_paren: // #define X(A)
1695 return false;
1696 case tok::comma: // #define X(A,
1697 break;
1698 case tok::ellipsis: // #define X(A... -> GCC extension
1699 // Diagnose extension.
1700 Diag(Tok, diag::ext_named_variadic_macro);
1701
1702 // Lex the token after the identifier.
1703 LexUnexpandedToken(Tok);
1704 if (Tok.getKind() != tok::r_paren) {
1705 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1706 return true;
1707 }
1708
1709 MI->setIsGNUVarargs();
1710 return false;
1711 }
1712 }
1713 }
1714}
1715
Chris Lattner22eb9722006-06-18 05:43:12 +00001716/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001717/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1718/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001719///
Chris Lattner81278c62006-10-14 19:03:49 +00001720void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1721 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001722 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001723
Chris Lattner22eb9722006-06-18 05:43:12 +00001724 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001725 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001726
1727 // Error reading macro name? If so, diagnostic already issued.
1728 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001729 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001730
Chris Lattner457fc152006-07-29 06:30:25 +00001731 // If we are supposed to keep comments in #defines, reenable comment saving
1732 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001733 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001734
Chris Lattner063400e2006-10-14 19:54:15 +00001735 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001736 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001737 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001738
Chris Lattner063400e2006-10-14 19:54:15 +00001739 // If the identifier is an 'other target' macro, clear this bit.
1740 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1741
1742
Chris Lattner22eb9722006-06-18 05:43:12 +00001743 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001744 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001745
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001746 // If this is a function-like macro definition, parse the argument list,
1747 // marking each of the identifiers as being used as macro arguments. Also,
1748 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001749 if (Tok.getKind() == tok::eom) {
1750 // If there is no body to this macro, we have no special handling here.
1751 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001752 // This is a function-like macro definition. Read the argument list.
1753 MI->setIsFunctionLike();
1754 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001755 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001756 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001757 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001758 if (CurLexer->ParsingPreprocessorDirective)
1759 DiscardUntilEndOfDirective();
1760 return;
1761 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001762
Chris Lattner815a1f92006-07-08 20:48:04 +00001763 // Read the first token after the arg list for down below.
1764 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001765 } else if (!Tok.hasLeadingSpace()) {
1766 // C99 requires whitespace between the macro definition and the body. Emit
1767 // a diagnostic for something like "#define X+".
1768 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001769 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001770 } else {
1771 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1772 // one in some cases!
1773 }
1774 } else {
1775 // This is a normal token with leading space. Clear the leading space
1776 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001777 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001778 }
1779
Chris Lattner7e374832006-07-29 03:46:57 +00001780 // If this is a definition of a variadic C99 function-like macro, not using
1781 // the GNU named varargs extension, enabled __VA_ARGS__.
1782
1783 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1784 // This gets unpoisoned where it is allowed.
1785 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1786 if (MI->isC99Varargs())
1787 Ident__VA_ARGS__->setIsPoisoned(false);
1788
Chris Lattner22eb9722006-06-18 05:43:12 +00001789 // Read the rest of the macro body.
1790 while (Tok.getKind() != tok::eom) {
1791 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001792
1793 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001794 // parameters in function-like macro expansions.
1795 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001796 // Get the next token of the macro.
1797 LexUnexpandedToken(Tok);
1798 continue;
1799 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001800
Chris Lattner815a1f92006-07-08 20:48:04 +00001801 // Get the next token of the macro.
1802 LexUnexpandedToken(Tok);
1803
1804 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001805 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001806 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001807 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001808 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001809
1810 // Disable __VA_ARGS__ again.
1811 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001812 return;
1813 }
1814
1815 // Things look ok, add the param name token to the macro.
1816 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001817
Chris Lattner22eb9722006-06-18 05:43:12 +00001818 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001819 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001820 }
Chris Lattner7e374832006-07-29 03:46:57 +00001821
1822 // Disable __VA_ARGS__ again.
1823 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001824
Chris Lattnerbff18d52006-07-06 04:49:18 +00001825 // Check that there is no paste (##) operator at the begining or end of the
1826 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001827 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001828 if (NumTokens != 0) {
1829 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001830 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001831 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001832 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001833 }
1834 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001835 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001836 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001837 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001838 }
1839 }
1840
Chris Lattner13044d92006-07-03 05:16:44 +00001841 // If this is the primary source file, remember that this macro hasn't been
1842 // used yet.
1843 if (isInPrimaryFile())
1844 MI->setIsUsed(false);
1845
Chris Lattner22eb9722006-06-18 05:43:12 +00001846 // Finally, if this identifier already had a macro defined for it, verify that
1847 // the macro bodies are identical and free the old definition.
1848 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001849 if (!OtherMI->isUsed())
1850 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1851
Chris Lattner22eb9722006-06-18 05:43:12 +00001852 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001853 // must be the same. C99 6.10.3.2.
1854 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001855 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1856 MacroNameTok.getIdentifierInfo()->getName());
1857 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1858 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001859 delete OtherMI;
1860 }
1861
1862 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001863}
1864
Chris Lattner063400e2006-10-14 19:54:15 +00001865/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1866void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1867 LexerToken MacroNameTok;
1868 ReadMacroName(MacroNameTok, 1);
1869
1870 // Error reading macro name? If so, diagnostic already issued.
1871 if (MacroNameTok.getKind() == tok::eom)
1872 return;
1873
1874 // Check to see if this is the last token on the #undef line.
1875 CheckEndOfDirective("#define_other_target");
1876
1877 // If there is already a macro defined by this name, turn it into a
1878 // target-specific define.
1879 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1880 MI->setIsTargetSpecific(true);
1881 return;
1882 }
1883
1884 // Mark the identifier as being a macro on some other target.
1885 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1886}
1887
Chris Lattner22eb9722006-06-18 05:43:12 +00001888
1889/// HandleUndefDirective - Implements #undef.
1890///
Chris Lattnercb283342006-06-18 06:48:37 +00001891void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001892 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001893
Chris Lattner22eb9722006-06-18 05:43:12 +00001894 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001895 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001896
1897 // Error reading macro name? If so, diagnostic already issued.
1898 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001899 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001900
1901 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001902 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001903
1904 // Okay, we finally have a valid identifier to undef.
1905 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1906
Chris Lattner063400e2006-10-14 19:54:15 +00001907 // #undef untaints an identifier if it were marked by define_other_target.
1908 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1909
Chris Lattner22eb9722006-06-18 05:43:12 +00001910 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001911 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001912
Chris Lattner13044d92006-07-03 05:16:44 +00001913 if (!MI->isUsed())
1914 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001915
1916 // Free macro definition.
1917 delete MI;
1918 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001919}
1920
1921
Chris Lattnerb8761832006-06-24 21:31:03 +00001922//===----------------------------------------------------------------------===//
1923// Preprocessor Conditional Directive Handling.
1924//===----------------------------------------------------------------------===//
1925
Chris Lattner22eb9722006-06-18 05:43:12 +00001926/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001927/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1928/// if any tokens have been returned or pp-directives activated before this
1929/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001930///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001931void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1932 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001933 ++NumIf;
1934 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001935
Chris Lattner22eb9722006-06-18 05:43:12 +00001936 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001937 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001938
1939 // Error reading macro name? If so, diagnostic already issued.
1940 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001941 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001942
1943 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001944 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1945
1946 // If the start of a top-level #ifdef, inform MIOpt.
1947 if (!ReadAnyTokensBeforeDirective &&
1948 CurLexer->getConditionalStackDepth() == 0) {
1949 assert(isIfndef && "#ifdef shouldn't reach here");
1950 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1951 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001952
Chris Lattner063400e2006-10-14 19:54:15 +00001953 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1954 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001955
Chris Lattner81278c62006-10-14 19:03:49 +00001956 // If there is a macro, process it.
1957 if (MI) {
1958 // Mark it used.
1959 MI->setIsUsed(true);
1960
1961 // If this is the first use of a target-specific macro, warn about it.
1962 if (MI->isTargetSpecific()) {
1963 MI->setIsTargetSpecific(false); // Don't warn on second use.
1964 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1965 diag::port_target_macro_use);
1966 }
Chris Lattner063400e2006-10-14 19:54:15 +00001967 } else {
1968 // Use of a target-specific macro for some other target? If so, warn.
1969 if (MII->isOtherTargetMacro()) {
1970 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1971 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1972 diag::port_target_macro_use);
1973 }
Chris Lattner81278c62006-10-14 19:03:49 +00001974 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001975
Chris Lattner22eb9722006-06-18 05:43:12 +00001976 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001977 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001978 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001979 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001980 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001981 } else {
1982 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001983 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001984 /*Foundnonskip*/false,
1985 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001986 }
1987}
1988
1989/// HandleIfDirective - Implements the #if directive.
1990///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001991void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1992 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001993 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001994
Chris Lattner371ac8a2006-07-04 07:11:10 +00001995 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001996 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001997 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001998
1999 // Should we include the stuff contained by this directive?
2000 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002001 // If this condition is equivalent to #ifndef X, and if this is the first
2002 // directive seen, handle it for the multiple-include optimization.
2003 if (!ReadAnyTokensBeforeDirective &&
2004 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2005 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2006
Chris Lattner22eb9722006-06-18 05:43:12 +00002007 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002008 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002009 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002010 } else {
2011 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002012 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002013 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002014 }
2015}
2016
2017/// HandleEndifDirective - Implements the #endif directive.
2018///
Chris Lattnercb283342006-06-18 06:48:37 +00002019void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002020 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002021
Chris Lattner22eb9722006-06-18 05:43:12 +00002022 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002023 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002024
2025 PPConditionalInfo CondInfo;
2026 if (CurLexer->popConditionalLevel(CondInfo)) {
2027 // No conditionals on the stack: this is an #endif without an #if.
2028 return Diag(EndifToken, diag::err_pp_endif_without_if);
2029 }
2030
Chris Lattner371ac8a2006-07-04 07:11:10 +00002031 // If this the end of a top-level #endif, inform MIOpt.
2032 if (CurLexer->getConditionalStackDepth() == 0)
2033 CurLexer->MIOpt.ExitTopLevelConditional();
2034
Chris Lattner538d7f32006-07-20 04:31:52 +00002035 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002036 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002037}
2038
2039
Chris Lattnercb283342006-06-18 06:48:37 +00002040void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002041 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002042
Chris Lattner22eb9722006-06-18 05:43:12 +00002043 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002044 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002045
2046 PPConditionalInfo CI;
2047 if (CurLexer->popConditionalLevel(CI))
2048 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002049
2050 // If this is a top-level #else, inform the MIOpt.
2051 if (CurLexer->getConditionalStackDepth() == 0)
2052 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002053
2054 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002055 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002056
2057 // Finally, skip the rest of the contents of this block and return the first
2058 // token after it.
2059 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2060 /*FoundElse*/true);
2061}
2062
Chris Lattnercb283342006-06-18 06:48:37 +00002063void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002064 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002065
Chris Lattner22eb9722006-06-18 05:43:12 +00002066 // #elif directive in a non-skipping conditional... start skipping.
2067 // We don't care what the condition is, because we will always skip it (since
2068 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002069 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002070
2071 PPConditionalInfo CI;
2072 if (CurLexer->popConditionalLevel(CI))
2073 return Diag(ElifToken, diag::pp_err_elif_without_if);
2074
Chris Lattner371ac8a2006-07-04 07:11:10 +00002075 // If this is a top-level #elif, inform the MIOpt.
2076 if (CurLexer->getConditionalStackDepth() == 0)
2077 CurLexer->MIOpt.FoundTopLevelElse();
2078
Chris Lattner22eb9722006-06-18 05:43:12 +00002079 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002080 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002081
2082 // Finally, skip the rest of the contents of this block and return the first
2083 // token after it.
2084 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2085 /*FoundElse*/CI.FoundElse);
2086}
Chris Lattnerb8761832006-06-24 21:31:03 +00002087