blob: c3fd55426469e1adda9f984375c548332a07cc83 [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 Lattner8a7003c2007-07-16 06:48:38 +000039#include "llvm/Support/MemoryBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000040#include <iostream>
Chris Lattner22eb9722006-06-18 05:43:12 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
44
Chris Lattner02dffbd2006-10-14 07:50:21 +000045Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000046 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000047 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000048 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
49 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000050 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000051 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000052
Chris Lattner22eb9722006-06-18 05:43:12 +000053 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000054 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000055 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000056 NumEnteredSourceFiles = 0;
57 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000058 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000059 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000061
62 // Default to discarding comments.
63 KeepComments = false;
64 KeepMacroComments = false;
65
Chris Lattner22eb9722006-06-18 05:43:12 +000066 // Macro expansion is enabled.
67 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000068 InMacroArgs = false;
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000069 NumCachedMacroExpanders = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000070
Chris Lattner8ff71992006-07-06 05:17:39 +000071 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
72 // This gets unpoisoned where it is allowed.
73 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
74
Chris Lattnerb8761832006-06-24 21:31:03 +000075 // Initialize the pragma handlers.
76 PragmaHandlers = new PragmaNamespace(0);
77 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000078
79 // Initialize builtin macros like __LINE__ and friends.
80 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000081}
82
83Preprocessor::~Preprocessor() {
84 // Free any active lexers.
85 delete CurLexer;
86
Chris Lattner69772b02006-07-02 20:34:39 +000087 while (!IncludeMacroStack.empty()) {
88 delete IncludeMacroStack.back().TheLexer;
89 delete IncludeMacroStack.back().TheMacroExpander;
90 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000091 }
Chris Lattnerb8761832006-06-24 21:31:03 +000092
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000093 // Free any cached macro expanders.
94 for (unsigned i = 0, e = NumCachedMacroExpanders; i != e; ++i)
95 delete MacroExpanderCache[i];
96
Chris Lattnerb8761832006-06-24 21:31:03 +000097 // Release pragma information.
98 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000099
100 // Delete the scratch buffer info.
101 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +0000102}
103
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000104PPCallbacks::~PPCallbacks() {
105}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000106
Chris Lattner22eb9722006-06-18 05:43:12 +0000107/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
108/// the specified LexerToken's location, translating the token's start
109/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattner36982e42007-05-16 17:49:37 +0000110void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
111 Diags.Report(Loc, DiagID);
112}
113
Chris Lattnercb283342006-06-18 06:48:37 +0000114void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000115 const std::string &Msg) {
Chris Lattner36982e42007-05-16 17:49:37 +0000116 Diags.Report(Loc, DiagID, &Msg, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000117}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000118
119void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
120 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
121 << getSpelling(Tok) << "'";
122
123 if (!DumpFlags) return;
124 std::cerr << "\t";
125 if (Tok.isAtStartOfLine())
126 std::cerr << " [StartOfLine]";
127 if (Tok.hasLeadingSpace())
128 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000129 if (Tok.isExpandDisabled())
130 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000131 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000132 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000133 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
134 << "']";
135 }
136}
137
138void Preprocessor::DumpMacro(const MacroInfo &MI) const {
139 std::cerr << "MACRO: ";
140 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
141 DumpToken(MI.getReplacementToken(i));
142 std::cerr << " ";
143 }
144 std::cerr << "\n";
145}
146
Chris Lattner22eb9722006-06-18 05:43:12 +0000147void Preprocessor::PrintStats() {
148 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000149 std::cerr << NumDirectives << " directives found:\n";
150 std::cerr << " " << NumDefined << " #define.\n";
151 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000152 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000153 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
154 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
155 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
156 std::cerr << " " << NumElse << " #else/#elif.\n";
157 std::cerr << " " << NumEndif << " #endif.\n";
158 std::cerr << " " << NumPragma << " #pragma.\n";
159 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
160
Chris Lattner78186052006-07-09 00:45:31 +0000161 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
162 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000163 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000164 std::cerr << (NumFastTokenPaste+NumTokenPaste)
165 << " token paste (##) operations performed, "
166 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000167}
168
169//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000170// Token Spelling
171//===----------------------------------------------------------------------===//
172
173
174/// getSpelling() - Return the 'spelling' of this token. The spelling of a
175/// token are the characters used to represent the token in the source file
176/// after trigraph expansion and escaped-newline folding. In particular, this
177/// wants to get the true, uncanonicalized, spelling of things like digraphs
178/// UCNs, etc.
179std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
180 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
181
182 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000183 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000184 if (!Tok.needsCleaning())
185 return std::string(TokStart, TokStart+Tok.getLength());
186
Chris Lattnerd01e2912006-06-18 16:22:51 +0000187 std::string Result;
188 Result.reserve(Tok.getLength());
189
Chris Lattneref9eae12006-07-04 22:33:12 +0000190 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000191 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
192 Ptr != End; ) {
193 unsigned CharSize;
194 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
195 Ptr += CharSize;
196 }
197 assert(Result.size() != unsigned(Tok.getLength()) &&
198 "NeedsCleaning flag set on something that didn't need cleaning!");
199 return Result;
200}
201
202/// getSpelling - This method is used to get the spelling of a token into a
203/// preallocated buffer, instead of as an std::string. The caller is required
204/// to allocate enough space for the token, which is guaranteed to be at least
205/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000206///
207/// Note that this method may do two possible things: it may either fill in
208/// the buffer specified with characters, or it may *change the input pointer*
209/// to point to a constant buffer with the data already in it (avoiding a
210/// copy). The caller is not allowed to modify the returned buffer pointer
211/// if an internal buffer is returned.
212unsigned Preprocessor::getSpelling(const LexerToken &Tok,
213 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000214 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
215
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000216 // If this token is an identifier, just return the string from the identifier
217 // table, which is very quick.
218 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
219 Buffer = II->getName();
220 return Tok.getLength();
221 }
222
223 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000224 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225
226 // If this token contains nothing interesting, return it directly.
227 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000228 Buffer = TokStart;
229 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000230 }
231 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000232 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000233 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
234 Ptr != End; ) {
235 unsigned CharSize;
236 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
237 Ptr += CharSize;
238 }
239 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
240 "NeedsCleaning flag set on something that didn't need cleaning!");
241
242 return OutBuf-Buffer;
243}
244
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000245
246/// CreateString - Plop the specified string into a scratch buffer and return a
247/// location for it. If specified, the source location provides a source
248/// location for the token.
249SourceLocation Preprocessor::
250CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
251 if (SLoc.isValid())
252 return ScratchBuf->getToken(Buf, Len, SLoc);
253 return ScratchBuf->getToken(Buf, Len);
254}
255
256
Chris Lattner8a7003c2007-07-16 06:48:38 +0000257/// AdvanceToTokenCharacter - Given a location that specifies the start of a
258/// token, return a new location that specifies a character within the token.
259SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
260 unsigned CharNo) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000261 // If they request the first char of the token, we're trivially done. If this
262 // is a macro expansion, it doesn't make sense to point to a character within
263 // the instantiation point (the name). We could point to the source
264 // character, but without also pointing to instantiation info, this is
265 // confusing.
266 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000267
268 // Figure out how many physical characters away the specified logical
269 // character is. This needs to take into consideration newlines and
270 // trigraphs.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000271 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
272 unsigned PhysOffset = 0;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000273
274 // The usual case is that tokens don't contain anything interesting. Skip
275 // over the uninteresting characters. If a token only consists of simple
276 // chars, this method is extremely fast.
277 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000278 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000279
280 // If we have a character that may be a trigraph or escaped newline, create a
281 // lexer to parse it correctly.
Chris Lattner8a7003c2007-07-16 06:48:38 +0000282 if (CharNo != 0) {
283 // Create a lexer starting at this token position.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000284 const llvm::MemoryBuffer *SrcBuf =SourceMgr.getBuffer(TokStart.getFileID());
285 Lexer TheLexer(SrcBuf, TokStart, *this, TokPtr);
Chris Lattner8a7003c2007-07-16 06:48:38 +0000286 LexerToken Tok;
287 // Skip over characters the remaining characters.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000288 const char *TokStartPtr = TokPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000289 for (; CharNo; --CharNo)
290 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000291
292 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000293 }
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000294
295 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner8a7003c2007-07-16 06:48:38 +0000296}
297
298
299
Chris Lattnerd01e2912006-06-18 16:22:51 +0000300//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000301// Source File Location Methods.
302//===----------------------------------------------------------------------===//
303
Chris Lattner22eb9722006-06-18 05:43:12 +0000304/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
305/// return null on failure. isAngled indicates whether the file reference is
306/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000307const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
308 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000309 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000310 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000311 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000312 // If the header lookup mechanism may be relative to the current file, pass in
313 // info about where the current file is.
314 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000315 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000316 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
317 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000318 }
319
Chris Lattner63dd32b2006-10-20 04:42:40 +0000320 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000321 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000322 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000323 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
324 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000325 if (FE) return FE;
326
327 // Otherwise, see if this is a subframework header. If so, this is relative
328 // to one of the headers on the #include stack. Walk the list of the current
329 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000330 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000331 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000332 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
333 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000334 return FE;
335 }
336
337 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
338 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000339 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000340 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000341 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
342 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000343 return FE;
344 }
345 }
346
347 // Otherwise, we really couldn't find the file.
348 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000349}
350
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000351/// isInPrimaryFile - Return true if we're in the top-level file, not in a
352/// #include.
353bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000354 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000355 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000356
Chris Lattner13044d92006-07-03 05:16:44 +0000357 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000358 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000359 if (IncludeMacroStack[i].TheLexer &&
360 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
361 return IncludeMacroStack[i].TheLexer->isMainFile();
362 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000363}
364
365/// getCurrentLexer - Return the current file lexer being lexed from. Note
366/// that this ignores any potentially active macro expansions and _Pragma
367/// expansions going on at the time.
368Lexer *Preprocessor::getCurrentFileLexer() const {
369 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
370
371 // Look for a stacked lexer.
372 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000373 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000374 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
375 return L;
376 }
377 return 0;
378}
379
380
Chris Lattner22eb9722006-06-18 05:43:12 +0000381/// EnterSourceFile - Add a source file to the top of the include stack and
382/// start lexing tokens from it instead of the current buffer. Return true
383/// on failure.
384void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000385 const DirectoryLookup *CurDir,
386 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000387 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000388 ++NumEnteredSourceFiles;
389
Chris Lattner69772b02006-07-02 20:34:39 +0000390 if (MaxIncludeStackDepth < IncludeMacroStack.size())
391 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000392
Chris Lattner23b7eb62007-06-15 23:05:46 +0000393 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000394 Lexer *TheLexer = new Lexer(Buffer, SourceLocation::getFileLoc(FileID, 0),
395 *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000396 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000397 EnterSourceFileWithLexer(TheLexer, CurDir);
398}
Chris Lattner22eb9722006-06-18 05:43:12 +0000399
Chris Lattner69772b02006-07-02 20:34:39 +0000400/// EnterSourceFile - Add a source file to the top of the include stack and
401/// start lexing tokens from it instead of the current buffer.
402void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
403 const DirectoryLookup *CurDir) {
404
405 // Add the current lexer to the include stack.
406 if (CurLexer || CurMacroExpander)
407 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
408 CurMacroExpander));
409
410 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000411 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000412 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000413
414 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000415 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000416 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
417
418 // Get the file entry for the current file.
419 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000420 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000421 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000422
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000423 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000424 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000425 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000426}
427
Chris Lattner69772b02006-07-02 20:34:39 +0000428
429
Chris Lattner22eb9722006-06-18 05:43:12 +0000430/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000431/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000432void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000433 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
434 CurMacroExpander));
435 CurLexer = 0;
436 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000437
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000438 if (NumCachedMacroExpanders == 0) {
439 CurMacroExpander = new MacroExpander(Tok, Args, *this);
440 } else {
441 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
442 CurMacroExpander->Init(Tok, Args);
443 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000444}
445
Chris Lattner7667d0d2006-07-16 18:16:58 +0000446/// EnterTokenStream - Add a "macro" context to the top of the include stack,
447/// which will cause the lexer to start returning the specified tokens. Note
448/// that these tokens will be re-macro-expanded when/if expansion is enabled.
449/// This method assumes that the specified stream of tokens has a permanent
450/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000451void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000452 // Save our current state.
453 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
454 CurMacroExpander));
455 CurLexer = 0;
456 CurDirLookup = 0;
457
458 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000459 if (NumCachedMacroExpanders == 0) {
460 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
461 } else {
462 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
463 CurMacroExpander->Init(Toks, NumToks);
464 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000465}
466
467/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
468/// lexer stack. This should only be used in situations where the current
469/// state of the top-of-stack lexer is known.
470void Preprocessor::RemoveTopOfLexerStack() {
471 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000472
473 if (CurMacroExpander) {
474 // Delete or cache the now-dead macro expander.
475 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
476 delete CurMacroExpander;
477 else
478 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
479 } else {
480 delete CurLexer;
481 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000482 CurLexer = IncludeMacroStack.back().TheLexer;
483 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
484 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
485 IncludeMacroStack.pop_back();
486}
487
Chris Lattner22eb9722006-06-18 05:43:12 +0000488//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000489// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000490//===----------------------------------------------------------------------===//
491
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000492/// RegisterBuiltinMacro - Register the specified identifier in the identifier
493/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000494IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000495 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000496 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000497
498 // Mark it as being a macro that is builtin.
499 MacroInfo *MI = new MacroInfo(SourceLocation());
500 MI->setIsBuiltinMacro();
501 Id->setMacroInfo(MI);
502 return Id;
503}
504
505
Chris Lattner677757a2006-06-28 05:26:32 +0000506/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
507/// identifier table.
508void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000509 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000510 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000511 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
512 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000513 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000514
515 // GCC Extensions.
516 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
517 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000518 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000519}
520
Chris Lattnerc2395832006-07-09 00:57:04 +0000521/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
522/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000523static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
524 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000525 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
526
527 // If the token isn't an identifier, it's always literally expanded.
528 if (II == 0) return true;
529
530 // If the identifier is a macro, and if that macro is enabled, it may be
531 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000532 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
533 // Fast expanding "#define X X" is ok, because X would be disabled.
534 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000535 return false;
536
537 // If this is an object-like macro invocation, it is safe to trivially expand
538 // it.
539 if (MI->isObjectLike()) return true;
540
541 // If this is a function-like macro invocation, it's safe to trivially expand
542 // as long as the identifier is not a macro argument.
543 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
544 I != E; ++I)
545 if (*I == II)
546 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000547
Chris Lattnerc2395832006-07-09 00:57:04 +0000548 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000549}
550
Chris Lattnerc2395832006-07-09 00:57:04 +0000551
Chris Lattnerafe603f2006-07-11 04:02:46 +0000552/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
553/// lexed is a '('. If so, consume the token and return true, if not, this
554/// method should have no observable side-effect on the lexed tokens.
555bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000556 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000557 unsigned Val;
558 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000559 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000560 else
561 Val = CurMacroExpander->isNextTokenLParen();
562
563 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000564 // We have run off the end. If it's a source file we don't
565 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
566 // macro stack.
567 if (CurLexer)
568 return false;
569 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000570 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
571 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000572 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000573 else
574 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000575
576 if (Val != 2)
577 break;
578
579 // Ran off the end of a source file?
580 if (Entry.TheLexer)
581 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000582 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000583 }
584
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000585 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
586 // have found something that isn't a '(' or we found the end of the
587 // translation unit. In either case, return false.
588 if (Val != 1)
589 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000590
591 LexerToken Tok;
592 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000593 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
594 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000595}
Chris Lattner677757a2006-06-28 05:26:32 +0000596
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000597/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
598/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000599bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000600 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000601
602 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
603 if (MI->isBuiltinMacro()) {
604 ExpandBuiltinMacro(Identifier);
605 return false;
606 }
607
Chris Lattner81278c62006-10-14 19:03:49 +0000608 // If this is the first use of a target-specific macro, warn about it.
609 if (MI->isTargetSpecific()) {
610 MI->setIsTargetSpecific(false); // Don't warn on second use.
611 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
612 diag::port_target_macro_use);
613 }
614
Chris Lattneree8760b2006-07-15 07:42:55 +0000615 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000616 /// for each macro argument, the list of tokens that were provided to the
617 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000618 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000619
620 // If this is a function-like macro, read the arguments.
621 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000622 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000623 // name isn't a '(', this macro should not be expanded. Otherwise, consume
624 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000625 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000626 return true;
627
Chris Lattner78186052006-07-09 00:45:31 +0000628 // Remember that we are now parsing the arguments to a macro invocation.
629 // Preprocessor directives used inside macro arguments are not portable, and
630 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000631 InMacroArgs = true;
632 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000633
634 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000635 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000636
637 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000638 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000639
640 ++NumFnMacroExpanded;
641 } else {
642 ++NumMacroExpanded;
643 }
Chris Lattner13044d92006-07-03 05:16:44 +0000644
645 // Notice that this macro has been used.
646 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000647
648 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000649
650 // If this macro expands to no tokens, don't bother to push it onto the
651 // expansion stack, only to take it right back off.
652 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000653 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000654 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000655
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000656 // Ignore this macro use, just return the next token in the current
657 // buffer.
658 bool HadLeadingSpace = Identifier.hasLeadingSpace();
659 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
660
661 Lex(Identifier);
662
663 // If the identifier isn't on some OTHER line, inherit the leading
664 // whitespace/first-on-a-line property of this token. This handles
665 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
666 // empty.
667 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000668 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
669 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000670 }
671 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000672 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000673
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000674 } else if (MI->getNumTokens() == 1 &&
675 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000676 // Otherwise, if this macro expands into a single trivially-expanded
677 // token: expand it now. This handles common cases like
678 // "#define VAL 42".
679
680 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
681 // identifier to the expanded token.
682 bool isAtStartOfLine = Identifier.isAtStartOfLine();
683 bool hasLeadingSpace = Identifier.hasLeadingSpace();
684
685 // Remember where the token is instantiated.
686 SourceLocation InstantiateLoc = Identifier.getLocation();
687
688 // Replace the result token.
689 Identifier = MI->getReplacementToken(0);
690
691 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000692 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
693 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000694
695 // Update the tokens location to include both its logical and physical
696 // locations.
697 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000698 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000699 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000700
Chris Lattner6e4bf522006-07-27 06:59:25 +0000701 // If this is #define X X, we must mark the result as unexpandible.
702 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
703 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000704 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000705
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000706 // Since this is not an identifier token, it can't be macro expanded, so
707 // we're done.
708 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000709 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000710 }
711
Chris Lattner78186052006-07-09 00:45:31 +0000712 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000713 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000714
715 // Now that the macro is at the top of the include stack, ask the
716 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000717 Lex(Identifier);
718 return false;
719}
720
Chris Lattneree8760b2006-07-15 07:42:55 +0000721/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000722/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000723/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000724MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
725 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000726 // The number of fixed arguments to parse.
727 unsigned NumFixedArgsLeft = MI->getNumArgs();
728 bool isVariadic = MI->isVariadic();
729
Chris Lattner78186052006-07-09 00:45:31 +0000730 // Outer loop, while there are more arguments, keep reading them.
731 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000732 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000733 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000734
735 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000736 // argument is separated by an EOF token. Use a SmallVector so we can avoid
737 // heap allocations in the common case.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000738 llvm::SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000739
740 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000741 while (Tok.getKind() == tok::comma) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000742 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
743 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000744 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000745
Chris Lattner78186052006-07-09 00:45:31 +0000746 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000747 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
748 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000749 LexUnexpandedToken(Tok);
750
751 if (Tok.getKind() == tok::eof) {
752 Diag(MacroName, diag::err_unterm_macro_invoc);
753 // Do not lose the EOF. Return it to the client.
754 MacroName = Tok;
755 return 0;
756 } else if (Tok.getKind() == tok::r_paren) {
757 // If we found the ) token, the macro arg list is done.
758 if (NumParens-- == 0)
759 break;
760 } else if (Tok.getKind() == tok::l_paren) {
761 ++NumParens;
762 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
763 // Comma ends this argument if there are more fixed arguments expected.
764 if (NumFixedArgsLeft)
765 break;
766
Chris Lattner2ada5d32006-07-15 07:51:24 +0000767 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000768 if (!isVariadic) {
769 // Emit the diagnostic at the macro name in case there is a missing ).
770 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000771 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000772 return 0;
773 }
774 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000775 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000776 // If this is a comment token in the argument list and we're just in
777 // -C mode (not -CC mode), discard the comment.
778 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000779 }
780
781 ArgTokens.push_back(Tok);
782 }
783
Chris Lattnera12dd152006-07-11 04:09:02 +0000784 // Empty arguments are standard in C99 and supported as an extension in
785 // other modes.
786 if (ArgTokens.empty() && !Features.C99)
787 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000788
Chris Lattner36b6e812006-07-21 06:38:30 +0000789 // Add a marker EOF token to the end of the token list for this argument.
790 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000791 EOFTok.startToken();
792 EOFTok.setKind(tok::eof);
793 EOFTok.setLocation(Tok.getLocation());
794 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000795 ArgTokens.push_back(EOFTok);
796 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000797 --NumFixedArgsLeft;
798 };
799
800 // Okay, we either found the r_paren. Check to see if we parsed too few
801 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000802 unsigned MinArgsExpected = MI->getNumArgs();
803
Chris Lattner775d8322006-07-29 04:39:41 +0000804 // See MacroArgs instance var for description of this.
805 bool isVarargsElided = false;
806
Chris Lattner2ada5d32006-07-15 07:51:24 +0000807 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000808 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000809 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000810 // Varargs where the named vararg parameter is missing: ok as extension.
811 // #define A(x, ...)
812 // A("blah")
813 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000814
815 // Remember this occurred if this is a C99 macro invocation with at least
816 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000817 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000818 } else if (MI->getNumArgs() == 1) {
819 // #define A(x)
820 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000821 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000822
823 // Empty arguments are standard in C99 and supported as an extension in
824 // other modes.
825 if (ArgTokens.empty() && !Features.C99)
826 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000827 } else {
828 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000829 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000830 return 0;
831 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000832
833 // Add a marker EOF token to the end of the token list for this argument.
834 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000835 Tok.startToken();
836 Tok.setKind(tok::eof);
837 Tok.setLocation(EndLoc);
838 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000839 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000840 }
841
Chris Lattner775d8322006-07-29 04:39:41 +0000842 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000843}
844
Chris Lattnerc673f902006-06-30 06:10:41 +0000845/// ComputeDATE_TIME - Compute the current time, enter it into the specified
846/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
847/// the identifier tokens inserted.
848static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000849 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000850 time_t TT = time(0);
851 struct tm *TM = localtime(&TT);
852
853 static const char * const Months[] = {
854 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
855 };
856
857 char TmpBuffer[100];
858 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
859 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000860 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000861
862 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000863 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000864}
865
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000866/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
867/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000868void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000869 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000870 IdentifierInfo *II = Tok.getIdentifierInfo();
871 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000872
873 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
874 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000875 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000876 return Handle_Pragma(Tok);
877
Chris Lattner78186052006-07-09 00:45:31 +0000878 ++NumBuiltinMacroExpanded;
879
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000880 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000881
882 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000883 Tok.setIdentifierInfo(0);
884 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000885
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000886 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000887 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000888 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000889 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000890 Tok.setKind(tok::numeric_constant);
891 Tok.setLength(Length);
892 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000893 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000894 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000895 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000896 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000897 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
898 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000899 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000900 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +0000901 }
902 }
903
Chris Lattner0766e592006-07-03 01:07:01 +0000904 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000905 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +0000906 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000907 Tok.setKind(tok::string_literal);
908 Tok.setLength(FN.size());
909 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000910 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000911 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000912 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000913 Tok.setKind(tok::string_literal);
914 Tok.setLength(strlen("\"Mmm dd yyyy\""));
915 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000916 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000917 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000918 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000919 Tok.setKind(tok::string_literal);
920 Tok.setLength(strlen("\"hh:mm:ss\""));
921 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000922 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000923 Diag(Tok, diag::ext_pp_include_level);
924
925 // Compute the include depth of this token.
926 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000927 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
928 for (; Loc.isValid(); ++Depth)
929 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +0000930
931 // __INCLUDE_LEVEL__ expands to a simple numeric value.
932 sprintf(TmpBuffer, "%u", Depth);
933 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000934 Tok.setKind(tok::numeric_constant);
935 Tok.setLength(Length);
936 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000937 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000938 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
939 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
940 Diag(Tok, diag::ext_pp_timestamp);
941
942 // Get the file that we are lexing out of. If we're currently lexing from
943 // a macro, dig into the include stack.
944 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000945 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000946
947 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000948 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +0000949
950 // If this file is older than the file it depends on, emit a diagnostic.
951 const char *Result;
952 if (CurFile) {
953 time_t TT = CurFile->getModificationTime();
954 struct tm *TM = localtime(&TT);
955 Result = asctime(TM);
956 } else {
957 Result = "??? ??? ?? ??:??:?? ????\n";
958 }
959 TmpBuffer[0] = '"';
960 strcpy(TmpBuffer+1, Result);
961 unsigned Len = strlen(TmpBuffer);
962 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000963 Tok.setKind(tok::string_literal);
964 Tok.setLength(Len);
965 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000966 } else {
967 assert(0 && "Unknown identifier!");
968 }
969}
Chris Lattner677757a2006-06-28 05:26:32 +0000970
971//===----------------------------------------------------------------------===//
972// Lexer Event Handling.
973//===----------------------------------------------------------------------===//
974
Chris Lattnercefc7682006-07-08 08:28:12 +0000975/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
976/// identifier information for the token and install it into the token.
977IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
978 const char *BufPtr) {
979 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
980 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
981
982 // Look up this token, see if it is a macro, or if it is a language keyword.
983 IdentifierInfo *II;
984 if (BufPtr && !Identifier.needsCleaning()) {
985 // No cleaning needed, just use the characters from the lexed buffer.
986 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
987 } else {
988 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +0000989 llvm::SmallVector<char, 64> IdentifierBuffer;
990 IdentifierBuffer.resize(Identifier.getLength());
991 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +0000992 unsigned Size = getSpelling(Identifier, TmpBuf);
993 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
994 }
Chris Lattner8c204872006-10-14 05:19:21 +0000995 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000996 return II;
997}
998
999
Chris Lattner677757a2006-06-28 05:26:32 +00001000/// HandleIdentifier - This callback is invoked when the lexer reads an
1001/// identifier. This callback looks up the identifier in the map and/or
1002/// potentially macro expands it or turns it into a named token (like 'for').
1003void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001004 assert(Identifier.getIdentifierInfo() &&
1005 "Can't handle identifiers without identifier info!");
1006
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001007 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001008
1009 // If this identifier was poisoned, and if it was not produced from a macro
1010 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001011 if (II.isPoisoned() && CurLexer) {
1012 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1013 Diag(Identifier, diag::err_pp_used_poisoned_id);
1014 else
1015 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1016 }
Chris Lattner677757a2006-06-28 05:26:32 +00001017
Chris Lattner78186052006-07-09 00:45:31 +00001018 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +00001019 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001020 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1021 if (MI->isEnabled()) {
1022 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1023 return;
1024 } else {
1025 // C99 6.10.3.4p2 says that a disabled macro may never again be
1026 // expanded, even if it's in a context where it could be expanded in the
1027 // future.
Chris Lattner8c204872006-10-14 05:19:21 +00001028 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001029 }
1030 }
Chris Lattner063400e2006-10-14 19:54:15 +00001031 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1032 // If this identifier is a macro on some other target, emit a diagnostic.
1033 // This diagnosic is only emitted when macro expansion is enabled, because
1034 // the macro would not have been expanded for the other target either.
1035 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1036 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1037 diag::port_target_macro_use);
1038
1039 }
Chris Lattner677757a2006-06-28 05:26:32 +00001040
Chris Lattner5b9f4892006-11-21 17:23:33 +00001041 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1042 // then we act as if it is the actual operator and not the textual
1043 // representation of it.
1044 if (II.isCPlusPlusOperatorKeyword())
1045 Identifier.setIdentifierInfo(0);
1046
Chris Lattner677757a2006-06-28 05:26:32 +00001047 // Change the kind of this identifier to the appropriate token kind, e.g.
1048 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001049 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001050
1051 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001052 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1053 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001054 if (II.isExtensionToken() && Features.C99)
1055 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001056}
1057
Chris Lattner22eb9722006-06-18 05:43:12 +00001058/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1059/// the current file. This either returns the EOF token or pops a level off
1060/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001061bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001062 assert(!CurMacroExpander &&
1063 "Ending a file when currently in a macro!");
1064
Chris Lattner371ac8a2006-07-04 07:11:10 +00001065 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001066 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001067 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001068 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001069 // Okay, this has a controlling macro, remember in PerFileInfo.
1070 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001071 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001072 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001073 }
1074 }
1075
Chris Lattner22eb9722006-06-18 05:43:12 +00001076 // If this is a #include'd file, pop it off the include stack and continue
1077 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001078 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001079 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001080 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001081
1082 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001083 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001084 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1085
1086 // Get the file entry for the current file.
1087 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001088 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001089 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001090
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001091 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1092 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001093 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001094
1095 // Client should lex another token.
1096 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 }
1098
Chris Lattner8c204872006-10-14 05:19:21 +00001099 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001100 CurLexer->BufferPtr = CurLexer->BufferEnd;
1101 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001102 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001103
1104 // We're done with the #included file.
1105 delete CurLexer;
1106 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001107
Chris Lattner03f83482006-07-10 06:16:26 +00001108 // This is the end of the top-level file. If the diag::pp_macro_not_used
1109 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1110 // have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001111 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1112 for (IdentifierTable::iterator I = Identifiers.begin(),
1113 E = Identifiers.end(); I != E; ++I) {
1114 const IdentifierInfo &II = I->getValue();
1115 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1116 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1117 }
1118 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001119
1120 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001121}
1122
1123/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001124/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001125bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001126 assert(CurMacroExpander && !CurLexer &&
1127 "Ending a macro when currently in a #include file!");
1128
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001129 // Delete or cache the now-dead macro expander.
1130 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1131 delete CurMacroExpander;
1132 else
1133 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001134
Chris Lattner69772b02006-07-02 20:34:39 +00001135 // Handle this like a #include file being popped off the stack.
1136 CurMacroExpander = 0;
1137 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001138}
1139
1140
1141//===----------------------------------------------------------------------===//
1142// Utility Methods for Preprocessor Directive Handling.
1143//===----------------------------------------------------------------------===//
1144
1145/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1146/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001147void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001148 LexerToken Tmp;
1149 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001150 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001151 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001152}
1153
Chris Lattner652c1692006-11-21 23:47:30 +00001154/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1155static bool isCXXNamedOperator(const std::string &Spelling) {
1156 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1157 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1158 Spelling == "or" || Spelling == "xor";
1159}
1160
Chris Lattner22eb9722006-06-18 05:43:12 +00001161/// ReadMacroName - Lex and validate a macro name, which occurs after a
1162/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001163/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1164/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001165/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001166void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001167 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001168 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001169
1170 // Missing macro name?
1171 if (MacroNameTok.getKind() == tok::eom)
1172 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1173
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001174 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1175 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001176 std::string Spelling = getSpelling(MacroNameTok);
1177 if (isCXXNamedOperator(Spelling))
1178 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1179 // except for their spellings.
1180 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1181 else
1182 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001183 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001184 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001185 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001186 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001187 } else if (isDefineUndef && II->getMacroInfo() &&
1188 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001189 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001190 if (isDefineUndef == 1)
1191 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1192 else
1193 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001194 } else {
1195 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001196 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001197 }
1198
Chris Lattner22eb9722006-06-18 05:43:12 +00001199 // Invalid macro name, read and discard the rest of the line. Then set the
1200 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001201 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001202 return DiscardUntilEndOfDirective();
1203}
1204
1205/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1206/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001207void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001208 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001209 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001210 // There should be no tokens after the directive, but we allow them as an
1211 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001212 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1213 Lex(Tmp);
1214
Chris Lattner22eb9722006-06-18 05:43:12 +00001215 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001216 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1217 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001218 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001219}
1220
1221
1222
1223/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1224/// decided that the subsequent tokens are in the #if'd out portion of the
1225/// file. Lex the rest of the file, until we see an #endif. If
1226/// FoundNonSkipPortion is true, then we have already emitted code for part of
1227/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1228/// is true, then #else directives are ok, if not, then we have already seen one
1229/// so a #else directive is a duplicate. When this returns, the caller can lex
1230/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001231void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001232 bool FoundNonSkipPortion,
1233 bool FoundElse) {
1234 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001235 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001236 "Lexing a macro, not a file?");
1237
1238 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1239 FoundNonSkipPortion, FoundElse);
1240
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001241 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1242 // disabling warnings, etc.
1243 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001244 LexerToken Tok;
1245 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001246 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001247
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001248 // If this is the end of the buffer, we have an error.
1249 if (Tok.getKind() == tok::eof) {
1250 // Emit errors for each unterminated conditional on the stack, including
1251 // the current one.
1252 while (!CurLexer->ConditionalStack.empty()) {
1253 Diag(CurLexer->ConditionalStack.back().IfLoc,
1254 diag::err_pp_unterminated_conditional);
1255 CurLexer->ConditionalStack.pop_back();
1256 }
1257
1258 // Just return and let the caller lex after this #include.
1259 break;
1260 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001261
1262 // If this token is not a preprocessor directive, just skip it.
1263 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1264 continue;
1265
1266 // We just parsed a # character at the start of a line, so we're in
1267 // directive mode. Tell the lexer this so any newlines we see will be
1268 // converted into an EOM token (this terminates the macro).
1269 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001270 CurLexer->KeepCommentMode = false;
1271
Chris Lattner22eb9722006-06-18 05:43:12 +00001272
1273 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001274 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001275
1276 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1277 // something bogus), skip it.
1278 if (Tok.getKind() != tok::identifier) {
1279 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001280 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001281 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001282 continue;
1283 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001284
Chris Lattner22eb9722006-06-18 05:43:12 +00001285 // If the first letter isn't i or e, it isn't intesting to us. We know that
1286 // this is safe in the face of spelling differences, because there is no way
1287 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001288 // allows us to avoid looking up the identifier info for #define/#undef and
1289 // other common directives.
1290 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1291 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001292 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1293 FirstChar != 'i' && FirstChar != 'e') {
1294 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001295 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001296 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001297 continue;
1298 }
1299
Chris Lattnere60165f2006-06-22 06:36:29 +00001300 // Get the identifier name without trigraphs or embedded newlines. Note
1301 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1302 // when skipping.
1303 // TODO: could do this with zero copies in the no-clean case by using
1304 // strncmp below.
1305 char Directive[20];
1306 unsigned IdLen;
1307 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1308 IdLen = Tok.getLength();
1309 memcpy(Directive, RawCharData, IdLen);
1310 Directive[IdLen] = 0;
1311 } else {
1312 std::string DirectiveStr = getSpelling(Tok);
1313 IdLen = DirectiveStr.size();
1314 if (IdLen >= 20) {
1315 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001316 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001317 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001318 continue;
1319 }
1320 memcpy(Directive, &DirectiveStr[0], IdLen);
1321 Directive[IdLen] = 0;
1322 }
1323
Chris Lattner22eb9722006-06-18 05:43:12 +00001324 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001325 if ((IdLen == 2) || // "if"
1326 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1327 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001328 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1329 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001330 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001331 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001332 /*foundnonskip*/false,
1333 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001334 }
1335 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001336 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001337 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001338 PPConditionalInfo CondInfo;
1339 CondInfo.WasSkipping = true; // Silence bogus warning.
1340 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001341 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001342 assert(!InCond && "Can't be skipping if not in a conditional!");
1343
1344 // If we popped the outermost skipping block, we're done skipping!
1345 if (!CondInfo.WasSkipping)
1346 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001347 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001348 // #else directive in a skipping conditional. If not in some other
1349 // skipping conditional, and if #else hasn't already been seen, enter it
1350 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001351 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001352 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1353
1354 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001355 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001356
1357 // Note that we've seen a #else in this conditional.
1358 CondInfo.FoundElse = true;
1359
1360 // If the conditional is at the top level, and the #if block wasn't
1361 // entered, enter the #else block now.
1362 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1363 CondInfo.FoundNonSkip = true;
1364 break;
1365 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001366 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001367 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1368
1369 bool ShouldEnter;
1370 // If this is in a skipping block or if we're already handled this #if
1371 // block, don't bother parsing the condition.
1372 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001373 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001374 ShouldEnter = false;
1375 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001376 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001377 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001378 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1379 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001380 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001381 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001382 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001383 }
1384
1385 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001386 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001387
1388 // If this condition is true, enter it!
1389 if (ShouldEnter) {
1390 CondInfo.FoundNonSkip = true;
1391 break;
1392 }
1393 }
1394 }
1395
1396 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001397 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001398 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001399 }
1400
1401 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1402 // of the file, just stop skipping and return to lexing whatever came after
1403 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001404 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001405}
1406
1407//===----------------------------------------------------------------------===//
1408// Preprocessor Directive Handling.
1409//===----------------------------------------------------------------------===//
1410
1411/// HandleDirective - This callback is invoked when the lexer sees a # token
1412/// at the start of a line. This consumes the directive, modifies the
1413/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1414/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001415void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001416 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001417
1418 // We just parsed a # character at the start of a line, so we're in directive
1419 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001420 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001421 CurLexer->ParsingPreprocessorDirective = true;
1422
1423 ++NumDirectives;
1424
Chris Lattner371ac8a2006-07-04 07:11:10 +00001425 // We are about to read a token. For the multiple-include optimization FA to
1426 // work, we have to remember if we had read any tokens *before* this
1427 // pp-directive.
1428 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1429
Chris Lattner78186052006-07-09 00:45:31 +00001430 // Read the next token, the directive flavor. This isn't expanded due to
1431 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001432 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001433
Chris Lattner78186052006-07-09 00:45:31 +00001434 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1435 // #define A(x) #x
1436 // A(abc
1437 // #warning blah
1438 // def)
1439 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001440 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001441 Diag(Result, diag::ext_embedded_directive);
1442
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001443TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001444 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001445 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001446 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001447 case tok::comment:
1448 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1449 LexUnexpandedToken(Result);
1450 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001451
Chris Lattner22eb9722006-06-18 05:43:12 +00001452 case tok::numeric_constant:
1453 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001454 DiscardUntilEndOfDirective();
1455 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001456 default:
1457 IdentifierInfo *II = Result.getIdentifierInfo();
1458 if (II == 0) break; // Not an identifier.
1459
1460 // Ask what the preprocessor keyword ID is.
1461 switch (II->getPPKeywordID()) {
1462 default: break;
1463 // C99 6.10.1 - Conditional Inclusion.
1464 case tok::pp_if:
1465 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1466 case tok::pp_ifdef:
1467 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1468 case tok::pp_ifndef:
1469 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1470 case tok::pp_elif:
1471 return HandleElifDirective(Result);
1472 case tok::pp_else:
1473 return HandleElseDirective(Result);
1474 case tok::pp_endif:
1475 return HandleEndifDirective(Result);
1476
1477 // C99 6.10.2 - Source File Inclusion.
1478 case tok::pp_include:
1479 return HandleIncludeDirective(Result); // Handle #include.
1480
1481 // C99 6.10.3 - Macro Replacement.
1482 case tok::pp_define:
1483 return HandleDefineDirective(Result, false);
1484 case tok::pp_undef:
1485 return HandleUndefDirective(Result);
1486
1487 // C99 6.10.4 - Line Control.
1488 case tok::pp_line:
1489 // FIXME: implement #line
1490 DiscardUntilEndOfDirective();
1491 return;
1492
1493 // C99 6.10.5 - Error Directive.
1494 case tok::pp_error:
1495 return HandleUserDiagnosticDirective(Result, false);
1496
1497 // C99 6.10.6 - Pragma Directive.
1498 case tok::pp_pragma:
1499 return HandlePragmaDirective();
1500
1501 // GNU Extensions.
1502 case tok::pp_import:
1503 return HandleImportDirective(Result);
1504 case tok::pp_include_next:
1505 return HandleIncludeNextDirective(Result);
1506
1507 case tok::pp_warning:
1508 Diag(Result, diag::ext_pp_warning_directive);
1509 return HandleUserDiagnosticDirective(Result, true);
1510 case tok::pp_ident:
1511 return HandleIdentSCCSDirective(Result);
1512 case tok::pp_sccs:
1513 return HandleIdentSCCSDirective(Result);
1514 case tok::pp_assert:
1515 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001516 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001517 case tok::pp_unassert:
1518 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001519 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001520
1521 // clang extensions.
1522 case tok::pp_define_target:
1523 return HandleDefineDirective(Result, true);
1524 case tok::pp_define_other_target:
1525 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001526 }
1527 break;
1528 }
1529
1530 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001531 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001532
1533 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001534 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001535
1536 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001537}
1538
Chris Lattner01d66cc2006-07-03 22:16:27 +00001539void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001540 bool isWarning) {
1541 // Read the rest of the line raw. We do this because we don't want macros
1542 // to be expanded and we don't require that the tokens be valid preprocessing
1543 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1544 // collapse multiple consequtive white space between tokens, but this isn't
1545 // specified by the standard.
1546 std::string Message = CurLexer->ReadToEndOfLine();
1547
1548 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001549 return Diag(Tok, DiagID, Message);
1550}
1551
1552/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1553///
1554void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001555 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001556 Diag(Tok, diag::ext_pp_ident_directive);
1557
Chris Lattner371ac8a2006-07-04 07:11:10 +00001558 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001559 LexerToken StrTok;
1560 Lex(StrTok);
1561
1562 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001563 if (StrTok.getKind() != tok::string_literal &&
1564 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001565 return Diag(StrTok, diag::err_pp_malformed_ident);
1566
1567 // Verify that there is nothing after the string, other than EOM.
1568 CheckEndOfDirective("#ident");
1569
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001570 if (Callbacks)
1571 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001572}
1573
Chris Lattnerb8761832006-06-24 21:31:03 +00001574//===----------------------------------------------------------------------===//
1575// Preprocessor Include Directive Handling.
1576//===----------------------------------------------------------------------===//
1577
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001578/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1579/// checked and spelled filename, e.g. as an operand of #include. This returns
1580/// true if the input filename was in <>'s or false if it were in ""'s. The
1581/// caller is expected to provide a buffer that is large enough to hold the
1582/// spelling of the filename, but is also expected to handle the case when
1583/// this method decides to use a different buffer.
1584bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1585 const char *&BufStart,
1586 const char *&BufEnd) {
1587 // Get the text form of the filename.
1588 unsigned Len = getSpelling(FilenameTok, BufStart);
1589 BufEnd = BufStart+Len;
1590 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1591
1592 // Make sure the filename is <x> or "x".
1593 bool isAngled;
1594 if (BufStart[0] == '<') {
1595 if (BufEnd[-1] != '>') {
1596 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1597 BufStart = 0;
1598 return true;
1599 }
1600 isAngled = true;
1601 } else if (BufStart[0] == '"') {
1602 if (BufEnd[-1] != '"') {
1603 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1604 BufStart = 0;
1605 return true;
1606 }
1607 isAngled = false;
1608 } else {
1609 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1610 BufStart = 0;
1611 return true;
1612 }
1613
1614 // Diagnose #include "" as invalid.
1615 if (BufEnd-BufStart <= 2) {
1616 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1617 BufStart = 0;
1618 return "";
1619 }
1620
1621 // Skip the brackets.
1622 ++BufStart;
1623 --BufEnd;
1624 return isAngled;
1625}
1626
Chris Lattner22eb9722006-06-18 05:43:12 +00001627/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1628/// file to be included from the lexer, then include it! This is a common
1629/// routine with functionality shared between #include, #include_next and
1630/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001631void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001632 const DirectoryLookup *LookupFrom,
1633 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001634
Chris Lattner22eb9722006-06-18 05:43:12 +00001635 LexerToken FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001636 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001637
1638 // If the token kind is EOM, the error has already been diagnosed.
1639 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001640 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001641
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001642 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001643 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001644 FilenameBuffer.resize(FilenameTok.getLength());
1645
1646 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1647 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1648 FilenameStart, FilenameEnd);
1649 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1650 // error.
1651 if (FilenameStart == 0)
1652 return;
1653
Chris Lattner269c2322006-06-25 06:23:00 +00001654 // Verify that there is nothing after the filename, other than EOM. Use the
1655 // preprocessor to lex this in case lexing the filename entered a macro.
1656 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001657
1658 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001659 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001660 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1661
Chris Lattner22eb9722006-06-18 05:43:12 +00001662 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001663 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001664 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001665 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001666 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001667 return Diag(FilenameTok, diag::err_pp_file_not_found,
1668 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001669
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001670 // Ask HeaderInfo if we should enter this #include file.
1671 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1672 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001673 return;
1674 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001675
1676 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001677 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001678 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001679 return Diag(FilenameTok, diag::err_pp_file_not_found,
1680 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001681
1682 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001683 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001684}
1685
1686/// HandleIncludeNextDirective - Implements #include_next.
1687///
Chris Lattnercb283342006-06-18 06:48:37 +00001688void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1689 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001690
1691 // #include_next is like #include, except that we start searching after
1692 // the current found directory. If we can't do this, issue a
1693 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001694 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001695 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001696 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001697 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001698 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001699 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001700 } else {
1701 // Start looking up in the next directory.
1702 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001703 }
1704
1705 return HandleIncludeDirective(IncludeNextTok, Lookup);
1706}
1707
1708/// HandleImportDirective - Implements #import.
1709///
Chris Lattnercb283342006-06-18 06:48:37 +00001710void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1711 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001712
1713 return HandleIncludeDirective(ImportTok, 0, true);
1714}
1715
Chris Lattnerb8761832006-06-24 21:31:03 +00001716//===----------------------------------------------------------------------===//
1717// Preprocessor Macro Directive Handling.
1718//===----------------------------------------------------------------------===//
1719
Chris Lattnercefc7682006-07-08 08:28:12 +00001720/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1721/// definition has just been read. Lex the rest of the arguments and the
1722/// closing ), updating MI with what we learn. Return true if an error occurs
1723/// parsing the arg list.
1724bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001725 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1726
Chris Lattnercefc7682006-07-08 08:28:12 +00001727 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001728 while (1) {
1729 LexUnexpandedToken(Tok);
1730 switch (Tok.getKind()) {
1731 case tok::r_paren:
1732 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001733 if (Arguments.empty()) { // #define FOO()
1734 MI->setArgumentList(Arguments.begin(), Arguments.end());
1735 return false;
1736 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001737 // Otherwise we have #define FOO(A,)
1738 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1739 return true;
1740 case tok::ellipsis: // #define X(... -> C99 varargs
1741 // Warn if use of C99 feature in non-C99 mode.
1742 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1743
1744 // Lex the token after the identifier.
1745 LexUnexpandedToken(Tok);
1746 if (Tok.getKind() != tok::r_paren) {
1747 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1748 return true;
1749 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001750 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001751 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001752 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001753 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001754 return false;
1755 case tok::eom: // #define X(
1756 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1757 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001758 default:
1759 // Handle keywords and identifiers here to accept things like
1760 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001761 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001762 if (II == 0) {
1763 // #define X(1
1764 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1765 return true;
1766 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001767
1768 // If this is already used as an argument, it is used multiple times (e.g.
1769 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00001770 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1771 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001772 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1773 return true;
1774 }
1775
1776 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00001777 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001778
1779 // Lex the token after the identifier.
1780 LexUnexpandedToken(Tok);
1781
1782 switch (Tok.getKind()) {
1783 default: // #define X(A B
1784 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1785 return true;
1786 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00001787 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001788 return false;
1789 case tok::comma: // #define X(A,
1790 break;
1791 case tok::ellipsis: // #define X(A... -> GCC extension
1792 // Diagnose extension.
1793 Diag(Tok, diag::ext_named_variadic_macro);
1794
1795 // Lex the token after the identifier.
1796 LexUnexpandedToken(Tok);
1797 if (Tok.getKind() != tok::r_paren) {
1798 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1799 return true;
1800 }
1801
1802 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001803 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001804 return false;
1805 }
1806 }
1807 }
1808}
1809
Chris Lattner22eb9722006-06-18 05:43:12 +00001810/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001811/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1812/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001813///
Chris Lattner81278c62006-10-14 19:03:49 +00001814void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1815 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001816 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001817
Chris Lattner22eb9722006-06-18 05:43:12 +00001818 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001819 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001820
1821 // Error reading macro name? If so, diagnostic already issued.
1822 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001823 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00001824
Chris Lattner457fc152006-07-29 06:30:25 +00001825 // If we are supposed to keep comments in #defines, reenable comment saving
1826 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001827 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001828
Chris Lattner063400e2006-10-14 19:54:15 +00001829 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001830 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001831 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001832
Chris Lattner063400e2006-10-14 19:54:15 +00001833 // If the identifier is an 'other target' macro, clear this bit.
1834 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1835
1836
Chris Lattner22eb9722006-06-18 05:43:12 +00001837 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001838 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001839
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001840 // If this is a function-like macro definition, parse the argument list,
1841 // marking each of the identifiers as being used as macro arguments. Also,
1842 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001843 if (Tok.getKind() == tok::eom) {
1844 // If there is no body to this macro, we have no special handling here.
1845 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001846 // This is a function-like macro definition. Read the argument list.
1847 MI->setIsFunctionLike();
1848 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001849 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001850 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001851 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001852 if (CurLexer->ParsingPreprocessorDirective)
1853 DiscardUntilEndOfDirective();
1854 return;
1855 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001856
Chris Lattner815a1f92006-07-08 20:48:04 +00001857 // Read the first token after the arg list for down below.
1858 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001859 } else if (!Tok.hasLeadingSpace()) {
1860 // C99 requires whitespace between the macro definition and the body. Emit
1861 // a diagnostic for something like "#define X+".
1862 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001863 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001864 } else {
1865 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1866 // one in some cases!
1867 }
1868 } else {
1869 // This is a normal token with leading space. Clear the leading space
1870 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001871 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001872 }
1873
Chris Lattner7e374832006-07-29 03:46:57 +00001874 // If this is a definition of a variadic C99 function-like macro, not using
1875 // the GNU named varargs extension, enabled __VA_ARGS__.
1876
1877 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1878 // This gets unpoisoned where it is allowed.
1879 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1880 if (MI->isC99Varargs())
1881 Ident__VA_ARGS__->setIsPoisoned(false);
1882
Chris Lattner22eb9722006-06-18 05:43:12 +00001883 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00001884 if (MI->isObjectLike()) {
1885 // Object-like macros are very simple, just read their body.
1886 while (Tok.getKind() != tok::eom) {
1887 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001888 // Get the next token of the macro.
1889 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001890 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001891
Chris Lattnera3834342007-07-14 21:54:03 +00001892 } else {
1893 // Otherwise, read the body of a function-like macro. This has to validate
1894 // the # (stringize) operator.
1895 while (Tok.getKind() != tok::eom) {
1896 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001897
Chris Lattnera3834342007-07-14 21:54:03 +00001898 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1899 // parameters in function-like macro expansions.
1900 if (Tok.getKind() != tok::hash) {
1901 // Get the next token of the macro.
1902 LexUnexpandedToken(Tok);
1903 continue;
1904 }
1905
1906 // Get the next token of the macro.
1907 LexUnexpandedToken(Tok);
1908
1909 // Not a macro arg identifier?
1910 if (!Tok.getIdentifierInfo() ||
1911 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1912 Diag(Tok, diag::err_pp_stringize_not_parameter);
1913 delete MI;
1914
1915 // Disable __VA_ARGS__ again.
1916 Ident__VA_ARGS__->setIsPoisoned(true);
1917 return;
1918 }
1919
1920 // Things look ok, add the param name token to the macro.
1921 MI->AddTokenToBody(Tok);
1922
1923 // Get the next token of the macro.
1924 LexUnexpandedToken(Tok);
1925 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001926 }
Chris Lattner7e374832006-07-29 03:46:57 +00001927
Chris Lattnerf40fe992007-07-14 22:11:41 +00001928
Chris Lattner7e374832006-07-29 03:46:57 +00001929 // Disable __VA_ARGS__ again.
1930 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001931
Chris Lattnerbff18d52006-07-06 04:49:18 +00001932 // Check that there is no paste (##) operator at the begining or end of the
1933 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001934 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001935 if (NumTokens != 0) {
1936 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001937 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001938 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001939 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001940 }
1941 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001942 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001943 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001944 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001945 }
1946 }
1947
Chris Lattner13044d92006-07-03 05:16:44 +00001948 // If this is the primary source file, remember that this macro hasn't been
1949 // used yet.
1950 if (isInPrimaryFile())
1951 MI->setIsUsed(false);
1952
Chris Lattner22eb9722006-06-18 05:43:12 +00001953 // Finally, if this identifier already had a macro defined for it, verify that
1954 // the macro bodies are identical and free the old definition.
1955 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001956 if (!OtherMI->isUsed())
1957 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1958
Chris Lattner22eb9722006-06-18 05:43:12 +00001959 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001960 // must be the same. C99 6.10.3.2.
1961 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001962 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1963 MacroNameTok.getIdentifierInfo()->getName());
1964 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1965 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001966 delete OtherMI;
1967 }
1968
1969 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001970}
1971
Chris Lattner063400e2006-10-14 19:54:15 +00001972/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1973void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1974 LexerToken MacroNameTok;
1975 ReadMacroName(MacroNameTok, 1);
1976
1977 // Error reading macro name? If so, diagnostic already issued.
1978 if (MacroNameTok.getKind() == tok::eom)
1979 return;
1980
1981 // Check to see if this is the last token on the #undef line.
1982 CheckEndOfDirective("#define_other_target");
1983
1984 // If there is already a macro defined by this name, turn it into a
1985 // target-specific define.
1986 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1987 MI->setIsTargetSpecific(true);
1988 return;
1989 }
1990
1991 // Mark the identifier as being a macro on some other target.
1992 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1993}
1994
Chris Lattner22eb9722006-06-18 05:43:12 +00001995
1996/// HandleUndefDirective - Implements #undef.
1997///
Chris Lattnercb283342006-06-18 06:48:37 +00001998void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001999 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002000
Chris Lattner22eb9722006-06-18 05:43:12 +00002001 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002002 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002003
2004 // Error reading macro name? If so, diagnostic already issued.
2005 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00002006 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002007
2008 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002009 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002010
2011 // Okay, we finally have a valid identifier to undef.
2012 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
2013
Chris Lattner063400e2006-10-14 19:54:15 +00002014 // #undef untaints an identifier if it were marked by define_other_target.
2015 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2016
Chris Lattner22eb9722006-06-18 05:43:12 +00002017 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002018 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002019
Chris Lattner13044d92006-07-03 05:16:44 +00002020 if (!MI->isUsed())
2021 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002022
2023 // Free macro definition.
2024 delete MI;
2025 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002026}
2027
2028
Chris Lattnerb8761832006-06-24 21:31:03 +00002029//===----------------------------------------------------------------------===//
2030// Preprocessor Conditional Directive Handling.
2031//===----------------------------------------------------------------------===//
2032
Chris Lattner22eb9722006-06-18 05:43:12 +00002033/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002034/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2035/// if any tokens have been returned or pp-directives activated before this
2036/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002037///
Chris Lattner371ac8a2006-07-04 07:11:10 +00002038void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
2039 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002040 ++NumIf;
2041 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002042
Chris Lattner22eb9722006-06-18 05:43:12 +00002043 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002044 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002045
2046 // Error reading macro name? If so, diagnostic already issued.
2047 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00002048 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002049
2050 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002051 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2052
2053 // If the start of a top-level #ifdef, inform MIOpt.
2054 if (!ReadAnyTokensBeforeDirective &&
2055 CurLexer->getConditionalStackDepth() == 0) {
2056 assert(isIfndef && "#ifdef shouldn't reach here");
2057 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2058 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002059
Chris Lattner063400e2006-10-14 19:54:15 +00002060 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2061 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00002062
Chris Lattner81278c62006-10-14 19:03:49 +00002063 // If there is a macro, process it.
2064 if (MI) {
2065 // Mark it used.
2066 MI->setIsUsed(true);
2067
2068 // If this is the first use of a target-specific macro, warn about it.
2069 if (MI->isTargetSpecific()) {
2070 MI->setIsTargetSpecific(false); // Don't warn on second use.
2071 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2072 diag::port_target_macro_use);
2073 }
Chris Lattner063400e2006-10-14 19:54:15 +00002074 } else {
2075 // Use of a target-specific macro for some other target? If so, warn.
2076 if (MII->isOtherTargetMacro()) {
2077 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2078 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2079 diag::port_target_macro_use);
2080 }
Chris Lattner81278c62006-10-14 19:03:49 +00002081 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002082
Chris Lattner22eb9722006-06-18 05:43:12 +00002083 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002084 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002085 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002086 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002087 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002088 } else {
2089 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002090 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002091 /*Foundnonskip*/false,
2092 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002093 }
2094}
2095
2096/// HandleIfDirective - Implements the #if directive.
2097///
Chris Lattnera8654ca2006-07-04 17:42:08 +00002098void Preprocessor::HandleIfDirective(LexerToken &IfToken,
2099 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002100 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002101
Chris Lattner371ac8a2006-07-04 07:11:10 +00002102 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002103 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002104 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002105
2106 // Should we include the stuff contained by this directive?
2107 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002108 // If this condition is equivalent to #ifndef X, and if this is the first
2109 // directive seen, handle it for the multiple-include optimization.
2110 if (!ReadAnyTokensBeforeDirective &&
2111 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2112 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2113
Chris Lattner22eb9722006-06-18 05:43:12 +00002114 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002115 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002116 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002117 } else {
2118 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002119 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002120 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002121 }
2122}
2123
2124/// HandleEndifDirective - Implements the #endif directive.
2125///
Chris Lattnercb283342006-06-18 06:48:37 +00002126void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002127 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002128
Chris Lattner22eb9722006-06-18 05:43:12 +00002129 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002130 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002131
2132 PPConditionalInfo CondInfo;
2133 if (CurLexer->popConditionalLevel(CondInfo)) {
2134 // No conditionals on the stack: this is an #endif without an #if.
2135 return Diag(EndifToken, diag::err_pp_endif_without_if);
2136 }
2137
Chris Lattner371ac8a2006-07-04 07:11:10 +00002138 // If this the end of a top-level #endif, inform MIOpt.
2139 if (CurLexer->getConditionalStackDepth() == 0)
2140 CurLexer->MIOpt.ExitTopLevelConditional();
2141
Chris Lattner538d7f32006-07-20 04:31:52 +00002142 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002143 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002144}
2145
2146
Chris Lattnercb283342006-06-18 06:48:37 +00002147void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002148 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002149
Chris Lattner22eb9722006-06-18 05:43:12 +00002150 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002151 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002152
2153 PPConditionalInfo CI;
2154 if (CurLexer->popConditionalLevel(CI))
2155 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002156
2157 // If this is a top-level #else, inform the MIOpt.
2158 if (CurLexer->getConditionalStackDepth() == 0)
2159 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002160
2161 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002162 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002163
2164 // Finally, skip the rest of the contents of this block and return the first
2165 // token after it.
2166 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2167 /*FoundElse*/true);
2168}
2169
Chris Lattnercb283342006-06-18 06:48:37 +00002170void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002171 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002172
Chris Lattner22eb9722006-06-18 05:43:12 +00002173 // #elif directive in a non-skipping conditional... start skipping.
2174 // We don't care what the condition is, because we will always skip it (since
2175 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002176 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002177
2178 PPConditionalInfo CI;
2179 if (CurLexer->popConditionalLevel(CI))
2180 return Diag(ElifToken, diag::pp_err_elif_without_if);
2181
Chris Lattner371ac8a2006-07-04 07:11:10 +00002182 // If this is a top-level #elif, inform the MIOpt.
2183 if (CurLexer->getConditionalStackDepth() == 0)
2184 CurLexer->MIOpt.FoundTopLevelElse();
2185
Chris Lattner22eb9722006-06-18 05:43:12 +00002186 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002187 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002188
2189 // Finally, skip the rest of the contents of this block and return the first
2190 // token after it.
2191 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2192 /*FoundElse*/CI.FoundElse);
2193}
Chris Lattnerb8761832006-06-24 21:31:03 +00002194