blob: 8376b9f8a30b39ca5f3a88c27c39890c5150b556 [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>
Chris Lattner22eb9722006-06-18 05:43:12 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
Chris Lattner02dffbd2006-10-14 07:50:21 +000044Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000045 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000046 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000047 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
48 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000049 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000050 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000051
Chris Lattner22eb9722006-06-18 05:43:12 +000052 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000053 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000054 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000055 NumEnteredSourceFiles = 0;
56 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000057 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000058 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000059 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000060
61 // Default to discarding comments.
62 KeepComments = false;
63 KeepMacroComments = false;
64
Chris Lattner22eb9722006-06-18 05:43:12 +000065 // Macro expansion is enabled.
66 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000067 InMacroArgs = false;
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000068 NumCachedMacroExpanders = 0;
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
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000092 // Free any cached macro expanders.
93 for (unsigned i = 0, e = NumCachedMacroExpanders; i != e; ++i)
94 delete MacroExpanderCache[i];
95
Chris Lattnerb8761832006-06-24 21:31:03 +000096 // Release pragma information.
97 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000098
99 // Delete the scratch buffer info.
100 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +0000101}
102
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000103PPCallbacks::~PPCallbacks() {
104}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000105
Chris Lattner22eb9722006-06-18 05:43:12 +0000106/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
107/// the specified LexerToken's location, translating the token's start
108/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattner36982e42007-05-16 17:49:37 +0000109void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
110 Diags.Report(Loc, DiagID);
111}
112
Chris Lattnercb283342006-06-18 06:48:37 +0000113void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000114 const std::string &Msg) {
Chris Lattner36982e42007-05-16 17:49:37 +0000115 Diags.Report(Loc, DiagID, &Msg, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000116}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000117
118void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
119 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
120 << getSpelling(Tok) << "'";
121
122 if (!DumpFlags) return;
123 std::cerr << "\t";
124 if (Tok.isAtStartOfLine())
125 std::cerr << " [StartOfLine]";
126 if (Tok.hasLeadingSpace())
127 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000128 if (Tok.isExpandDisabled())
129 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000130 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000131 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000132 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
133 << "']";
134 }
135}
136
137void Preprocessor::DumpMacro(const MacroInfo &MI) const {
138 std::cerr << "MACRO: ";
139 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
140 DumpToken(MI.getReplacementToken(i));
141 std::cerr << " ";
142 }
143 std::cerr << "\n";
144}
145
Chris Lattner22eb9722006-06-18 05:43:12 +0000146void Preprocessor::PrintStats() {
147 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000148 std::cerr << NumDirectives << " directives found:\n";
149 std::cerr << " " << NumDefined << " #define.\n";
150 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000151 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000152 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
153 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
154 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
155 std::cerr << " " << NumElse << " #else/#elif.\n";
156 std::cerr << " " << NumEndif << " #endif.\n";
157 std::cerr << " " << NumPragma << " #pragma.\n";
158 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
159
Chris Lattner78186052006-07-09 00:45:31 +0000160 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
161 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000162 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000163 std::cerr << (NumFastTokenPaste+NumTokenPaste)
164 << " token paste (##) operations performed, "
165 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000166}
167
168//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000169// Token Spelling
170//===----------------------------------------------------------------------===//
171
172
173/// getSpelling() - Return the 'spelling' of this token. The spelling of a
174/// token are the characters used to represent the token in the source file
175/// after trigraph expansion and escaped-newline folding. In particular, this
176/// wants to get the true, uncanonicalized, spelling of things like digraphs
177/// UCNs, etc.
178std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
179 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
180
181 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000182 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000183 if (!Tok.needsCleaning())
184 return std::string(TokStart, TokStart+Tok.getLength());
185
Chris Lattnerd01e2912006-06-18 16:22:51 +0000186 std::string Result;
187 Result.reserve(Tok.getLength());
188
Chris Lattneref9eae12006-07-04 22:33:12 +0000189 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000190 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
191 Ptr != End; ) {
192 unsigned CharSize;
193 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
194 Ptr += CharSize;
195 }
196 assert(Result.size() != unsigned(Tok.getLength()) &&
197 "NeedsCleaning flag set on something that didn't need cleaning!");
198 return Result;
199}
200
201/// getSpelling - This method is used to get the spelling of a token into a
202/// preallocated buffer, instead of as an std::string. The caller is required
203/// to allocate enough space for the token, which is guaranteed to be at least
204/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000205///
206/// Note that this method may do two possible things: it may either fill in
207/// the buffer specified with characters, or it may *change the input pointer*
208/// to point to a constant buffer with the data already in it (avoiding a
209/// copy). The caller is not allowed to modify the returned buffer pointer
210/// if an internal buffer is returned.
211unsigned Preprocessor::getSpelling(const LexerToken &Tok,
212 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000213 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
214
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000215 // If this token is an identifier, just return the string from the identifier
216 // table, which is very quick.
217 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
218 Buffer = II->getName();
219 return Tok.getLength();
220 }
221
222 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000223 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224
225 // If this token contains nothing interesting, return it directly.
226 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000227 Buffer = TokStart;
228 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000229 }
230 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000231 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000232 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
233 Ptr != End; ) {
234 unsigned CharSize;
235 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
236 Ptr += CharSize;
237 }
238 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
239 "NeedsCleaning flag set on something that didn't need cleaning!");
240
241 return OutBuf-Buffer;
242}
243
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000244
245/// CreateString - Plop the specified string into a scratch buffer and return a
246/// location for it. If specified, the source location provides a source
247/// location for the token.
248SourceLocation Preprocessor::
249CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
250 if (SLoc.isValid())
251 return ScratchBuf->getToken(Buf, Len, SLoc);
252 return ScratchBuf->getToken(Buf, Len);
253}
254
255
Chris Lattnerd01e2912006-06-18 16:22:51 +0000256//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000257// Source File Location Methods.
258//===----------------------------------------------------------------------===//
259
Chris Lattner22eb9722006-06-18 05:43:12 +0000260/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
261/// return null on failure. isAngled indicates whether the file reference is
262/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000263const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
264 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000265 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000266 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000267 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000268 // If the header lookup mechanism may be relative to the current file, pass in
269 // info about where the current file is.
270 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000271 if (!FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000272 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000273 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000274 }
275
Chris Lattner63dd32b2006-10-20 04:42:40 +0000276 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000277 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000278 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000279 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
280 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000281 if (FE) return FE;
282
283 // Otherwise, see if this is a subframework header. If so, this is relative
284 // to one of the headers on the #include stack. Walk the list of the current
285 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000286 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000287 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000288 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
289 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000290 return FE;
291 }
292
293 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
294 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000295 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000296 CurFileEnt =
297 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000298 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
299 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000300 return FE;
301 }
302 }
303
304 // Otherwise, we really couldn't find the file.
305 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000306}
307
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000308/// isInPrimaryFile - Return true if we're in the top-level file, not in a
309/// #include.
310bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000311 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000312 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000313
Chris Lattner13044d92006-07-03 05:16:44 +0000314 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000315 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000316 if (IncludeMacroStack[i].TheLexer &&
317 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
318 return IncludeMacroStack[i].TheLexer->isMainFile();
319 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000320}
321
322/// getCurrentLexer - Return the current file lexer being lexed from. Note
323/// that this ignores any potentially active macro expansions and _Pragma
324/// expansions going on at the time.
325Lexer *Preprocessor::getCurrentFileLexer() const {
326 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
327
328 // Look for a stacked lexer.
329 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000330 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000331 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
332 return L;
333 }
334 return 0;
335}
336
337
Chris Lattner22eb9722006-06-18 05:43:12 +0000338/// EnterSourceFile - Add a source file to the top of the include stack and
339/// start lexing tokens from it instead of the current buffer. Return true
340/// on failure.
341void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000342 const DirectoryLookup *CurDir,
343 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000344 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000345 ++NumEnteredSourceFiles;
346
Chris Lattner69772b02006-07-02 20:34:39 +0000347 if (MaxIncludeStackDepth < IncludeMacroStack.size())
348 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000349
Chris Lattner23b7eb62007-06-15 23:05:46 +0000350 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000351 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000352 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000353 EnterSourceFileWithLexer(TheLexer, CurDir);
354}
Chris Lattner22eb9722006-06-18 05:43:12 +0000355
Chris Lattner69772b02006-07-02 20:34:39 +0000356/// EnterSourceFile - Add a source file to the top of the include stack and
357/// start lexing tokens from it instead of the current buffer.
358void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
359 const DirectoryLookup *CurDir) {
360
361 // Add the current lexer to the include stack.
362 if (CurLexer || CurMacroExpander)
363 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
364 CurMacroExpander));
365
366 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000367 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000368 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000369
370 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000371 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000372 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
373
374 // Get the file entry for the current file.
375 if (const FileEntry *FE =
376 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000377 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000378
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000379 Callbacks->FileChanged(SourceLocation(CurLexer->getCurFileID(), 0),
380 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000381 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000382}
383
Chris Lattner69772b02006-07-02 20:34:39 +0000384
385
Chris Lattner22eb9722006-06-18 05:43:12 +0000386/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000387/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000388void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000389 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
390 CurMacroExpander));
391 CurLexer = 0;
392 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000393
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000394 if (NumCachedMacroExpanders == 0) {
395 CurMacroExpander = new MacroExpander(Tok, Args, *this);
396 } else {
397 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
398 CurMacroExpander->Init(Tok, Args);
399 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000400}
401
Chris Lattner7667d0d2006-07-16 18:16:58 +0000402/// EnterTokenStream - Add a "macro" context to the top of the include stack,
403/// which will cause the lexer to start returning the specified tokens. Note
404/// that these tokens will be re-macro-expanded when/if expansion is enabled.
405/// This method assumes that the specified stream of tokens has a permanent
406/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000407void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000408 // Save our current state.
409 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
410 CurMacroExpander));
411 CurLexer = 0;
412 CurDirLookup = 0;
413
414 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000415 if (NumCachedMacroExpanders == 0) {
416 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
417 } else {
418 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
419 CurMacroExpander->Init(Toks, NumToks);
420 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000421}
422
423/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
424/// lexer stack. This should only be used in situations where the current
425/// state of the top-of-stack lexer is known.
426void Preprocessor::RemoveTopOfLexerStack() {
427 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000428
429 if (CurMacroExpander) {
430 // Delete or cache the now-dead macro expander.
431 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
432 delete CurMacroExpander;
433 else
434 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
435 } else {
436 delete CurLexer;
437 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000438 CurLexer = IncludeMacroStack.back().TheLexer;
439 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
440 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
441 IncludeMacroStack.pop_back();
442}
443
Chris Lattner22eb9722006-06-18 05:43:12 +0000444//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000445// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000446//===----------------------------------------------------------------------===//
447
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000448/// RegisterBuiltinMacro - Register the specified identifier in the identifier
449/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000450IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000451 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000452 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000453
454 // Mark it as being a macro that is builtin.
455 MacroInfo *MI = new MacroInfo(SourceLocation());
456 MI->setIsBuiltinMacro();
457 Id->setMacroInfo(MI);
458 return Id;
459}
460
461
Chris Lattner677757a2006-06-28 05:26:32 +0000462/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
463/// identifier table.
464void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000465 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000466 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000467 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
468 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000469 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000470
471 // GCC Extensions.
472 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
473 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000474 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000475}
476
Chris Lattnerc2395832006-07-09 00:57:04 +0000477/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
478/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000479static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
480 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000481 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
482
483 // If the token isn't an identifier, it's always literally expanded.
484 if (II == 0) return true;
485
486 // If the identifier is a macro, and if that macro is enabled, it may be
487 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000488 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
489 // Fast expanding "#define X X" is ok, because X would be disabled.
490 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000491 return false;
492
493 // If this is an object-like macro invocation, it is safe to trivially expand
494 // it.
495 if (MI->isObjectLike()) return true;
496
497 // If this is a function-like macro invocation, it's safe to trivially expand
498 // as long as the identifier is not a macro argument.
499 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
500 I != E; ++I)
501 if (*I == II)
502 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000503
Chris Lattnerc2395832006-07-09 00:57:04 +0000504 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000505}
506
Chris Lattnerc2395832006-07-09 00:57:04 +0000507
Chris Lattnerafe603f2006-07-11 04:02:46 +0000508/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
509/// lexed is a '('. If so, consume the token and return true, if not, this
510/// method should have no observable side-effect on the lexed tokens.
511bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000512 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000513 unsigned Val;
514 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000515 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000516 else
517 Val = CurMacroExpander->isNextTokenLParen();
518
519 if (Val == 2) {
520 // If we ran off the end of the lexer or macro expander, walk the include
521 // stack, looking for whatever will return the next token.
522 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
523 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
524 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000525 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000526 else
527 Val = Entry.TheMacroExpander->isNextTokenLParen();
528 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000529 }
530
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000531 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
532 // have found something that isn't a '(' or we found the end of the
533 // translation unit. In either case, return false.
534 if (Val != 1)
535 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000536
537 LexerToken Tok;
538 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000539 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
540 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000541}
Chris Lattner677757a2006-06-28 05:26:32 +0000542
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000543/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
544/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000545bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000546 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000547
548 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
549 if (MI->isBuiltinMacro()) {
550 ExpandBuiltinMacro(Identifier);
551 return false;
552 }
553
Chris Lattner81278c62006-10-14 19:03:49 +0000554 // If this is the first use of a target-specific macro, warn about it.
555 if (MI->isTargetSpecific()) {
556 MI->setIsTargetSpecific(false); // Don't warn on second use.
557 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
558 diag::port_target_macro_use);
559 }
560
Chris Lattneree8760b2006-07-15 07:42:55 +0000561 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000562 /// for each macro argument, the list of tokens that were provided to the
563 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000564 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000565
566 // If this is a function-like macro, read the arguments.
567 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000568 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
569 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000570 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000571 return true;
572
Chris Lattner78186052006-07-09 00:45:31 +0000573 // Remember that we are now parsing the arguments to a macro invocation.
574 // Preprocessor directives used inside macro arguments are not portable, and
575 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000576 InMacroArgs = true;
577 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000578
579 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000580 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000581
582 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000583 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000584
585 ++NumFnMacroExpanded;
586 } else {
587 ++NumMacroExpanded;
588 }
Chris Lattner13044d92006-07-03 05:16:44 +0000589
590 // Notice that this macro has been used.
591 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000592
593 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000594
595 // If this macro expands to no tokens, don't bother to push it onto the
596 // expansion stack, only to take it right back off.
597 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000598 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000599 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000600
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000601 // Ignore this macro use, just return the next token in the current
602 // buffer.
603 bool HadLeadingSpace = Identifier.hasLeadingSpace();
604 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
605
606 Lex(Identifier);
607
608 // If the identifier isn't on some OTHER line, inherit the leading
609 // whitespace/first-on-a-line property of this token. This handles
610 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
611 // empty.
612 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000613 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
614 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000615 }
616 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000617 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000618
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000619 } else if (MI->getNumTokens() == 1 &&
620 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000621 // Otherwise, if this macro expands into a single trivially-expanded
622 // token: expand it now. This handles common cases like
623 // "#define VAL 42".
624
625 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
626 // identifier to the expanded token.
627 bool isAtStartOfLine = Identifier.isAtStartOfLine();
628 bool hasLeadingSpace = Identifier.hasLeadingSpace();
629
630 // Remember where the token is instantiated.
631 SourceLocation InstantiateLoc = Identifier.getLocation();
632
633 // Replace the result token.
634 Identifier = MI->getReplacementToken(0);
635
636 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000637 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
638 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000639
640 // Update the tokens location to include both its logical and physical
641 // locations.
642 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000643 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000644 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000645
Chris Lattner6e4bf522006-07-27 06:59:25 +0000646 // If this is #define X X, we must mark the result as unexpandible.
647 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
648 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000649 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000650
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000651 // Since this is not an identifier token, it can't be macro expanded, so
652 // we're done.
653 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000654 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000655 }
656
Chris Lattner78186052006-07-09 00:45:31 +0000657 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000658 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000659
660 // Now that the macro is at the top of the include stack, ask the
661 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000662 Lex(Identifier);
663 return false;
664}
665
Chris Lattneree8760b2006-07-15 07:42:55 +0000666/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000667/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000668/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000669MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
670 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000671 // The number of fixed arguments to parse.
672 unsigned NumFixedArgsLeft = MI->getNumArgs();
673 bool isVariadic = MI->isVariadic();
674
Chris Lattner78186052006-07-09 00:45:31 +0000675 // Outer loop, while there are more arguments, keep reading them.
676 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000677 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000678 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000679
680 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000681 // argument is separated by an EOF token. Use a SmallVector so we can avoid
682 // heap allocations in the common case.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000683 llvm::SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000684
685 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000686 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000687 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
688 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000689
Chris Lattner78186052006-07-09 00:45:31 +0000690 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000691 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
692 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000693 LexUnexpandedToken(Tok);
694
695 if (Tok.getKind() == tok::eof) {
696 Diag(MacroName, diag::err_unterm_macro_invoc);
697 // Do not lose the EOF. Return it to the client.
698 MacroName = Tok;
699 return 0;
700 } else if (Tok.getKind() == tok::r_paren) {
701 // If we found the ) token, the macro arg list is done.
702 if (NumParens-- == 0)
703 break;
704 } else if (Tok.getKind() == tok::l_paren) {
705 ++NumParens;
706 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
707 // Comma ends this argument if there are more fixed arguments expected.
708 if (NumFixedArgsLeft)
709 break;
710
Chris Lattner2ada5d32006-07-15 07:51:24 +0000711 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000712 if (!isVariadic) {
713 // Emit the diagnostic at the macro name in case there is a missing ).
714 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000715 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000716 return 0;
717 }
718 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000719 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000720 // If this is a comment token in the argument list and we're just in
721 // -C mode (not -CC mode), discard the comment.
722 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000723 }
724
725 ArgTokens.push_back(Tok);
726 }
727
Chris Lattnera12dd152006-07-11 04:09:02 +0000728 // Empty arguments are standard in C99 and supported as an extension in
729 // other modes.
730 if (ArgTokens.empty() && !Features.C99)
731 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000732
Chris Lattner36b6e812006-07-21 06:38:30 +0000733 // Add a marker EOF token to the end of the token list for this argument.
734 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000735 EOFTok.startToken();
736 EOFTok.setKind(tok::eof);
737 EOFTok.setLocation(Tok.getLocation());
738 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000739 ArgTokens.push_back(EOFTok);
740 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000741 --NumFixedArgsLeft;
742 };
743
744 // Okay, we either found the r_paren. Check to see if we parsed too few
745 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000746 unsigned MinArgsExpected = MI->getNumArgs();
747
Chris Lattner775d8322006-07-29 04:39:41 +0000748 // See MacroArgs instance var for description of this.
749 bool isVarargsElided = false;
750
Chris Lattner2ada5d32006-07-15 07:51:24 +0000751 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000752 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000753 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000754 // Varargs where the named vararg parameter is missing: ok as extension.
755 // #define A(x, ...)
756 // A("blah")
757 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000758
759 // Remember this occurred if this is a C99 macro invocation with at least
760 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000761 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000762 } else if (MI->getNumArgs() == 1) {
763 // #define A(x)
764 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000765 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000766
767 // Empty arguments are standard in C99 and supported as an extension in
768 // other modes.
769 if (ArgTokens.empty() && !Features.C99)
770 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000771 } else {
772 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000773 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000774 return 0;
775 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000776
777 // Add a marker EOF token to the end of the token list for this argument.
778 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000779 Tok.startToken();
780 Tok.setKind(tok::eof);
781 Tok.setLocation(EndLoc);
782 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000783 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000784 }
785
Chris Lattner775d8322006-07-29 04:39:41 +0000786 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000787}
788
Chris Lattnerc673f902006-06-30 06:10:41 +0000789/// ComputeDATE_TIME - Compute the current time, enter it into the specified
790/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
791/// the identifier tokens inserted.
792static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000793 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000794 time_t TT = time(0);
795 struct tm *TM = localtime(&TT);
796
797 static const char * const Months[] = {
798 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
799 };
800
801 char TmpBuffer[100];
802 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
803 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000804 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000805
806 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000807 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000808}
809
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000810/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
811/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000812void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000813 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000814 IdentifierInfo *II = Tok.getIdentifierInfo();
815 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000816
817 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
818 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000819 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000820 return Handle_Pragma(Tok);
821
Chris Lattner78186052006-07-09 00:45:31 +0000822 ++NumBuiltinMacroExpanded;
823
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000824 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000825
826 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000827 Tok.setIdentifierInfo(0);
828 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000829
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000830 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000831 // __LINE__ expands to a simple numeric value.
832 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
833 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000834 Tok.setKind(tok::numeric_constant);
835 Tok.setLength(Length);
836 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000837 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000838 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000839 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000840 Diag(Tok, diag::ext_pp_base_file);
841 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
842 while (NextLoc.getFileID() != 0) {
843 Loc = NextLoc;
844 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
845 }
846 }
847
Chris Lattner0766e592006-07-03 01:07:01 +0000848 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
849 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000850 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000851 Tok.setKind(tok::string_literal);
852 Tok.setLength(FN.size());
853 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000854 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000855 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000856 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000857 Tok.setKind(tok::string_literal);
858 Tok.setLength(strlen("\"Mmm dd yyyy\""));
859 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000860 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000861 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000862 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000863 Tok.setKind(tok::string_literal);
864 Tok.setLength(strlen("\"hh:mm:ss\""));
865 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000866 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000867 Diag(Tok, diag::ext_pp_include_level);
868
869 // Compute the include depth of this token.
870 unsigned Depth = 0;
871 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
872 for (; Loc.getFileID() != 0; ++Depth)
873 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
874
875 // __INCLUDE_LEVEL__ expands to a simple numeric value.
876 sprintf(TmpBuffer, "%u", Depth);
877 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000878 Tok.setKind(tok::numeric_constant);
879 Tok.setLength(Length);
880 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000881 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000882 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
883 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
884 Diag(Tok, diag::ext_pp_timestamp);
885
886 // Get the file that we are lexing out of. If we're currently lexing from
887 // a macro, dig into the include stack.
888 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000889 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000890
891 if (TheLexer)
892 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
893
894 // If this file is older than the file it depends on, emit a diagnostic.
895 const char *Result;
896 if (CurFile) {
897 time_t TT = CurFile->getModificationTime();
898 struct tm *TM = localtime(&TT);
899 Result = asctime(TM);
900 } else {
901 Result = "??? ??? ?? ??:??:?? ????\n";
902 }
903 TmpBuffer[0] = '"';
904 strcpy(TmpBuffer+1, Result);
905 unsigned Len = strlen(TmpBuffer);
906 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000907 Tok.setKind(tok::string_literal);
908 Tok.setLength(Len);
909 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000910 } else {
911 assert(0 && "Unknown identifier!");
912 }
913}
Chris Lattner677757a2006-06-28 05:26:32 +0000914
915//===----------------------------------------------------------------------===//
916// Lexer Event Handling.
917//===----------------------------------------------------------------------===//
918
Chris Lattnercefc7682006-07-08 08:28:12 +0000919/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
920/// identifier information for the token and install it into the token.
921IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
922 const char *BufPtr) {
923 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
924 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
925
926 // Look up this token, see if it is a macro, or if it is a language keyword.
927 IdentifierInfo *II;
928 if (BufPtr && !Identifier.needsCleaning()) {
929 // No cleaning needed, just use the characters from the lexed buffer.
930 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
931 } else {
932 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +0000933 llvm::SmallVector<char, 64> IdentifierBuffer;
934 IdentifierBuffer.resize(Identifier.getLength());
935 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +0000936 unsigned Size = getSpelling(Identifier, TmpBuf);
937 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
938 }
Chris Lattner8c204872006-10-14 05:19:21 +0000939 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000940 return II;
941}
942
943
Chris Lattner677757a2006-06-28 05:26:32 +0000944/// HandleIdentifier - This callback is invoked when the lexer reads an
945/// identifier. This callback looks up the identifier in the map and/or
946/// potentially macro expands it or turns it into a named token (like 'for').
947void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000948 assert(Identifier.getIdentifierInfo() &&
949 "Can't handle identifiers without identifier info!");
950
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000951 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000952
953 // If this identifier was poisoned, and if it was not produced from a macro
954 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000955 if (II.isPoisoned() && CurLexer) {
956 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
957 Diag(Identifier, diag::err_pp_used_poisoned_id);
958 else
959 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
960 }
Chris Lattner677757a2006-06-28 05:26:32 +0000961
Chris Lattner78186052006-07-09 00:45:31 +0000962 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000963 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000964 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
965 if (MI->isEnabled()) {
966 if (!HandleMacroExpandedIdentifier(Identifier, MI))
967 return;
968 } else {
969 // C99 6.10.3.4p2 says that a disabled macro may never again be
970 // expanded, even if it's in a context where it could be expanded in the
971 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000972 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000973 }
974 }
Chris Lattner063400e2006-10-14 19:54:15 +0000975 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
976 // If this identifier is a macro on some other target, emit a diagnostic.
977 // This diagnosic is only emitted when macro expansion is enabled, because
978 // the macro would not have been expanded for the other target either.
979 II.setIsOtherTargetMacro(false); // Don't warn on second use.
980 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
981 diag::port_target_macro_use);
982
983 }
Chris Lattner677757a2006-06-28 05:26:32 +0000984
Chris Lattner5b9f4892006-11-21 17:23:33 +0000985 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
986 // then we act as if it is the actual operator and not the textual
987 // representation of it.
988 if (II.isCPlusPlusOperatorKeyword())
989 Identifier.setIdentifierInfo(0);
990
Chris Lattner677757a2006-06-28 05:26:32 +0000991 // Change the kind of this identifier to the appropriate token kind, e.g.
992 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000993 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000994
995 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +0000996 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
997 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +0000998 if (II.isExtensionToken() && Features.C99)
999 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001000}
1001
Chris Lattner22eb9722006-06-18 05:43:12 +00001002/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1003/// the current file. This either returns the EOF token or pops a level off
1004/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001005bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001006 assert(!CurMacroExpander &&
1007 "Ending a file when currently in a macro!");
1008
Chris Lattner371ac8a2006-07-04 07:11:10 +00001009 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001010 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001011 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001012 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001013 // Okay, this has a controlling macro, remember in PerFileInfo.
1014 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001015 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1016 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001017 }
1018 }
1019
Chris Lattner22eb9722006-06-18 05:43:12 +00001020 // If this is a #include'd file, pop it off the include stack and continue
1021 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001022 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001023 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001024 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001025
1026 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001027 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001028 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1029
1030 // Get the file entry for the current file.
1031 if (const FileEntry *FE =
1032 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001033 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001034
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001035 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1036 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001037 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001038
1039 // Client should lex another token.
1040 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001041 }
1042
Chris Lattner8c204872006-10-14 05:19:21 +00001043 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001044 CurLexer->BufferPtr = CurLexer->BufferEnd;
1045 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001046 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001047
1048 // We're done with the #included file.
1049 delete CurLexer;
1050 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001051
Chris Lattner03f83482006-07-10 06:16:26 +00001052 // This is the end of the top-level file. If the diag::pp_macro_not_used
1053 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1054 // have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001055 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1056 for (IdentifierTable::iterator I = Identifiers.begin(),
1057 E = Identifiers.end(); I != E; ++I) {
1058 const IdentifierInfo &II = I->getValue();
1059 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1060 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1061 }
1062 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001063
1064 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001065}
1066
1067/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001068/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001069bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001070 assert(CurMacroExpander && !CurLexer &&
1071 "Ending a macro when currently in a #include file!");
1072
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001073 // Delete or cache the now-dead macro expander.
1074 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1075 delete CurMacroExpander;
1076 else
1077 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001078
Chris Lattner69772b02006-07-02 20:34:39 +00001079 // Handle this like a #include file being popped off the stack.
1080 CurMacroExpander = 0;
1081 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001082}
1083
1084
1085//===----------------------------------------------------------------------===//
1086// Utility Methods for Preprocessor Directive Handling.
1087//===----------------------------------------------------------------------===//
1088
1089/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1090/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001091void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001092 LexerToken Tmp;
1093 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001094 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001095 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001096}
1097
Chris Lattner652c1692006-11-21 23:47:30 +00001098/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1099static bool isCXXNamedOperator(const std::string &Spelling) {
1100 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1101 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1102 Spelling == "or" || Spelling == "xor";
1103}
1104
Chris Lattner22eb9722006-06-18 05:43:12 +00001105/// ReadMacroName - Lex and validate a macro name, which occurs after a
1106/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001107/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1108/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001109/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001110void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001111 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001112 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001113
1114 // Missing macro name?
1115 if (MacroNameTok.getKind() == tok::eom)
1116 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1117
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001118 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1119 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001120 std::string Spelling = getSpelling(MacroNameTok);
1121 if (isCXXNamedOperator(Spelling))
1122 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1123 // except for their spellings.
1124 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1125 else
1126 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001127 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001128 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001129 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001130 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001131 } else if (isDefineUndef && II->getMacroInfo() &&
1132 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001133 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001134 if (isDefineUndef == 1)
1135 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1136 else
1137 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001138 } else {
1139 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001140 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001141 }
1142
Chris Lattner22eb9722006-06-18 05:43:12 +00001143 // Invalid macro name, read and discard the rest of the line. Then set the
1144 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001145 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001146 return DiscardUntilEndOfDirective();
1147}
1148
1149/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1150/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001151void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001153 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001154 // There should be no tokens after the directive, but we allow them as an
1155 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001156 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1157 Lex(Tmp);
1158
Chris Lattner22eb9722006-06-18 05:43:12 +00001159 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001160 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1161 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001162 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001163}
1164
1165
1166
1167/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1168/// decided that the subsequent tokens are in the #if'd out portion of the
1169/// file. Lex the rest of the file, until we see an #endif. If
1170/// FoundNonSkipPortion is true, then we have already emitted code for part of
1171/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1172/// is true, then #else directives are ok, if not, then we have already seen one
1173/// so a #else directive is a duplicate. When this returns, the caller can lex
1174/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001175void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001176 bool FoundNonSkipPortion,
1177 bool FoundElse) {
1178 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001179 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001180 "Lexing a macro, not a file?");
1181
1182 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1183 FoundNonSkipPortion, FoundElse);
1184
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001185 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1186 // disabling warnings, etc.
1187 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001188 LexerToken Tok;
1189 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001190 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001191
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001192 // If this is the end of the buffer, we have an error.
1193 if (Tok.getKind() == tok::eof) {
1194 // Emit errors for each unterminated conditional on the stack, including
1195 // the current one.
1196 while (!CurLexer->ConditionalStack.empty()) {
1197 Diag(CurLexer->ConditionalStack.back().IfLoc,
1198 diag::err_pp_unterminated_conditional);
1199 CurLexer->ConditionalStack.pop_back();
1200 }
1201
1202 // Just return and let the caller lex after this #include.
1203 break;
1204 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001205
1206 // If this token is not a preprocessor directive, just skip it.
1207 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1208 continue;
1209
1210 // We just parsed a # character at the start of a line, so we're in
1211 // directive mode. Tell the lexer this so any newlines we see will be
1212 // converted into an EOM token (this terminates the macro).
1213 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001214 CurLexer->KeepCommentMode = false;
1215
Chris Lattner22eb9722006-06-18 05:43:12 +00001216
1217 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001218 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001219
1220 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1221 // something bogus), skip it.
1222 if (Tok.getKind() != tok::identifier) {
1223 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001224 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001225 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001226 continue;
1227 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001228
Chris Lattner22eb9722006-06-18 05:43:12 +00001229 // If the first letter isn't i or e, it isn't intesting to us. We know that
1230 // this is safe in the face of spelling differences, because there is no way
1231 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001232 // allows us to avoid looking up the identifier info for #define/#undef and
1233 // other common directives.
1234 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1235 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001236 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1237 FirstChar != 'i' && FirstChar != 'e') {
1238 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001239 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001240 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001241 continue;
1242 }
1243
Chris Lattnere60165f2006-06-22 06:36:29 +00001244 // Get the identifier name without trigraphs or embedded newlines. Note
1245 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1246 // when skipping.
1247 // TODO: could do this with zero copies in the no-clean case by using
1248 // strncmp below.
1249 char Directive[20];
1250 unsigned IdLen;
1251 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1252 IdLen = Tok.getLength();
1253 memcpy(Directive, RawCharData, IdLen);
1254 Directive[IdLen] = 0;
1255 } else {
1256 std::string DirectiveStr = getSpelling(Tok);
1257 IdLen = DirectiveStr.size();
1258 if (IdLen >= 20) {
1259 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001260 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001261 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001262 continue;
1263 }
1264 memcpy(Directive, &DirectiveStr[0], IdLen);
1265 Directive[IdLen] = 0;
1266 }
1267
Chris Lattner22eb9722006-06-18 05:43:12 +00001268 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001269 if ((IdLen == 2) || // "if"
1270 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1271 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001272 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1273 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001274 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001275 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001276 /*foundnonskip*/false,
1277 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001278 }
1279 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001280 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001281 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001282 PPConditionalInfo CondInfo;
1283 CondInfo.WasSkipping = true; // Silence bogus warning.
1284 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001285 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001286 assert(!InCond && "Can't be skipping if not in a conditional!");
1287
1288 // If we popped the outermost skipping block, we're done skipping!
1289 if (!CondInfo.WasSkipping)
1290 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001291 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001292 // #else directive in a skipping conditional. If not in some other
1293 // skipping conditional, and if #else hasn't already been seen, enter it
1294 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001295 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1297
1298 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001299 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001300
1301 // Note that we've seen a #else in this conditional.
1302 CondInfo.FoundElse = true;
1303
1304 // If the conditional is at the top level, and the #if block wasn't
1305 // entered, enter the #else block now.
1306 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1307 CondInfo.FoundNonSkip = true;
1308 break;
1309 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001310 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001311 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1312
1313 bool ShouldEnter;
1314 // If this is in a skipping block or if we're already handled this #if
1315 // block, don't bother parsing the condition.
1316 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001317 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001318 ShouldEnter = false;
1319 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001320 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001321 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001322 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1323 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001324 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001325 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001326 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001327 }
1328
1329 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001330 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001331
1332 // If this condition is true, enter it!
1333 if (ShouldEnter) {
1334 CondInfo.FoundNonSkip = true;
1335 break;
1336 }
1337 }
1338 }
1339
1340 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001341 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001342 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001343 }
1344
1345 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1346 // of the file, just stop skipping and return to lexing whatever came after
1347 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001348 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001349}
1350
1351//===----------------------------------------------------------------------===//
1352// Preprocessor Directive Handling.
1353//===----------------------------------------------------------------------===//
1354
1355/// HandleDirective - This callback is invoked when the lexer sees a # token
1356/// at the start of a line. This consumes the directive, modifies the
1357/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1358/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001359void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001360 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001361
1362 // We just parsed a # character at the start of a line, so we're in directive
1363 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001364 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001365 CurLexer->ParsingPreprocessorDirective = true;
1366
1367 ++NumDirectives;
1368
Chris Lattner371ac8a2006-07-04 07:11:10 +00001369 // We are about to read a token. For the multiple-include optimization FA to
1370 // work, we have to remember if we had read any tokens *before* this
1371 // pp-directive.
1372 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1373
Chris Lattner78186052006-07-09 00:45:31 +00001374 // Read the next token, the directive flavor. This isn't expanded due to
1375 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001376 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001377
Chris Lattner78186052006-07-09 00:45:31 +00001378 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1379 // #define A(x) #x
1380 // A(abc
1381 // #warning blah
1382 // def)
1383 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001384 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001385 Diag(Result, diag::ext_embedded_directive);
1386
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001387TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001388 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001389 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001390 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001391 case tok::comment:
1392 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1393 LexUnexpandedToken(Result);
1394 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001395
Chris Lattner22eb9722006-06-18 05:43:12 +00001396 case tok::numeric_constant:
1397 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001398 DiscardUntilEndOfDirective();
1399 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001400 default:
1401 IdentifierInfo *II = Result.getIdentifierInfo();
1402 if (II == 0) break; // Not an identifier.
1403
1404 // Ask what the preprocessor keyword ID is.
1405 switch (II->getPPKeywordID()) {
1406 default: break;
1407 // C99 6.10.1 - Conditional Inclusion.
1408 case tok::pp_if:
1409 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1410 case tok::pp_ifdef:
1411 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1412 case tok::pp_ifndef:
1413 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1414 case tok::pp_elif:
1415 return HandleElifDirective(Result);
1416 case tok::pp_else:
1417 return HandleElseDirective(Result);
1418 case tok::pp_endif:
1419 return HandleEndifDirective(Result);
1420
1421 // C99 6.10.2 - Source File Inclusion.
1422 case tok::pp_include:
1423 return HandleIncludeDirective(Result); // Handle #include.
1424
1425 // C99 6.10.3 - Macro Replacement.
1426 case tok::pp_define:
1427 return HandleDefineDirective(Result, false);
1428 case tok::pp_undef:
1429 return HandleUndefDirective(Result);
1430
1431 // C99 6.10.4 - Line Control.
1432 case tok::pp_line:
1433 // FIXME: implement #line
1434 DiscardUntilEndOfDirective();
1435 return;
1436
1437 // C99 6.10.5 - Error Directive.
1438 case tok::pp_error:
1439 return HandleUserDiagnosticDirective(Result, false);
1440
1441 // C99 6.10.6 - Pragma Directive.
1442 case tok::pp_pragma:
1443 return HandlePragmaDirective();
1444
1445 // GNU Extensions.
1446 case tok::pp_import:
1447 return HandleImportDirective(Result);
1448 case tok::pp_include_next:
1449 return HandleIncludeNextDirective(Result);
1450
1451 case tok::pp_warning:
1452 Diag(Result, diag::ext_pp_warning_directive);
1453 return HandleUserDiagnosticDirective(Result, true);
1454 case tok::pp_ident:
1455 return HandleIdentSCCSDirective(Result);
1456 case tok::pp_sccs:
1457 return HandleIdentSCCSDirective(Result);
1458 case tok::pp_assert:
1459 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001460 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001461 case tok::pp_unassert:
1462 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001463 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001464
1465 // clang extensions.
1466 case tok::pp_define_target:
1467 return HandleDefineDirective(Result, true);
1468 case tok::pp_define_other_target:
1469 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001470 }
1471 break;
1472 }
1473
1474 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001475 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001476
1477 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001478 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001479
1480 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001481}
1482
Chris Lattner01d66cc2006-07-03 22:16:27 +00001483void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001484 bool isWarning) {
1485 // Read the rest of the line raw. We do this because we don't want macros
1486 // to be expanded and we don't require that the tokens be valid preprocessing
1487 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1488 // collapse multiple consequtive white space between tokens, but this isn't
1489 // specified by the standard.
1490 std::string Message = CurLexer->ReadToEndOfLine();
1491
1492 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001493 return Diag(Tok, DiagID, Message);
1494}
1495
1496/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1497///
1498void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001499 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001500 Diag(Tok, diag::ext_pp_ident_directive);
1501
Chris Lattner371ac8a2006-07-04 07:11:10 +00001502 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001503 LexerToken StrTok;
1504 Lex(StrTok);
1505
1506 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001507 if (StrTok.getKind() != tok::string_literal &&
1508 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001509 return Diag(StrTok, diag::err_pp_malformed_ident);
1510
1511 // Verify that there is nothing after the string, other than EOM.
1512 CheckEndOfDirective("#ident");
1513
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001514 if (Callbacks)
1515 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001516}
1517
Chris Lattnerb8761832006-06-24 21:31:03 +00001518//===----------------------------------------------------------------------===//
1519// Preprocessor Include Directive Handling.
1520//===----------------------------------------------------------------------===//
1521
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001522/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1523/// checked and spelled filename, e.g. as an operand of #include. This returns
1524/// true if the input filename was in <>'s or false if it were in ""'s. The
1525/// caller is expected to provide a buffer that is large enough to hold the
1526/// spelling of the filename, but is also expected to handle the case when
1527/// this method decides to use a different buffer.
1528bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1529 const char *&BufStart,
1530 const char *&BufEnd) {
1531 // Get the text form of the filename.
1532 unsigned Len = getSpelling(FilenameTok, BufStart);
1533 BufEnd = BufStart+Len;
1534 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1535
1536 // Make sure the filename is <x> or "x".
1537 bool isAngled;
1538 if (BufStart[0] == '<') {
1539 if (BufEnd[-1] != '>') {
1540 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1541 BufStart = 0;
1542 return true;
1543 }
1544 isAngled = true;
1545 } else if (BufStart[0] == '"') {
1546 if (BufEnd[-1] != '"') {
1547 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1548 BufStart = 0;
1549 return true;
1550 }
1551 isAngled = false;
1552 } else {
1553 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1554 BufStart = 0;
1555 return true;
1556 }
1557
1558 // Diagnose #include "" as invalid.
1559 if (BufEnd-BufStart <= 2) {
1560 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1561 BufStart = 0;
1562 return "";
1563 }
1564
1565 // Skip the brackets.
1566 ++BufStart;
1567 --BufEnd;
1568 return isAngled;
1569}
1570
Chris Lattner22eb9722006-06-18 05:43:12 +00001571/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1572/// file to be included from the lexer, then include it! This is a common
1573/// routine with functionality shared between #include, #include_next and
1574/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001575void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001576 const DirectoryLookup *LookupFrom,
1577 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001578
Chris Lattner22eb9722006-06-18 05:43:12 +00001579 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001580 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001581
1582 // If the token kind is EOM, the error has already been diagnosed.
1583 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001584 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001585
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001586 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001587 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001588 FilenameBuffer.resize(FilenameTok.getLength());
1589
1590 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1591 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1592 FilenameStart, FilenameEnd);
1593 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1594 // error.
1595 if (FilenameStart == 0)
1596 return;
1597
Chris Lattner269c2322006-06-25 06:23:00 +00001598 // Verify that there is nothing after the filename, other than EOM. Use the
1599 // preprocessor to lex this in case lexing the filename entered a macro.
1600 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001601
1602 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001603 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001604 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1605
Chris Lattner22eb9722006-06-18 05:43:12 +00001606 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001607 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001608 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001609 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001610 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001611 return Diag(FilenameTok, diag::err_pp_file_not_found,
1612 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001613
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001614 // Ask HeaderInfo if we should enter this #include file.
1615 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1616 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001617 return;
1618 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001619
1620 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001621 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001622 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001623 return Diag(FilenameTok, diag::err_pp_file_not_found,
1624 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001625
1626 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001627 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001628}
1629
1630/// HandleIncludeNextDirective - Implements #include_next.
1631///
Chris Lattnercb283342006-06-18 06:48:37 +00001632void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1633 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001634
1635 // #include_next is like #include, except that we start searching after
1636 // the current found directory. If we can't do this, issue a
1637 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001638 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001639 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001640 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001641 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001642 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001643 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001644 } else {
1645 // Start looking up in the next directory.
1646 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001647 }
1648
1649 return HandleIncludeDirective(IncludeNextTok, Lookup);
1650}
1651
1652/// HandleImportDirective - Implements #import.
1653///
Chris Lattnercb283342006-06-18 06:48:37 +00001654void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1655 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001656
1657 return HandleIncludeDirective(ImportTok, 0, true);
1658}
1659
Chris Lattnerb8761832006-06-24 21:31:03 +00001660//===----------------------------------------------------------------------===//
1661// Preprocessor Macro Directive Handling.
1662//===----------------------------------------------------------------------===//
1663
Chris Lattnercefc7682006-07-08 08:28:12 +00001664/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1665/// definition has just been read. Lex the rest of the arguments and the
1666/// closing ), updating MI with what we learn. Return true if an error occurs
1667/// parsing the arg list.
1668bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001669 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1670
Chris Lattnercefc7682006-07-08 08:28:12 +00001671 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001672 while (1) {
1673 LexUnexpandedToken(Tok);
1674 switch (Tok.getKind()) {
1675 case tok::r_paren:
1676 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001677 if (Arguments.empty()) { // #define FOO()
1678 MI->setArgumentList(Arguments.begin(), Arguments.end());
1679 return false;
1680 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001681 // Otherwise we have #define FOO(A,)
1682 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1683 return true;
1684 case tok::ellipsis: // #define X(... -> C99 varargs
1685 // Warn if use of C99 feature in non-C99 mode.
1686 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1687
1688 // Lex the token after the identifier.
1689 LexUnexpandedToken(Tok);
1690 if (Tok.getKind() != tok::r_paren) {
1691 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1692 return true;
1693 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001694 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001695 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001696 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001697 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001698 return false;
1699 case tok::eom: // #define X(
1700 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1701 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001702 default:
1703 // Handle keywords and identifiers here to accept things like
1704 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001705 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001706 if (II == 0) {
1707 // #define X(1
1708 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1709 return true;
1710 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001711
1712 // If this is already used as an argument, it is used multiple times (e.g.
1713 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00001714 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1715 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001716 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1717 return true;
1718 }
1719
1720 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00001721 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001722
1723 // Lex the token after the identifier.
1724 LexUnexpandedToken(Tok);
1725
1726 switch (Tok.getKind()) {
1727 default: // #define X(A B
1728 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1729 return true;
1730 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00001731 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001732 return false;
1733 case tok::comma: // #define X(A,
1734 break;
1735 case tok::ellipsis: // #define X(A... -> GCC extension
1736 // Diagnose extension.
1737 Diag(Tok, diag::ext_named_variadic_macro);
1738
1739 // Lex the token after the identifier.
1740 LexUnexpandedToken(Tok);
1741 if (Tok.getKind() != tok::r_paren) {
1742 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1743 return true;
1744 }
1745
1746 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001747 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001748 return false;
1749 }
1750 }
1751 }
1752}
1753
Chris Lattner22eb9722006-06-18 05:43:12 +00001754/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001755/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1756/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001757///
Chris Lattner81278c62006-10-14 19:03:49 +00001758void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1759 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001760 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001761
Chris Lattner22eb9722006-06-18 05:43:12 +00001762 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001763 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001764
1765 // Error reading macro name? If so, diagnostic already issued.
1766 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001767 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00001768
Chris Lattner457fc152006-07-29 06:30:25 +00001769 // If we are supposed to keep comments in #defines, reenable comment saving
1770 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001771 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001772
Chris Lattner063400e2006-10-14 19:54:15 +00001773 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001774 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001775 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001776
Chris Lattner063400e2006-10-14 19:54:15 +00001777 // If the identifier is an 'other target' macro, clear this bit.
1778 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1779
1780
Chris Lattner22eb9722006-06-18 05:43:12 +00001781 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001782 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001783
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001784 // If this is a function-like macro definition, parse the argument list,
1785 // marking each of the identifiers as being used as macro arguments. Also,
1786 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001787 if (Tok.getKind() == tok::eom) {
1788 // If there is no body to this macro, we have no special handling here.
1789 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001790 // This is a function-like macro definition. Read the argument list.
1791 MI->setIsFunctionLike();
1792 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001793 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001794 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001795 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001796 if (CurLexer->ParsingPreprocessorDirective)
1797 DiscardUntilEndOfDirective();
1798 return;
1799 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001800
Chris Lattner815a1f92006-07-08 20:48:04 +00001801 // Read the first token after the arg list for down below.
1802 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001803 } else if (!Tok.hasLeadingSpace()) {
1804 // C99 requires whitespace between the macro definition and the body. Emit
1805 // a diagnostic for something like "#define X+".
1806 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001807 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001808 } else {
1809 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1810 // one in some cases!
1811 }
1812 } else {
1813 // This is a normal token with leading space. Clear the leading space
1814 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001815 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001816 }
1817
Chris Lattner7e374832006-07-29 03:46:57 +00001818 // If this is a definition of a variadic C99 function-like macro, not using
1819 // the GNU named varargs extension, enabled __VA_ARGS__.
1820
1821 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1822 // This gets unpoisoned where it is allowed.
1823 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1824 if (MI->isC99Varargs())
1825 Ident__VA_ARGS__->setIsPoisoned(false);
1826
Chris Lattner22eb9722006-06-18 05:43:12 +00001827 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00001828 if (MI->isObjectLike()) {
1829 // Object-like macros are very simple, just read their body.
1830 while (Tok.getKind() != tok::eom) {
1831 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001832 // Get the next token of the macro.
1833 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001834 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001835
Chris Lattnera3834342007-07-14 21:54:03 +00001836 } else {
1837 // Otherwise, read the body of a function-like macro. This has to validate
1838 // the # (stringize) operator.
1839 while (Tok.getKind() != tok::eom) {
1840 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001841
Chris Lattnera3834342007-07-14 21:54:03 +00001842 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1843 // parameters in function-like macro expansions.
1844 if (Tok.getKind() != tok::hash) {
1845 // Get the next token of the macro.
1846 LexUnexpandedToken(Tok);
1847 continue;
1848 }
1849
1850 // Get the next token of the macro.
1851 LexUnexpandedToken(Tok);
1852
1853 // Not a macro arg identifier?
1854 if (!Tok.getIdentifierInfo() ||
1855 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1856 Diag(Tok, diag::err_pp_stringize_not_parameter);
1857 delete MI;
1858
1859 // Disable __VA_ARGS__ again.
1860 Ident__VA_ARGS__->setIsPoisoned(true);
1861 return;
1862 }
1863
1864 // Things look ok, add the param name token to the macro.
1865 MI->AddTokenToBody(Tok);
1866
1867 // Get the next token of the macro.
1868 LexUnexpandedToken(Tok);
1869 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001870 }
Chris Lattner7e374832006-07-29 03:46:57 +00001871
Chris Lattnerf40fe992007-07-14 22:11:41 +00001872
Chris Lattner7e374832006-07-29 03:46:57 +00001873 // Disable __VA_ARGS__ again.
1874 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001875
Chris Lattnerbff18d52006-07-06 04:49:18 +00001876 // Check that there is no paste (##) operator at the begining or end of the
1877 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001878 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001879 if (NumTokens != 0) {
1880 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001881 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001882 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001883 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001884 }
1885 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001886 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001887 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001888 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001889 }
1890 }
1891
Chris Lattner13044d92006-07-03 05:16:44 +00001892 // If this is the primary source file, remember that this macro hasn't been
1893 // used yet.
1894 if (isInPrimaryFile())
1895 MI->setIsUsed(false);
1896
Chris Lattner22eb9722006-06-18 05:43:12 +00001897 // Finally, if this identifier already had a macro defined for it, verify that
1898 // the macro bodies are identical and free the old definition.
1899 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001900 if (!OtherMI->isUsed())
1901 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1902
Chris Lattner22eb9722006-06-18 05:43:12 +00001903 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001904 // must be the same. C99 6.10.3.2.
1905 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001906 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1907 MacroNameTok.getIdentifierInfo()->getName());
1908 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1909 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001910 delete OtherMI;
1911 }
1912
1913 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001914}
1915
Chris Lattner063400e2006-10-14 19:54:15 +00001916/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1917void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1918 LexerToken MacroNameTok;
1919 ReadMacroName(MacroNameTok, 1);
1920
1921 // Error reading macro name? If so, diagnostic already issued.
1922 if (MacroNameTok.getKind() == tok::eom)
1923 return;
1924
1925 // Check to see if this is the last token on the #undef line.
1926 CheckEndOfDirective("#define_other_target");
1927
1928 // If there is already a macro defined by this name, turn it into a
1929 // target-specific define.
1930 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1931 MI->setIsTargetSpecific(true);
1932 return;
1933 }
1934
1935 // Mark the identifier as being a macro on some other target.
1936 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1937}
1938
Chris Lattner22eb9722006-06-18 05:43:12 +00001939
1940/// HandleUndefDirective - Implements #undef.
1941///
Chris Lattnercb283342006-06-18 06:48:37 +00001942void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001943 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001944
Chris Lattner22eb9722006-06-18 05:43:12 +00001945 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001946 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001947
1948 // Error reading macro name? If so, diagnostic already issued.
1949 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001950 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001951
1952 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001953 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001954
1955 // Okay, we finally have a valid identifier to undef.
1956 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1957
Chris Lattner063400e2006-10-14 19:54:15 +00001958 // #undef untaints an identifier if it were marked by define_other_target.
1959 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1960
Chris Lattner22eb9722006-06-18 05:43:12 +00001961 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001962 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001963
Chris Lattner13044d92006-07-03 05:16:44 +00001964 if (!MI->isUsed())
1965 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001966
1967 // Free macro definition.
1968 delete MI;
1969 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001970}
1971
1972
Chris Lattnerb8761832006-06-24 21:31:03 +00001973//===----------------------------------------------------------------------===//
1974// Preprocessor Conditional Directive Handling.
1975//===----------------------------------------------------------------------===//
1976
Chris Lattner22eb9722006-06-18 05:43:12 +00001977/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001978/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1979/// if any tokens have been returned or pp-directives activated before this
1980/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001981///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001982void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1983 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001984 ++NumIf;
1985 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001986
Chris Lattner22eb9722006-06-18 05:43:12 +00001987 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001988 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001989
1990 // Error reading macro name? If so, diagnostic already issued.
1991 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001992 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001993
1994 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001995 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1996
1997 // If the start of a top-level #ifdef, inform MIOpt.
1998 if (!ReadAnyTokensBeforeDirective &&
1999 CurLexer->getConditionalStackDepth() == 0) {
2000 assert(isIfndef && "#ifdef shouldn't reach here");
2001 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2002 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002003
Chris Lattner063400e2006-10-14 19:54:15 +00002004 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2005 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00002006
Chris Lattner81278c62006-10-14 19:03:49 +00002007 // If there is a macro, process it.
2008 if (MI) {
2009 // Mark it used.
2010 MI->setIsUsed(true);
2011
2012 // If this is the first use of a target-specific macro, warn about it.
2013 if (MI->isTargetSpecific()) {
2014 MI->setIsTargetSpecific(false); // Don't warn on second use.
2015 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2016 diag::port_target_macro_use);
2017 }
Chris Lattner063400e2006-10-14 19:54:15 +00002018 } else {
2019 // Use of a target-specific macro for some other target? If so, warn.
2020 if (MII->isOtherTargetMacro()) {
2021 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2022 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2023 diag::port_target_macro_use);
2024 }
Chris Lattner81278c62006-10-14 19:03:49 +00002025 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002026
Chris Lattner22eb9722006-06-18 05:43:12 +00002027 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002028 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002029 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002030 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002031 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002032 } else {
2033 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002034 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002035 /*Foundnonskip*/false,
2036 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002037 }
2038}
2039
2040/// HandleIfDirective - Implements the #if directive.
2041///
Chris Lattnera8654ca2006-07-04 17:42:08 +00002042void Preprocessor::HandleIfDirective(LexerToken &IfToken,
2043 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002044 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002045
Chris Lattner371ac8a2006-07-04 07:11:10 +00002046 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002047 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002048 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002049
2050 // Should we include the stuff contained by this directive?
2051 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002052 // If this condition is equivalent to #ifndef X, and if this is the first
2053 // directive seen, handle it for the multiple-include optimization.
2054 if (!ReadAnyTokensBeforeDirective &&
2055 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2056 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2057
Chris Lattner22eb9722006-06-18 05:43:12 +00002058 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002059 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002060 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002061 } else {
2062 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002063 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002064 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002065 }
2066}
2067
2068/// HandleEndifDirective - Implements the #endif directive.
2069///
Chris Lattnercb283342006-06-18 06:48:37 +00002070void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002071 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002072
Chris Lattner22eb9722006-06-18 05:43:12 +00002073 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002074 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002075
2076 PPConditionalInfo CondInfo;
2077 if (CurLexer->popConditionalLevel(CondInfo)) {
2078 // No conditionals on the stack: this is an #endif without an #if.
2079 return Diag(EndifToken, diag::err_pp_endif_without_if);
2080 }
2081
Chris Lattner371ac8a2006-07-04 07:11:10 +00002082 // If this the end of a top-level #endif, inform MIOpt.
2083 if (CurLexer->getConditionalStackDepth() == 0)
2084 CurLexer->MIOpt.ExitTopLevelConditional();
2085
Chris Lattner538d7f32006-07-20 04:31:52 +00002086 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002087 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002088}
2089
2090
Chris Lattnercb283342006-06-18 06:48:37 +00002091void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002092 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002093
Chris Lattner22eb9722006-06-18 05:43:12 +00002094 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002095 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002096
2097 PPConditionalInfo CI;
2098 if (CurLexer->popConditionalLevel(CI))
2099 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002100
2101 // If this is a top-level #else, inform the MIOpt.
2102 if (CurLexer->getConditionalStackDepth() == 0)
2103 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002104
2105 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002106 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002107
2108 // Finally, skip the rest of the contents of this block and return the first
2109 // token after it.
2110 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2111 /*FoundElse*/true);
2112}
2113
Chris Lattnercb283342006-06-18 06:48:37 +00002114void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002115 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002116
Chris Lattner22eb9722006-06-18 05:43:12 +00002117 // #elif directive in a non-skipping conditional... start skipping.
2118 // We don't care what the condition is, because we will always skip it (since
2119 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002120 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002121
2122 PPConditionalInfo CI;
2123 if (CurLexer->popConditionalLevel(CI))
2124 return Diag(ElifToken, diag::pp_err_elif_without_if);
2125
Chris Lattner371ac8a2006-07-04 07:11:10 +00002126 // If this is a top-level #elif, inform the MIOpt.
2127 if (CurLexer->getConditionalStackDepth() == 0)
2128 CurLexer->MIOpt.FoundTopLevelElse();
2129
Chris Lattner22eb9722006-06-18 05:43:12 +00002130 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002131 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002132
2133 // Finally, skip the rest of the contents of this block and return the first
2134 // token after it.
2135 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2136 /*FoundElse*/CI.FoundElse);
2137}
Chris Lattnerb8761832006-06-24 21:31:03 +00002138