blob: e99f34e0c76147e63e34f9ab26c1c2c5b97882e2 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner22eb9722006-06-18 05:43:12 +000016// -d[MDNI] - Dump various things.
17// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000029#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000030#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000031#include "clang/Lex/PPCallbacks.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000032#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000033#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000034#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000037#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000038#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000039#include <iostream>
40using namespace llvm;
41using namespace clang;
42
43//===----------------------------------------------------------------------===//
44
Chris Lattner02dffbd2006-10-14 07:50:21 +000045Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000046 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000047 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000048 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
49 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000050 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000051 ScratchBuf = new ScratchBuffer(SourceMgr);
52
Chris Lattner22eb9722006-06-18 05:43:12 +000053 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000054 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000055 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000056 NumEnteredSourceFiles = 0;
57 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000058 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000059 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000061
62 // Default to discarding comments.
63 KeepComments = false;
64 KeepMacroComments = false;
65
Chris Lattner22eb9722006-06-18 05:43:12 +000066 // Macro expansion is enabled.
67 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000068 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000069
Chris Lattner8ff71992006-07-06 05:17:39 +000070 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
71 // This gets unpoisoned where it is allowed.
72 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
73
Chris Lattnerb8761832006-06-24 21:31:03 +000074 // Initialize the pragma handlers.
75 PragmaHandlers = new PragmaNamespace(0);
76 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000077
78 // Initialize builtin macros like __LINE__ and friends.
79 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000080}
81
82Preprocessor::~Preprocessor() {
83 // Free any active lexers.
84 delete CurLexer;
85
Chris Lattner69772b02006-07-02 20:34:39 +000086 while (!IncludeMacroStack.empty()) {
87 delete IncludeMacroStack.back().TheLexer;
88 delete IncludeMacroStack.back().TheMacroExpander;
89 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000090 }
Chris Lattnerb8761832006-06-24 21:31:03 +000091
92 // Release pragma information.
93 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000094
95 // Delete the scratch buffer info.
96 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000097}
98
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000099PPCallbacks::~PPCallbacks() {
100}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000101
Chris Lattner22eb9722006-06-18 05:43:12 +0000102/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
103/// the specified LexerToken's location, translating the token's start
104/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000105void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000106 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000107 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000108}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000109
110void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
111 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
112 << getSpelling(Tok) << "'";
113
114 if (!DumpFlags) return;
115 std::cerr << "\t";
116 if (Tok.isAtStartOfLine())
117 std::cerr << " [StartOfLine]";
118 if (Tok.hasLeadingSpace())
119 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000120 if (Tok.isExpandDisabled())
121 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000122 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000123 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000124 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
125 << "']";
126 }
127}
128
129void Preprocessor::DumpMacro(const MacroInfo &MI) const {
130 std::cerr << "MACRO: ";
131 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
132 DumpToken(MI.getReplacementToken(i));
133 std::cerr << " ";
134 }
135 std::cerr << "\n";
136}
137
Chris Lattner22eb9722006-06-18 05:43:12 +0000138void Preprocessor::PrintStats() {
139 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000140 std::cerr << NumDirectives << " directives found:\n";
141 std::cerr << " " << NumDefined << " #define.\n";
142 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000143 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000144 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
145 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
146 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
147 std::cerr << " " << NumElse << " #else/#elif.\n";
148 std::cerr << " " << NumEndif << " #endif.\n";
149 std::cerr << " " << NumPragma << " #pragma.\n";
150 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
151
Chris Lattner78186052006-07-09 00:45:31 +0000152 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
153 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000154 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000155 std::cerr << (NumFastTokenPaste+NumTokenPaste)
156 << " token paste (##) operations performed, "
157 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000158}
159
160//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000161// Token Spelling
162//===----------------------------------------------------------------------===//
163
164
165/// getSpelling() - Return the 'spelling' of this token. The spelling of a
166/// token are the characters used to represent the token in the source file
167/// after trigraph expansion and escaped-newline folding. In particular, this
168/// wants to get the true, uncanonicalized, spelling of things like digraphs
169/// UCNs, etc.
170std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
171 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
172
173 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000174 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000175 if (!Tok.needsCleaning())
176 return std::string(TokStart, TokStart+Tok.getLength());
177
Chris Lattnerd01e2912006-06-18 16:22:51 +0000178 std::string Result;
179 Result.reserve(Tok.getLength());
180
Chris Lattneref9eae12006-07-04 22:33:12 +0000181 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000182 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
183 Ptr != End; ) {
184 unsigned CharSize;
185 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
186 Ptr += CharSize;
187 }
188 assert(Result.size() != unsigned(Tok.getLength()) &&
189 "NeedsCleaning flag set on something that didn't need cleaning!");
190 return Result;
191}
192
193/// getSpelling - This method is used to get the spelling of a token into a
194/// preallocated buffer, instead of as an std::string. The caller is required
195/// to allocate enough space for the token, which is guaranteed to be at least
196/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000197///
198/// Note that this method may do two possible things: it may either fill in
199/// the buffer specified with characters, or it may *change the input pointer*
200/// to point to a constant buffer with the data already in it (avoiding a
201/// copy). The caller is not allowed to modify the returned buffer pointer
202/// if an internal buffer is returned.
203unsigned Preprocessor::getSpelling(const LexerToken &Tok,
204 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000205 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
206
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000207 // If this token is an identifier, just return the string from the identifier
208 // table, which is very quick.
209 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
210 Buffer = II->getName();
211 return Tok.getLength();
212 }
213
214 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000215 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000216
217 // If this token contains nothing interesting, return it directly.
218 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000219 Buffer = TokStart;
220 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 }
222 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000223 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
225 Ptr != End; ) {
226 unsigned CharSize;
227 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
228 Ptr += CharSize;
229 }
230 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
231 "NeedsCleaning flag set on something that didn't need cleaning!");
232
233 return OutBuf-Buffer;
234}
235
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000236
237/// CreateString - Plop the specified string into a scratch buffer and return a
238/// location for it. If specified, the source location provides a source
239/// location for the token.
240SourceLocation Preprocessor::
241CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
242 if (SLoc.isValid())
243 return ScratchBuf->getToken(Buf, Len, SLoc);
244 return ScratchBuf->getToken(Buf, Len);
245}
246
247
Chris Lattnerd01e2912006-06-18 16:22:51 +0000248//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000249// Source File Location Methods.
250//===----------------------------------------------------------------------===//
251
Chris Lattner22eb9722006-06-18 05:43:12 +0000252/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
253/// return null on failure. isAngled indicates whether the file reference is
254/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000255const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
256 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000257 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000258 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000259 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000260 // If the header lookup mechanism may be relative to the current file, pass in
261 // info about where the current file is.
262 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000263 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000264 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000265 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000266 }
267
Chris Lattner63dd32b2006-10-20 04:42:40 +0000268 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000269 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000270 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000271 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
272 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000273 if (FE) return FE;
274
275 // Otherwise, see if this is a subframework header. If so, this is relative
276 // to one of the headers on the #include stack. Walk the list of the current
277 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000278 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000279 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000280 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
281 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000282 return FE;
283 }
284
285 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
286 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000287 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000288 CurFileEnt =
289 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000290 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
291 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000292 return FE;
293 }
294 }
295
296 // Otherwise, we really couldn't find the file.
297 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000298}
299
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000300/// isInPrimaryFile - Return true if we're in the top-level file, not in a
301/// #include.
302bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000303 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000304 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000305
Chris Lattner13044d92006-07-03 05:16:44 +0000306 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000307 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000308 if (IncludeMacroStack[i].TheLexer &&
309 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
310 return IncludeMacroStack[i].TheLexer->isMainFile();
311 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000312}
313
314/// getCurrentLexer - Return the current file lexer being lexed from. Note
315/// that this ignores any potentially active macro expansions and _Pragma
316/// expansions going on at the time.
317Lexer *Preprocessor::getCurrentFileLexer() const {
318 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
319
320 // Look for a stacked lexer.
321 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000322 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000323 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
324 return L;
325 }
326 return 0;
327}
328
329
Chris Lattner22eb9722006-06-18 05:43:12 +0000330/// EnterSourceFile - Add a source file to the top of the include stack and
331/// start lexing tokens from it instead of the current buffer. Return true
332/// on failure.
333void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000334 const DirectoryLookup *CurDir,
335 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000336 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000337 ++NumEnteredSourceFiles;
338
Chris Lattner69772b02006-07-02 20:34:39 +0000339 if (MaxIncludeStackDepth < IncludeMacroStack.size())
340 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000341
Chris Lattner22eb9722006-06-18 05:43:12 +0000342 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000343 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000344 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000345 EnterSourceFileWithLexer(TheLexer, CurDir);
346}
Chris Lattner22eb9722006-06-18 05:43:12 +0000347
Chris Lattner69772b02006-07-02 20:34:39 +0000348/// EnterSourceFile - Add a source file to the top of the include stack and
349/// start lexing tokens from it instead of the current buffer.
350void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
351 const DirectoryLookup *CurDir) {
352
353 // Add the current lexer to the include stack.
354 if (CurLexer || CurMacroExpander)
355 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
356 CurMacroExpander));
357
358 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000359 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000360 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000361
362 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000363 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000364 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
365
366 // Get the file entry for the current file.
367 if (const FileEntry *FE =
368 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000369 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000370
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000371 Callbacks->FileChanged(SourceLocation(CurLexer->getCurFileID(), 0),
372 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000373 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000374}
375
Chris Lattner69772b02006-07-02 20:34:39 +0000376
377
Chris Lattner22eb9722006-06-18 05:43:12 +0000378/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000379/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000380void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000381 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
382 CurMacroExpander));
383 CurLexer = 0;
384 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000385
Chris Lattneree8760b2006-07-15 07:42:55 +0000386 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000387}
388
Chris Lattner7667d0d2006-07-16 18:16:58 +0000389/// EnterTokenStream - Add a "macro" context to the top of the include stack,
390/// which will cause the lexer to start returning the specified tokens. Note
391/// that these tokens will be re-macro-expanded when/if expansion is enabled.
392/// This method assumes that the specified stream of tokens has a permanent
393/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000394void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000395 // Save our current state.
396 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
397 CurMacroExpander));
398 CurLexer = 0;
399 CurDirLookup = 0;
400
401 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000402 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000403}
404
405/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
406/// lexer stack. This should only be used in situations where the current
407/// state of the top-of-stack lexer is known.
408void Preprocessor::RemoveTopOfLexerStack() {
409 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
410 delete CurLexer;
411 delete CurMacroExpander;
412 CurLexer = IncludeMacroStack.back().TheLexer;
413 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
414 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
415 IncludeMacroStack.pop_back();
416}
417
Chris Lattner22eb9722006-06-18 05:43:12 +0000418//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000419// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000420//===----------------------------------------------------------------------===//
421
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000422/// RegisterBuiltinMacro - Register the specified identifier in the identifier
423/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000424IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000425 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000426 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000427
428 // Mark it as being a macro that is builtin.
429 MacroInfo *MI = new MacroInfo(SourceLocation());
430 MI->setIsBuiltinMacro();
431 Id->setMacroInfo(MI);
432 return Id;
433}
434
435
Chris Lattner677757a2006-06-28 05:26:32 +0000436/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
437/// identifier table.
438void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000439 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000440 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000441 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
442 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000443 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000444
445 // GCC Extensions.
446 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
447 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000448 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000449}
450
Chris Lattnerc2395832006-07-09 00:57:04 +0000451/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
452/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000453static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
454 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000455 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
456
457 // If the token isn't an identifier, it's always literally expanded.
458 if (II == 0) return true;
459
460 // If the identifier is a macro, and if that macro is enabled, it may be
461 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000462 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
463 // Fast expanding "#define X X" is ok, because X would be disabled.
464 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000465 return false;
466
467 // If this is an object-like macro invocation, it is safe to trivially expand
468 // it.
469 if (MI->isObjectLike()) return true;
470
471 // If this is a function-like macro invocation, it's safe to trivially expand
472 // as long as the identifier is not a macro argument.
473 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
474 I != E; ++I)
475 if (*I == II)
476 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000477
Chris Lattnerc2395832006-07-09 00:57:04 +0000478 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000479}
480
Chris Lattnerc2395832006-07-09 00:57:04 +0000481
Chris Lattnerafe603f2006-07-11 04:02:46 +0000482/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
483/// lexed is a '('. If so, consume the token and return true, if not, this
484/// method should have no observable side-effect on the lexed tokens.
485bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000486 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000487 unsigned Val;
488 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000489 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000490 else
491 Val = CurMacroExpander->isNextTokenLParen();
492
493 if (Val == 2) {
494 // If we ran off the end of the lexer or macro expander, walk the include
495 // stack, looking for whatever will return the next token.
496 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
497 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
498 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000499 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000500 else
501 Val = Entry.TheMacroExpander->isNextTokenLParen();
502 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000503 }
504
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000505 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
506 // have found something that isn't a '(' or we found the end of the
507 // translation unit. In either case, return false.
508 if (Val != 1)
509 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000510
511 LexerToken Tok;
512 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000513 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
514 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000515}
Chris Lattner677757a2006-06-28 05:26:32 +0000516
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000517/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
518/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000519bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000520 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000521
522 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
523 if (MI->isBuiltinMacro()) {
524 ExpandBuiltinMacro(Identifier);
525 return false;
526 }
527
Chris Lattner81278c62006-10-14 19:03:49 +0000528 // If this is the first use of a target-specific macro, warn about it.
529 if (MI->isTargetSpecific()) {
530 MI->setIsTargetSpecific(false); // Don't warn on second use.
531 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
532 diag::port_target_macro_use);
533 }
534
Chris Lattneree8760b2006-07-15 07:42:55 +0000535 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000536 /// for each macro argument, the list of tokens that were provided to the
537 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000538 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000539
540 // If this is a function-like macro, read the arguments.
541 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000542 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
543 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000544 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000545 return true;
546
Chris Lattner78186052006-07-09 00:45:31 +0000547 // Remember that we are now parsing the arguments to a macro invocation.
548 // Preprocessor directives used inside macro arguments are not portable, and
549 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000550 InMacroArgs = true;
551 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000552
553 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000554 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000555
556 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000557 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000558
559 ++NumFnMacroExpanded;
560 } else {
561 ++NumMacroExpanded;
562 }
Chris Lattner13044d92006-07-03 05:16:44 +0000563
564 // Notice that this macro has been used.
565 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000566
567 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000568
569 // If this macro expands to no tokens, don't bother to push it onto the
570 // expansion stack, only to take it right back off.
571 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000572 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000573 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000574
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000575 // Ignore this macro use, just return the next token in the current
576 // buffer.
577 bool HadLeadingSpace = Identifier.hasLeadingSpace();
578 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
579
580 Lex(Identifier);
581
582 // If the identifier isn't on some OTHER line, inherit the leading
583 // whitespace/first-on-a-line property of this token. This handles
584 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
585 // empty.
586 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000587 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
588 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000589 }
590 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000591 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000592
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000593 } else if (MI->getNumTokens() == 1 &&
594 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000595 // Otherwise, if this macro expands into a single trivially-expanded
596 // token: expand it now. This handles common cases like
597 // "#define VAL 42".
598
599 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
600 // identifier to the expanded token.
601 bool isAtStartOfLine = Identifier.isAtStartOfLine();
602 bool hasLeadingSpace = Identifier.hasLeadingSpace();
603
604 // Remember where the token is instantiated.
605 SourceLocation InstantiateLoc = Identifier.getLocation();
606
607 // Replace the result token.
608 Identifier = MI->getReplacementToken(0);
609
610 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000611 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
612 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000613
614 // Update the tokens location to include both its logical and physical
615 // locations.
616 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000617 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000618 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000619
Chris Lattner6e4bf522006-07-27 06:59:25 +0000620 // If this is #define X X, we must mark the result as unexpandible.
621 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
622 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000623 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000624
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000625 // Since this is not an identifier token, it can't be macro expanded, so
626 // we're done.
627 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000628 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000629 }
630
Chris Lattner78186052006-07-09 00:45:31 +0000631 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000632 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000633
634 // Now that the macro is at the top of the include stack, ask the
635 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000636 Lex(Identifier);
637 return false;
638}
639
Chris Lattneree8760b2006-07-15 07:42:55 +0000640/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000641/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000642/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000643MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
644 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000645 // The number of fixed arguments to parse.
646 unsigned NumFixedArgsLeft = MI->getNumArgs();
647 bool isVariadic = MI->isVariadic();
648
Chris Lattner78186052006-07-09 00:45:31 +0000649 // Outer loop, while there are more arguments, keep reading them.
650 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000651 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000652 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000653
654 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000655 // argument is separated by an EOF token. Use a SmallVector so we can avoid
656 // heap allocations in the common case.
657 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000658
659 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000660 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000661 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
662 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000663
Chris Lattner78186052006-07-09 00:45:31 +0000664 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000665 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
666 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000667 LexUnexpandedToken(Tok);
668
669 if (Tok.getKind() == tok::eof) {
670 Diag(MacroName, diag::err_unterm_macro_invoc);
671 // Do not lose the EOF. Return it to the client.
672 MacroName = Tok;
673 return 0;
674 } else if (Tok.getKind() == tok::r_paren) {
675 // If we found the ) token, the macro arg list is done.
676 if (NumParens-- == 0)
677 break;
678 } else if (Tok.getKind() == tok::l_paren) {
679 ++NumParens;
680 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
681 // Comma ends this argument if there are more fixed arguments expected.
682 if (NumFixedArgsLeft)
683 break;
684
Chris Lattner2ada5d32006-07-15 07:51:24 +0000685 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000686 if (!isVariadic) {
687 // Emit the diagnostic at the macro name in case there is a missing ).
688 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000689 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000690 return 0;
691 }
692 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000693 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000694 // If this is a comment token in the argument list and we're just in
695 // -C mode (not -CC mode), discard the comment.
696 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000697 }
698
699 ArgTokens.push_back(Tok);
700 }
701
Chris Lattnera12dd152006-07-11 04:09:02 +0000702 // Empty arguments are standard in C99 and supported as an extension in
703 // other modes.
704 if (ArgTokens.empty() && !Features.C99)
705 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000706
Chris Lattner36b6e812006-07-21 06:38:30 +0000707 // Add a marker EOF token to the end of the token list for this argument.
708 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000709 EOFTok.startToken();
710 EOFTok.setKind(tok::eof);
711 EOFTok.setLocation(Tok.getLocation());
712 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000713 ArgTokens.push_back(EOFTok);
714 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000715 --NumFixedArgsLeft;
716 };
717
718 // Okay, we either found the r_paren. Check to see if we parsed too few
719 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000720 unsigned MinArgsExpected = MI->getNumArgs();
721
Chris Lattner775d8322006-07-29 04:39:41 +0000722 // See MacroArgs instance var for description of this.
723 bool isVarargsElided = false;
724
Chris Lattner2ada5d32006-07-15 07:51:24 +0000725 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000726 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000727 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000728 // Varargs where the named vararg parameter is missing: ok as extension.
729 // #define A(x, ...)
730 // A("blah")
731 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000732
733 // Remember this occurred if this is a C99 macro invocation with at least
734 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000735 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000736 } else if (MI->getNumArgs() == 1) {
737 // #define A(x)
738 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000739 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000740
741 // Empty arguments are standard in C99 and supported as an extension in
742 // other modes.
743 if (ArgTokens.empty() && !Features.C99)
744 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000745 } else {
746 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000747 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000748 return 0;
749 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000750
751 // Add a marker EOF token to the end of the token list for this argument.
752 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000753 Tok.startToken();
754 Tok.setKind(tok::eof);
755 Tok.setLocation(EndLoc);
756 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000757 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000758 }
759
Chris Lattner775d8322006-07-29 04:39:41 +0000760 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000761}
762
Chris Lattnerc673f902006-06-30 06:10:41 +0000763/// ComputeDATE_TIME - Compute the current time, enter it into the specified
764/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
765/// the identifier tokens inserted.
766static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000767 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000768 time_t TT = time(0);
769 struct tm *TM = localtime(&TT);
770
771 static const char * const Months[] = {
772 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
773 };
774
775 char TmpBuffer[100];
776 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
777 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000778 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000779
780 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000781 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000782}
783
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000784/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
785/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000786void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000787 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000788 IdentifierInfo *II = Tok.getIdentifierInfo();
789 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000790
791 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
792 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000793 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000794 return Handle_Pragma(Tok);
795
Chris Lattner78186052006-07-09 00:45:31 +0000796 ++NumBuiltinMacroExpanded;
797
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000798 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000799
800 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000801 Tok.setIdentifierInfo(0);
802 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000803
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000804 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000805 // __LINE__ expands to a simple numeric value.
806 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
807 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000808 Tok.setKind(tok::numeric_constant);
809 Tok.setLength(Length);
810 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000811 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000812 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000813 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000814 Diag(Tok, diag::ext_pp_base_file);
815 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
816 while (NextLoc.getFileID() != 0) {
817 Loc = NextLoc;
818 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
819 }
820 }
821
Chris Lattner0766e592006-07-03 01:07:01 +0000822 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
823 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000824 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000825 Tok.setKind(tok::string_literal);
826 Tok.setLength(FN.size());
827 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000828 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000829 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000830 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000831 Tok.setKind(tok::string_literal);
832 Tok.setLength(strlen("\"Mmm dd yyyy\""));
833 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000834 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000835 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000836 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000837 Tok.setKind(tok::string_literal);
838 Tok.setLength(strlen("\"hh:mm:ss\""));
839 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000840 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000841 Diag(Tok, diag::ext_pp_include_level);
842
843 // Compute the include depth of this token.
844 unsigned Depth = 0;
845 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
846 for (; Loc.getFileID() != 0; ++Depth)
847 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
848
849 // __INCLUDE_LEVEL__ expands to a simple numeric value.
850 sprintf(TmpBuffer, "%u", Depth);
851 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000852 Tok.setKind(tok::numeric_constant);
853 Tok.setLength(Length);
854 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000855 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000856 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
857 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
858 Diag(Tok, diag::ext_pp_timestamp);
859
860 // Get the file that we are lexing out of. If we're currently lexing from
861 // a macro, dig into the include stack.
862 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000863 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000864
865 if (TheLexer)
866 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
867
868 // If this file is older than the file it depends on, emit a diagnostic.
869 const char *Result;
870 if (CurFile) {
871 time_t TT = CurFile->getModificationTime();
872 struct tm *TM = localtime(&TT);
873 Result = asctime(TM);
874 } else {
875 Result = "??? ??? ?? ??:??:?? ????\n";
876 }
877 TmpBuffer[0] = '"';
878 strcpy(TmpBuffer+1, Result);
879 unsigned Len = strlen(TmpBuffer);
880 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000881 Tok.setKind(tok::string_literal);
882 Tok.setLength(Len);
883 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000884 } else {
885 assert(0 && "Unknown identifier!");
886 }
887}
Chris Lattner677757a2006-06-28 05:26:32 +0000888
Chris Lattner13044d92006-07-03 05:16:44 +0000889namespace {
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000890struct UnusedIdentifierReporter : public CStringMapVisitor {
Chris Lattner13044d92006-07-03 05:16:44 +0000891 Preprocessor &PP;
892 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
893
Chris Lattner2b9e19b2006-10-29 23:43:13 +0000894 void Visit(const char *Key, void *Value) const {
895 IdentifierInfo &II = *static_cast<IdentifierInfo*>(Value);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000896 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
897 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000898 }
899};
900}
901
Chris Lattner677757a2006-06-28 05:26:32 +0000902//===----------------------------------------------------------------------===//
903// Lexer Event Handling.
904//===----------------------------------------------------------------------===//
905
Chris Lattnercefc7682006-07-08 08:28:12 +0000906/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
907/// identifier information for the token and install it into the token.
908IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
909 const char *BufPtr) {
910 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
911 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
912
913 // Look up this token, see if it is a macro, or if it is a language keyword.
914 IdentifierInfo *II;
915 if (BufPtr && !Identifier.needsCleaning()) {
916 // No cleaning needed, just use the characters from the lexed buffer.
917 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
918 } else {
919 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
920 const char *TmpBuf = (char*)alloca(Identifier.getLength());
921 unsigned Size = getSpelling(Identifier, TmpBuf);
922 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
923 }
Chris Lattner8c204872006-10-14 05:19:21 +0000924 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000925 return II;
926}
927
928
Chris Lattner677757a2006-06-28 05:26:32 +0000929/// HandleIdentifier - This callback is invoked when the lexer reads an
930/// identifier. This callback looks up the identifier in the map and/or
931/// potentially macro expands it or turns it into a named token (like 'for').
932void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000933 assert(Identifier.getIdentifierInfo() &&
934 "Can't handle identifiers without identifier info!");
935
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000936 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000937
938 // If this identifier was poisoned, and if it was not produced from a macro
939 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000940 if (II.isPoisoned() && CurLexer) {
941 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
942 Diag(Identifier, diag::err_pp_used_poisoned_id);
943 else
944 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
945 }
Chris Lattner677757a2006-06-28 05:26:32 +0000946
Chris Lattner78186052006-07-09 00:45:31 +0000947 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000948 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000949 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
950 if (MI->isEnabled()) {
951 if (!HandleMacroExpandedIdentifier(Identifier, MI))
952 return;
953 } else {
954 // C99 6.10.3.4p2 says that a disabled macro may never again be
955 // expanded, even if it's in a context where it could be expanded in the
956 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000957 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000958 }
959 }
Chris Lattner063400e2006-10-14 19:54:15 +0000960 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
961 // If this identifier is a macro on some other target, emit a diagnostic.
962 // This diagnosic is only emitted when macro expansion is enabled, because
963 // the macro would not have been expanded for the other target either.
964 II.setIsOtherTargetMacro(false); // Don't warn on second use.
965 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
966 diag::port_target_macro_use);
967
968 }
Chris Lattner677757a2006-06-28 05:26:32 +0000969
Chris Lattner5b9f4892006-11-21 17:23:33 +0000970 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
971 // then we act as if it is the actual operator and not the textual
972 // representation of it.
973 if (II.isCPlusPlusOperatorKeyword())
974 Identifier.setIdentifierInfo(0);
975
Chris Lattner677757a2006-06-28 05:26:32 +0000976 // Change the kind of this identifier to the appropriate token kind, e.g.
977 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000978 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000979
980 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000981 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000982}
983
Chris Lattner22eb9722006-06-18 05:43:12 +0000984/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
985/// the current file. This either returns the EOF token or pops a level off
986/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000987bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000988 assert(!CurMacroExpander &&
989 "Ending a file when currently in a macro!");
990
Chris Lattner371ac8a2006-07-04 07:11:10 +0000991 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000992 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000993 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000994 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000995 // Okay, this has a controlling macro, remember in PerFileInfo.
996 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000997 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
998 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000999 }
1000 }
1001
Chris Lattner22eb9722006-06-18 05:43:12 +00001002 // If this is a #include'd file, pop it off the include stack and continue
1003 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001004 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001005 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001006 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001007
1008 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001009 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001010 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1011
1012 // Get the file entry for the current file.
1013 if (const FileEntry *FE =
1014 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001015 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001016
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001017 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1018 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001019 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001020
1021 // Client should lex another token.
1022 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001023 }
1024
Chris Lattner8c204872006-10-14 05:19:21 +00001025 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001026 CurLexer->BufferPtr = CurLexer->BufferEnd;
1027 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001028 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001029
1030 // We're done with the #included file.
1031 delete CurLexer;
1032 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001033
Chris Lattner03f83482006-07-10 06:16:26 +00001034 // This is the end of the top-level file. If the diag::pp_macro_not_used
1035 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1036 // have not been used.
1037 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1038 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001039
1040 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001041}
1042
1043/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001044/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001045bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001046 assert(CurMacroExpander && !CurLexer &&
1047 "Ending a macro when currently in a #include file!");
1048
Chris Lattner22eb9722006-06-18 05:43:12 +00001049 delete CurMacroExpander;
1050
Chris Lattner69772b02006-07-02 20:34:39 +00001051 // Handle this like a #include file being popped off the stack.
1052 CurMacroExpander = 0;
1053 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001054}
1055
1056
1057//===----------------------------------------------------------------------===//
1058// Utility Methods for Preprocessor Directive Handling.
1059//===----------------------------------------------------------------------===//
1060
1061/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1062/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001063void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001064 LexerToken Tmp;
1065 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001066 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001067 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001068}
1069
Chris Lattner652c1692006-11-21 23:47:30 +00001070/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1071static bool isCXXNamedOperator(const std::string &Spelling) {
1072 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1073 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1074 Spelling == "or" || Spelling == "xor";
1075}
1076
Chris Lattner22eb9722006-06-18 05:43:12 +00001077/// ReadMacroName - Lex and validate a macro name, which occurs after a
1078/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001079/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1080/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001081/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001082void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001083 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001084 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001085
1086 // Missing macro name?
1087 if (MacroNameTok.getKind() == tok::eom)
1088 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1089
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001090 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1091 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001092 std::string Spelling = getSpelling(MacroNameTok);
1093 if (isCXXNamedOperator(Spelling))
1094 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1095 // except for their spellings.
1096 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1097 else
1098 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001099 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001100 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001101 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001102 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001103 } else if (isDefineUndef && II->getMacroInfo() &&
1104 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001105 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001106 if (isDefineUndef == 1)
1107 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1108 else
1109 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001110 } else {
1111 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001112 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001113 }
1114
Chris Lattner22eb9722006-06-18 05:43:12 +00001115 // Invalid macro name, read and discard the rest of the line. Then set the
1116 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001117 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001118 return DiscardUntilEndOfDirective();
1119}
1120
1121/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1122/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001123void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001124 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001125 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001126 // There should be no tokens after the directive, but we allow them as an
1127 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001128 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1129 Lex(Tmp);
1130
Chris Lattner22eb9722006-06-18 05:43:12 +00001131 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001132 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1133 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001134 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001135}
1136
1137
1138
1139/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1140/// decided that the subsequent tokens are in the #if'd out portion of the
1141/// file. Lex the rest of the file, until we see an #endif. If
1142/// FoundNonSkipPortion is true, then we have already emitted code for part of
1143/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1144/// is true, then #else directives are ok, if not, then we have already seen one
1145/// so a #else directive is a duplicate. When this returns, the caller can lex
1146/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001147void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001148 bool FoundNonSkipPortion,
1149 bool FoundElse) {
1150 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001151 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 "Lexing a macro, not a file?");
1153
1154 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1155 FoundNonSkipPortion, FoundElse);
1156
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001157 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1158 // disabling warnings, etc.
1159 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001160 LexerToken Tok;
1161 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001162 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001163
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001164 // If this is the end of the buffer, we have an error.
1165 if (Tok.getKind() == tok::eof) {
1166 // Emit errors for each unterminated conditional on the stack, including
1167 // the current one.
1168 while (!CurLexer->ConditionalStack.empty()) {
1169 Diag(CurLexer->ConditionalStack.back().IfLoc,
1170 diag::err_pp_unterminated_conditional);
1171 CurLexer->ConditionalStack.pop_back();
1172 }
1173
1174 // Just return and let the caller lex after this #include.
1175 break;
1176 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001177
1178 // If this token is not a preprocessor directive, just skip it.
1179 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1180 continue;
1181
1182 // We just parsed a # character at the start of a line, so we're in
1183 // directive mode. Tell the lexer this so any newlines we see will be
1184 // converted into an EOM token (this terminates the macro).
1185 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001186 CurLexer->KeepCommentMode = false;
1187
Chris Lattner22eb9722006-06-18 05:43:12 +00001188
1189 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001190 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001191
1192 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1193 // something bogus), skip it.
1194 if (Tok.getKind() != tok::identifier) {
1195 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001196 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001197 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001198 continue;
1199 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001200
Chris Lattner22eb9722006-06-18 05:43:12 +00001201 // If the first letter isn't i or e, it isn't intesting to us. We know that
1202 // this is safe in the face of spelling differences, because there is no way
1203 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001204 // allows us to avoid looking up the identifier info for #define/#undef and
1205 // other common directives.
1206 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1207 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001208 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1209 FirstChar != 'i' && FirstChar != 'e') {
1210 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001211 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001212 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001213 continue;
1214 }
1215
Chris Lattnere60165f2006-06-22 06:36:29 +00001216 // Get the identifier name without trigraphs or embedded newlines. Note
1217 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1218 // when skipping.
1219 // TODO: could do this with zero copies in the no-clean case by using
1220 // strncmp below.
1221 char Directive[20];
1222 unsigned IdLen;
1223 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1224 IdLen = Tok.getLength();
1225 memcpy(Directive, RawCharData, IdLen);
1226 Directive[IdLen] = 0;
1227 } else {
1228 std::string DirectiveStr = getSpelling(Tok);
1229 IdLen = DirectiveStr.size();
1230 if (IdLen >= 20) {
1231 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001232 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001233 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001234 continue;
1235 }
1236 memcpy(Directive, &DirectiveStr[0], IdLen);
1237 Directive[IdLen] = 0;
1238 }
1239
Chris Lattner22eb9722006-06-18 05:43:12 +00001240 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001241 if ((IdLen == 2) || // "if"
1242 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1243 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001244 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1245 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001246 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001247 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001248 /*foundnonskip*/false,
1249 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001250 }
1251 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001252 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001253 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001254 PPConditionalInfo CondInfo;
1255 CondInfo.WasSkipping = true; // Silence bogus warning.
1256 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001257 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001258 assert(!InCond && "Can't be skipping if not in a conditional!");
1259
1260 // If we popped the outermost skipping block, we're done skipping!
1261 if (!CondInfo.WasSkipping)
1262 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001263 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001264 // #else directive in a skipping conditional. If not in some other
1265 // skipping conditional, and if #else hasn't already been seen, enter it
1266 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001267 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001268 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1269
1270 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001271 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001272
1273 // Note that we've seen a #else in this conditional.
1274 CondInfo.FoundElse = true;
1275
1276 // If the conditional is at the top level, and the #if block wasn't
1277 // entered, enter the #else block now.
1278 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1279 CondInfo.FoundNonSkip = true;
1280 break;
1281 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001282 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001283 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1284
1285 bool ShouldEnter;
1286 // If this is in a skipping block or if we're already handled this #if
1287 // block, don't bother parsing the condition.
1288 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001289 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001290 ShouldEnter = false;
1291 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001292 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001293 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001294 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1295 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001296 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001297 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001298 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001299 }
1300
1301 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001302 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001303
1304 // If this condition is true, enter it!
1305 if (ShouldEnter) {
1306 CondInfo.FoundNonSkip = true;
1307 break;
1308 }
1309 }
1310 }
1311
1312 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001313 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001314 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001315 }
1316
1317 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1318 // of the file, just stop skipping and return to lexing whatever came after
1319 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001320 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001321}
1322
1323//===----------------------------------------------------------------------===//
1324// Preprocessor Directive Handling.
1325//===----------------------------------------------------------------------===//
1326
1327/// HandleDirective - This callback is invoked when the lexer sees a # token
1328/// at the start of a line. This consumes the directive, modifies the
1329/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1330/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001331void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001332 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001333
1334 // We just parsed a # character at the start of a line, so we're in directive
1335 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001336 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001337 CurLexer->ParsingPreprocessorDirective = true;
1338
1339 ++NumDirectives;
1340
Chris Lattner371ac8a2006-07-04 07:11:10 +00001341 // We are about to read a token. For the multiple-include optimization FA to
1342 // work, we have to remember if we had read any tokens *before* this
1343 // pp-directive.
1344 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1345
Chris Lattner78186052006-07-09 00:45:31 +00001346 // Read the next token, the directive flavor. This isn't expanded due to
1347 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001348 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001349
Chris Lattner78186052006-07-09 00:45:31 +00001350 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1351 // #define A(x) #x
1352 // A(abc
1353 // #warning blah
1354 // def)
1355 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001356 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001357 Diag(Result, diag::ext_embedded_directive);
1358
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001359TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001360 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001361 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001362 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001363 case tok::comment:
1364 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1365 LexUnexpandedToken(Result);
1366 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001367
Chris Lattner22eb9722006-06-18 05:43:12 +00001368 case tok::numeric_constant:
1369 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001370 DiscardUntilEndOfDirective();
1371 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001372 default:
1373 IdentifierInfo *II = Result.getIdentifierInfo();
1374 if (II == 0) break; // Not an identifier.
1375
1376 // Ask what the preprocessor keyword ID is.
1377 switch (II->getPPKeywordID()) {
1378 default: break;
1379 // C99 6.10.1 - Conditional Inclusion.
1380 case tok::pp_if:
1381 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1382 case tok::pp_ifdef:
1383 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1384 case tok::pp_ifndef:
1385 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1386 case tok::pp_elif:
1387 return HandleElifDirective(Result);
1388 case tok::pp_else:
1389 return HandleElseDirective(Result);
1390 case tok::pp_endif:
1391 return HandleEndifDirective(Result);
1392
1393 // C99 6.10.2 - Source File Inclusion.
1394 case tok::pp_include:
1395 return HandleIncludeDirective(Result); // Handle #include.
1396
1397 // C99 6.10.3 - Macro Replacement.
1398 case tok::pp_define:
1399 return HandleDefineDirective(Result, false);
1400 case tok::pp_undef:
1401 return HandleUndefDirective(Result);
1402
1403 // C99 6.10.4 - Line Control.
1404 case tok::pp_line:
1405 // FIXME: implement #line
1406 DiscardUntilEndOfDirective();
1407 return;
1408
1409 // C99 6.10.5 - Error Directive.
1410 case tok::pp_error:
1411 return HandleUserDiagnosticDirective(Result, false);
1412
1413 // C99 6.10.6 - Pragma Directive.
1414 case tok::pp_pragma:
1415 return HandlePragmaDirective();
1416
1417 // GNU Extensions.
1418 case tok::pp_import:
1419 return HandleImportDirective(Result);
1420 case tok::pp_include_next:
1421 return HandleIncludeNextDirective(Result);
1422
1423 case tok::pp_warning:
1424 Diag(Result, diag::ext_pp_warning_directive);
1425 return HandleUserDiagnosticDirective(Result, true);
1426 case tok::pp_ident:
1427 return HandleIdentSCCSDirective(Result);
1428 case tok::pp_sccs:
1429 return HandleIdentSCCSDirective(Result);
1430 case tok::pp_assert:
1431 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001432 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001433 case tok::pp_unassert:
1434 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001435 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001436
1437 // clang extensions.
1438 case tok::pp_define_target:
1439 return HandleDefineDirective(Result, true);
1440 case tok::pp_define_other_target:
1441 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001442 }
1443 break;
1444 }
1445
1446 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001447 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001448
1449 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001450 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001451
1452 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001453}
1454
Chris Lattner01d66cc2006-07-03 22:16:27 +00001455void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001456 bool isWarning) {
1457 // Read the rest of the line raw. We do this because we don't want macros
1458 // to be expanded and we don't require that the tokens be valid preprocessing
1459 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1460 // collapse multiple consequtive white space between tokens, but this isn't
1461 // specified by the standard.
1462 std::string Message = CurLexer->ReadToEndOfLine();
1463
1464 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001465 return Diag(Tok, DiagID, Message);
1466}
1467
1468/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1469///
1470void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001471 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001472 Diag(Tok, diag::ext_pp_ident_directive);
1473
Chris Lattner371ac8a2006-07-04 07:11:10 +00001474 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001475 LexerToken StrTok;
1476 Lex(StrTok);
1477
1478 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001479 if (StrTok.getKind() != tok::string_literal &&
1480 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001481 return Diag(StrTok, diag::err_pp_malformed_ident);
1482
1483 // Verify that there is nothing after the string, other than EOM.
1484 CheckEndOfDirective("#ident");
1485
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001486 if (Callbacks)
1487 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001488}
1489
Chris Lattnerb8761832006-06-24 21:31:03 +00001490//===----------------------------------------------------------------------===//
1491// Preprocessor Include Directive Handling.
1492//===----------------------------------------------------------------------===//
1493
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001494/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1495/// checked and spelled filename, e.g. as an operand of #include. This returns
1496/// true if the input filename was in <>'s or false if it were in ""'s. The
1497/// caller is expected to provide a buffer that is large enough to hold the
1498/// spelling of the filename, but is also expected to handle the case when
1499/// this method decides to use a different buffer.
1500bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1501 const char *&BufStart,
1502 const char *&BufEnd) {
1503 // Get the text form of the filename.
1504 unsigned Len = getSpelling(FilenameTok, BufStart);
1505 BufEnd = BufStart+Len;
1506 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1507
1508 // Make sure the filename is <x> or "x".
1509 bool isAngled;
1510 if (BufStart[0] == '<') {
1511 if (BufEnd[-1] != '>') {
1512 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1513 BufStart = 0;
1514 return true;
1515 }
1516 isAngled = true;
1517 } else if (BufStart[0] == '"') {
1518 if (BufEnd[-1] != '"') {
1519 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1520 BufStart = 0;
1521 return true;
1522 }
1523 isAngled = false;
1524 } else {
1525 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1526 BufStart = 0;
1527 return true;
1528 }
1529
1530 // Diagnose #include "" as invalid.
1531 if (BufEnd-BufStart <= 2) {
1532 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1533 BufStart = 0;
1534 return "";
1535 }
1536
1537 // Skip the brackets.
1538 ++BufStart;
1539 --BufEnd;
1540 return isAngled;
1541}
1542
Chris Lattner22eb9722006-06-18 05:43:12 +00001543/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1544/// file to be included from the lexer, then include it! This is a common
1545/// routine with functionality shared between #include, #include_next and
1546/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001547void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001548 const DirectoryLookup *LookupFrom,
1549 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001550
Chris Lattner22eb9722006-06-18 05:43:12 +00001551 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001552 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001553
1554 // If the token kind is EOM, the error has already been diagnosed.
1555 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001556 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001557
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001558 // Reserve a buffer to get the spelling.
1559 SmallVector<char, 128> FilenameBuffer;
1560 FilenameBuffer.resize(FilenameTok.getLength());
1561
1562 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1563 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1564 FilenameStart, FilenameEnd);
1565 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1566 // error.
1567 if (FilenameStart == 0)
1568 return;
1569
Chris Lattner269c2322006-06-25 06:23:00 +00001570 // Verify that there is nothing after the filename, other than EOM. Use the
1571 // preprocessor to lex this in case lexing the filename entered a macro.
1572 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001573
1574 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001575 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001576 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1577
Chris Lattner22eb9722006-06-18 05:43:12 +00001578 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001579 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001580 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001581 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001582 if (File == 0)
1583 return Diag(FilenameTok, diag::err_pp_file_not_found);
1584
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001585 // Ask HeaderInfo if we should enter this #include file.
1586 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1587 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001588 return;
1589 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001590
1591 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001592 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001593 if (FileID == 0)
1594 return Diag(FilenameTok, diag::err_pp_file_not_found);
1595
1596 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001597 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001598}
1599
1600/// HandleIncludeNextDirective - Implements #include_next.
1601///
Chris Lattnercb283342006-06-18 06:48:37 +00001602void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1603 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001604
1605 // #include_next is like #include, except that we start searching after
1606 // the current found directory. If we can't do this, issue a
1607 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001608 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001609 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001610 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001611 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001612 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001613 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001614 } else {
1615 // Start looking up in the next directory.
1616 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001617 }
1618
1619 return HandleIncludeDirective(IncludeNextTok, Lookup);
1620}
1621
1622/// HandleImportDirective - Implements #import.
1623///
Chris Lattnercb283342006-06-18 06:48:37 +00001624void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1625 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001626
1627 return HandleIncludeDirective(ImportTok, 0, true);
1628}
1629
Chris Lattnerb8761832006-06-24 21:31:03 +00001630//===----------------------------------------------------------------------===//
1631// Preprocessor Macro Directive Handling.
1632//===----------------------------------------------------------------------===//
1633
Chris Lattnercefc7682006-07-08 08:28:12 +00001634/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1635/// definition has just been read. Lex the rest of the arguments and the
1636/// closing ), updating MI with what we learn. Return true if an error occurs
1637/// parsing the arg list.
1638bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1639 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001640 while (1) {
1641 LexUnexpandedToken(Tok);
1642 switch (Tok.getKind()) {
1643 case tok::r_paren:
1644 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001645 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001646 // Otherwise we have #define FOO(A,)
1647 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1648 return true;
1649 case tok::ellipsis: // #define X(... -> C99 varargs
1650 // Warn if use of C99 feature in non-C99 mode.
1651 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1652
1653 // Lex the token after the identifier.
1654 LexUnexpandedToken(Tok);
1655 if (Tok.getKind() != tok::r_paren) {
1656 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1657 return true;
1658 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001659 // Add the __VA_ARGS__ identifier as an argument.
1660 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001661 MI->setIsC99Varargs();
1662 return false;
1663 case tok::eom: // #define X(
1664 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1665 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001666 default:
1667 // Handle keywords and identifiers here to accept things like
1668 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001669 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001670 if (II == 0) {
1671 // #define X(1
1672 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1673 return true;
1674 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001675
1676 // If this is already used as an argument, it is used multiple times (e.g.
1677 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001678 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001679 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1680 return true;
1681 }
1682
1683 // Add the argument to the macro info.
1684 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001685
1686 // Lex the token after the identifier.
1687 LexUnexpandedToken(Tok);
1688
1689 switch (Tok.getKind()) {
1690 default: // #define X(A B
1691 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1692 return true;
1693 case tok::r_paren: // #define X(A)
1694 return false;
1695 case tok::comma: // #define X(A,
1696 break;
1697 case tok::ellipsis: // #define X(A... -> GCC extension
1698 // Diagnose extension.
1699 Diag(Tok, diag::ext_named_variadic_macro);
1700
1701 // Lex the token after the identifier.
1702 LexUnexpandedToken(Tok);
1703 if (Tok.getKind() != tok::r_paren) {
1704 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1705 return true;
1706 }
1707
1708 MI->setIsGNUVarargs();
1709 return false;
1710 }
1711 }
1712 }
1713}
1714
Chris Lattner22eb9722006-06-18 05:43:12 +00001715/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001716/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1717/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001718///
Chris Lattner81278c62006-10-14 19:03:49 +00001719void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1720 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001721 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001722
Chris Lattner22eb9722006-06-18 05:43:12 +00001723 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001724 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001725
1726 // Error reading macro name? If so, diagnostic already issued.
1727 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001728 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001729
Chris Lattner457fc152006-07-29 06:30:25 +00001730 // If we are supposed to keep comments in #defines, reenable comment saving
1731 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001732 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001733
Chris Lattner063400e2006-10-14 19:54:15 +00001734 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001735 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001736 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001737
Chris Lattner063400e2006-10-14 19:54:15 +00001738 // If the identifier is an 'other target' macro, clear this bit.
1739 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1740
1741
Chris Lattner22eb9722006-06-18 05:43:12 +00001742 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001743 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001744
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001745 // If this is a function-like macro definition, parse the argument list,
1746 // marking each of the identifiers as being used as macro arguments. Also,
1747 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001748 if (Tok.getKind() == tok::eom) {
1749 // If there is no body to this macro, we have no special handling here.
1750 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001751 // This is a function-like macro definition. Read the argument list.
1752 MI->setIsFunctionLike();
1753 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001754 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001755 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001756 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001757 if (CurLexer->ParsingPreprocessorDirective)
1758 DiscardUntilEndOfDirective();
1759 return;
1760 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001761
Chris Lattner815a1f92006-07-08 20:48:04 +00001762 // Read the first token after the arg list for down below.
1763 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001764 } else if (!Tok.hasLeadingSpace()) {
1765 // C99 requires whitespace between the macro definition and the body. Emit
1766 // a diagnostic for something like "#define X+".
1767 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001768 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001769 } else {
1770 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1771 // one in some cases!
1772 }
1773 } else {
1774 // This is a normal token with leading space. Clear the leading space
1775 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001776 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001777 }
1778
Chris Lattner7e374832006-07-29 03:46:57 +00001779 // If this is a definition of a variadic C99 function-like macro, not using
1780 // the GNU named varargs extension, enabled __VA_ARGS__.
1781
1782 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1783 // This gets unpoisoned where it is allowed.
1784 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1785 if (MI->isC99Varargs())
1786 Ident__VA_ARGS__->setIsPoisoned(false);
1787
Chris Lattner22eb9722006-06-18 05:43:12 +00001788 // Read the rest of the macro body.
1789 while (Tok.getKind() != tok::eom) {
1790 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001791
1792 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001793 // parameters in function-like macro expansions.
1794 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001795 // Get the next token of the macro.
1796 LexUnexpandedToken(Tok);
1797 continue;
1798 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001799
Chris Lattner815a1f92006-07-08 20:48:04 +00001800 // Get the next token of the macro.
1801 LexUnexpandedToken(Tok);
1802
1803 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001804 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001805 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001806 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001807 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001808
1809 // Disable __VA_ARGS__ again.
1810 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001811 return;
1812 }
1813
1814 // Things look ok, add the param name token to the macro.
1815 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001816
Chris Lattner22eb9722006-06-18 05:43:12 +00001817 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001818 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001819 }
Chris Lattner7e374832006-07-29 03:46:57 +00001820
1821 // Disable __VA_ARGS__ again.
1822 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001823
Chris Lattnerbff18d52006-07-06 04:49:18 +00001824 // Check that there is no paste (##) operator at the begining or end of the
1825 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001826 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001827 if (NumTokens != 0) {
1828 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001829 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001830 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001831 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001832 }
1833 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001834 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001835 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001836 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001837 }
1838 }
1839
Chris Lattner13044d92006-07-03 05:16:44 +00001840 // If this is the primary source file, remember that this macro hasn't been
1841 // used yet.
1842 if (isInPrimaryFile())
1843 MI->setIsUsed(false);
1844
Chris Lattner22eb9722006-06-18 05:43:12 +00001845 // Finally, if this identifier already had a macro defined for it, verify that
1846 // the macro bodies are identical and free the old definition.
1847 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001848 if (!OtherMI->isUsed())
1849 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1850
Chris Lattner22eb9722006-06-18 05:43:12 +00001851 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001852 // must be the same. C99 6.10.3.2.
1853 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001854 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1855 MacroNameTok.getIdentifierInfo()->getName());
1856 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1857 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001858 delete OtherMI;
1859 }
1860
1861 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001862}
1863
Chris Lattner063400e2006-10-14 19:54:15 +00001864/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1865void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1866 LexerToken MacroNameTok;
1867 ReadMacroName(MacroNameTok, 1);
1868
1869 // Error reading macro name? If so, diagnostic already issued.
1870 if (MacroNameTok.getKind() == tok::eom)
1871 return;
1872
1873 // Check to see if this is the last token on the #undef line.
1874 CheckEndOfDirective("#define_other_target");
1875
1876 // If there is already a macro defined by this name, turn it into a
1877 // target-specific define.
1878 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1879 MI->setIsTargetSpecific(true);
1880 return;
1881 }
1882
1883 // Mark the identifier as being a macro on some other target.
1884 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1885}
1886
Chris Lattner22eb9722006-06-18 05:43:12 +00001887
1888/// HandleUndefDirective - Implements #undef.
1889///
Chris Lattnercb283342006-06-18 06:48:37 +00001890void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001891 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001892
Chris Lattner22eb9722006-06-18 05:43:12 +00001893 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001894 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001895
1896 // Error reading macro name? If so, diagnostic already issued.
1897 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001898 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001899
1900 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001901 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001902
1903 // Okay, we finally have a valid identifier to undef.
1904 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1905
Chris Lattner063400e2006-10-14 19:54:15 +00001906 // #undef untaints an identifier if it were marked by define_other_target.
1907 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1908
Chris Lattner22eb9722006-06-18 05:43:12 +00001909 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001910 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001911
Chris Lattner13044d92006-07-03 05:16:44 +00001912 if (!MI->isUsed())
1913 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001914
1915 // Free macro definition.
1916 delete MI;
1917 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001918}
1919
1920
Chris Lattnerb8761832006-06-24 21:31:03 +00001921//===----------------------------------------------------------------------===//
1922// Preprocessor Conditional Directive Handling.
1923//===----------------------------------------------------------------------===//
1924
Chris Lattner22eb9722006-06-18 05:43:12 +00001925/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001926/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1927/// if any tokens have been returned or pp-directives activated before this
1928/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001929///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001930void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1931 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001932 ++NumIf;
1933 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001934
Chris Lattner22eb9722006-06-18 05:43:12 +00001935 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001936 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001937
1938 // Error reading macro name? If so, diagnostic already issued.
1939 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001940 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001941
1942 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001943 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1944
1945 // If the start of a top-level #ifdef, inform MIOpt.
1946 if (!ReadAnyTokensBeforeDirective &&
1947 CurLexer->getConditionalStackDepth() == 0) {
1948 assert(isIfndef && "#ifdef shouldn't reach here");
1949 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1950 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001951
Chris Lattner063400e2006-10-14 19:54:15 +00001952 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1953 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001954
Chris Lattner81278c62006-10-14 19:03:49 +00001955 // If there is a macro, process it.
1956 if (MI) {
1957 // Mark it used.
1958 MI->setIsUsed(true);
1959
1960 // If this is the first use of a target-specific macro, warn about it.
1961 if (MI->isTargetSpecific()) {
1962 MI->setIsTargetSpecific(false); // Don't warn on second use.
1963 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1964 diag::port_target_macro_use);
1965 }
Chris Lattner063400e2006-10-14 19:54:15 +00001966 } else {
1967 // Use of a target-specific macro for some other target? If so, warn.
1968 if (MII->isOtherTargetMacro()) {
1969 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1970 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1971 diag::port_target_macro_use);
1972 }
Chris Lattner81278c62006-10-14 19:03:49 +00001973 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001974
Chris Lattner22eb9722006-06-18 05:43:12 +00001975 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001976 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001977 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001978 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001979 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001980 } else {
1981 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001982 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001983 /*Foundnonskip*/false,
1984 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001985 }
1986}
1987
1988/// HandleIfDirective - Implements the #if directive.
1989///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001990void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1991 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001992 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001993
Chris Lattner371ac8a2006-07-04 07:11:10 +00001994 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001995 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001996 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001997
1998 // Should we include the stuff contained by this directive?
1999 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002000 // If this condition is equivalent to #ifndef X, and if this is the first
2001 // directive seen, handle it for the multiple-include optimization.
2002 if (!ReadAnyTokensBeforeDirective &&
2003 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2004 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2005
Chris Lattner22eb9722006-06-18 05:43:12 +00002006 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002007 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002008 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002009 } else {
2010 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002011 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002012 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002013 }
2014}
2015
2016/// HandleEndifDirective - Implements the #endif directive.
2017///
Chris Lattnercb283342006-06-18 06:48:37 +00002018void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002019 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002020
Chris Lattner22eb9722006-06-18 05:43:12 +00002021 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002022 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002023
2024 PPConditionalInfo CondInfo;
2025 if (CurLexer->popConditionalLevel(CondInfo)) {
2026 // No conditionals on the stack: this is an #endif without an #if.
2027 return Diag(EndifToken, diag::err_pp_endif_without_if);
2028 }
2029
Chris Lattner371ac8a2006-07-04 07:11:10 +00002030 // If this the end of a top-level #endif, inform MIOpt.
2031 if (CurLexer->getConditionalStackDepth() == 0)
2032 CurLexer->MIOpt.ExitTopLevelConditional();
2033
Chris Lattner538d7f32006-07-20 04:31:52 +00002034 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002035 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002036}
2037
2038
Chris Lattnercb283342006-06-18 06:48:37 +00002039void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002040 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002041
Chris Lattner22eb9722006-06-18 05:43:12 +00002042 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002043 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002044
2045 PPConditionalInfo CI;
2046 if (CurLexer->popConditionalLevel(CI))
2047 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002048
2049 // If this is a top-level #else, inform the MIOpt.
2050 if (CurLexer->getConditionalStackDepth() == 0)
2051 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002052
2053 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002054 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002055
2056 // Finally, skip the rest of the contents of this block and return the first
2057 // token after it.
2058 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2059 /*FoundElse*/true);
2060}
2061
Chris Lattnercb283342006-06-18 06:48:37 +00002062void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002063 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002064
Chris Lattner22eb9722006-06-18 05:43:12 +00002065 // #elif directive in a non-skipping conditional... start skipping.
2066 // We don't care what the condition is, because we will always skip it (since
2067 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002068 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002069
2070 PPConditionalInfo CI;
2071 if (CurLexer->popConditionalLevel(CI))
2072 return Diag(ElifToken, diag::pp_err_elif_without_if);
2073
Chris Lattner371ac8a2006-07-04 07:11:10 +00002074 // If this is a top-level #elif, inform the MIOpt.
2075 if (CurLexer->getConditionalStackDepth() == 0)
2076 CurLexer->MIOpt.FoundTopLevelElse();
2077
Chris Lattner22eb9722006-06-18 05:43:12 +00002078 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002079 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002080
2081 // Finally, skip the rest of the contents of this block and return the first
2082 // token after it.
2083 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2084 /*FoundElse*/CI.FoundElse);
2085}
Chris Lattnerb8761832006-06-24 21:31:03 +00002086