blob: 2067a0bc4ae189cb03dc24055e01a167b7f8651b [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
Chris Lattner146762e2007-07-20 16:59:19 +0000108/// the specified Token's location, translating the token's start
Chris Lattner22eb9722006-06-18 05:43:12 +0000109/// 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
Chris Lattner146762e2007-07-20 16:59:19 +0000119void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000120 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.
Chris Lattner146762e2007-07-20 16:59:19 +0000179std::string Preprocessor::getSpelling(const Token &Tok) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000180 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.
Chris Lattner146762e2007-07-20 16:59:19 +0000212unsigned Preprocessor::getSpelling(const Token &Tok,
Chris Lattneref9eae12006-07-04 22:33:12 +0000213 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 Lattner77e9de52007-07-20 16:52:03 +0000284 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattner146762e2007-07-20 16:59:19 +0000285 Token Tok;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000286 // Skip over characters the remaining characters.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000287 const char *TokStartPtr = TokPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000288 for (; CharNo; --CharNo)
289 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000290
291 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000292 }
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000293
294 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner8a7003c2007-07-16 06:48:38 +0000295}
296
297
298
Chris Lattnerd01e2912006-06-18 16:22:51 +0000299//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000300// Source File Location Methods.
301//===----------------------------------------------------------------------===//
302
Chris Lattner22eb9722006-06-18 05:43:12 +0000303/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
304/// return null on failure. isAngled indicates whether the file reference is
305/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000306const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
307 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000308 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000309 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000310 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000311 // If the header lookup mechanism may be relative to the current file, pass in
312 // info about where the current file is.
313 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000314 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000315 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
316 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000317 }
318
Chris Lattner63dd32b2006-10-20 04:42:40 +0000319 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000320 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000321 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000322 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
323 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000324 if (FE) return FE;
325
326 // Otherwise, see if this is a subframework header. If so, this is relative
327 // to one of the headers on the #include stack. Walk the list of the current
328 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000329 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000330 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000331 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
332 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000333 return FE;
334 }
335
336 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
337 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000338 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000339 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000340 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
341 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000342 return FE;
343 }
344 }
345
346 // Otherwise, we really couldn't find the file.
347 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000348}
349
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000350/// isInPrimaryFile - Return true if we're in the top-level file, not in a
351/// #include.
352bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000353 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000354 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000355
Chris Lattner13044d92006-07-03 05:16:44 +0000356 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000357 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000358 if (IncludeMacroStack[i].TheLexer &&
359 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
360 return IncludeMacroStack[i].TheLexer->isMainFile();
361 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000362}
363
364/// getCurrentLexer - Return the current file lexer being lexed from. Note
365/// that this ignores any potentially active macro expansions and _Pragma
366/// expansions going on at the time.
367Lexer *Preprocessor::getCurrentFileLexer() const {
368 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
369
370 // Look for a stacked lexer.
371 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000372 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000373 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
374 return L;
375 }
376 return 0;
377}
378
379
Chris Lattner22eb9722006-06-18 05:43:12 +0000380/// EnterSourceFile - Add a source file to the top of the include stack and
381/// start lexing tokens from it instead of the current buffer. Return true
382/// on failure.
383void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000384 const DirectoryLookup *CurDir,
385 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000386 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000387 ++NumEnteredSourceFiles;
388
Chris Lattner69772b02006-07-02 20:34:39 +0000389 if (MaxIncludeStackDepth < IncludeMacroStack.size())
390 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000391
Chris Lattner77e9de52007-07-20 16:52:03 +0000392 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000393 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000394 EnterSourceFileWithLexer(TheLexer, CurDir);
395}
Chris Lattner22eb9722006-06-18 05:43:12 +0000396
Chris Lattner69772b02006-07-02 20:34:39 +0000397/// EnterSourceFile - Add a source file to the top of the include stack and
398/// start lexing tokens from it instead of the current buffer.
399void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
400 const DirectoryLookup *CurDir) {
401
402 // Add the current lexer to the include stack.
403 if (CurLexer || CurMacroExpander)
404 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
405 CurMacroExpander));
406
407 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000408 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000409 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000410
411 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000412 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000413 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
414
415 // Get the file entry for the current file.
416 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000417 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000418 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000419
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000420 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000421 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000422 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000423}
424
Chris Lattner69772b02006-07-02 20:34:39 +0000425
426
Chris Lattner22eb9722006-06-18 05:43:12 +0000427/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000428/// tokens from it instead of the current buffer.
Chris Lattner146762e2007-07-20 16:59:19 +0000429void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000430 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
431 CurMacroExpander));
432 CurLexer = 0;
433 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000434
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000435 if (NumCachedMacroExpanders == 0) {
436 CurMacroExpander = new MacroExpander(Tok, Args, *this);
437 } else {
438 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
439 CurMacroExpander->Init(Tok, Args);
440 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000441}
442
Chris Lattner7667d0d2006-07-16 18:16:58 +0000443/// EnterTokenStream - Add a "macro" context to the top of the include stack,
444/// which will cause the lexer to start returning the specified tokens. Note
445/// that these tokens will be re-macro-expanded when/if expansion is enabled.
446/// This method assumes that the specified stream of tokens has a permanent
447/// owner somewhere, so they do not need to be copied.
Chris Lattner146762e2007-07-20 16:59:19 +0000448void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000449 // Save our current state.
450 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
451 CurMacroExpander));
452 CurLexer = 0;
453 CurDirLookup = 0;
454
455 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000456 if (NumCachedMacroExpanders == 0) {
457 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
458 } else {
459 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
460 CurMacroExpander->Init(Toks, NumToks);
461 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000462}
463
464/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
465/// lexer stack. This should only be used in situations where the current
466/// state of the top-of-stack lexer is known.
467void Preprocessor::RemoveTopOfLexerStack() {
468 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000469
470 if (CurMacroExpander) {
471 // Delete or cache the now-dead macro expander.
472 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
473 delete CurMacroExpander;
474 else
475 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
476 } else {
477 delete CurLexer;
478 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000479 CurLexer = IncludeMacroStack.back().TheLexer;
480 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
481 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
482 IncludeMacroStack.pop_back();
483}
484
Chris Lattner22eb9722006-06-18 05:43:12 +0000485//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000486// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000487//===----------------------------------------------------------------------===//
488
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000489/// RegisterBuiltinMacro - Register the specified identifier in the identifier
490/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000491IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000492 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000493 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000494
495 // Mark it as being a macro that is builtin.
496 MacroInfo *MI = new MacroInfo(SourceLocation());
497 MI->setIsBuiltinMacro();
498 Id->setMacroInfo(MI);
499 return Id;
500}
501
502
Chris Lattner677757a2006-06-28 05:26:32 +0000503/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
504/// identifier table.
505void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000506 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000507 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000508 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
509 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000510 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000511
512 // GCC Extensions.
513 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
514 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000515 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000516}
517
Chris Lattnerc2395832006-07-09 00:57:04 +0000518/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
519/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000520static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
521 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000522 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
523
524 // If the token isn't an identifier, it's always literally expanded.
525 if (II == 0) return true;
526
527 // If the identifier is a macro, and if that macro is enabled, it may be
528 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000529 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
530 // Fast expanding "#define X X" is ok, because X would be disabled.
531 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000532 return false;
533
534 // If this is an object-like macro invocation, it is safe to trivially expand
535 // it.
536 if (MI->isObjectLike()) return true;
537
538 // If this is a function-like macro invocation, it's safe to trivially expand
539 // as long as the identifier is not a macro argument.
540 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
541 I != E; ++I)
542 if (*I == II)
543 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000544
Chris Lattnerc2395832006-07-09 00:57:04 +0000545 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000546}
547
Chris Lattnerc2395832006-07-09 00:57:04 +0000548
Chris Lattnerafe603f2006-07-11 04:02:46 +0000549/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
550/// lexed is a '('. If so, consume the token and return true, if not, this
551/// method should have no observable side-effect on the lexed tokens.
552bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000553 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000554 unsigned Val;
555 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000556 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000557 else
558 Val = CurMacroExpander->isNextTokenLParen();
559
560 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000561 // We have run off the end. If it's a source file we don't
562 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
563 // macro stack.
564 if (CurLexer)
565 return false;
566 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000567 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
568 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000569 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000570 else
571 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000572
573 if (Val != 2)
574 break;
575
576 // Ran off the end of a source file?
577 if (Entry.TheLexer)
578 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000579 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000580 }
581
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000582 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
583 // have found something that isn't a '(' or we found the end of the
584 // translation unit. In either case, return false.
585 if (Val != 1)
586 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000587
Chris Lattner146762e2007-07-20 16:59:19 +0000588 Token Tok;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000589 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000590 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
591 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000592}
Chris Lattner677757a2006-06-28 05:26:32 +0000593
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000594/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
595/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner146762e2007-07-20 16:59:19 +0000596bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000597 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000598
599 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
600 if (MI->isBuiltinMacro()) {
601 ExpandBuiltinMacro(Identifier);
602 return false;
603 }
604
Chris Lattner81278c62006-10-14 19:03:49 +0000605 // If this is the first use of a target-specific macro, warn about it.
606 if (MI->isTargetSpecific()) {
607 MI->setIsTargetSpecific(false); // Don't warn on second use.
608 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
609 diag::port_target_macro_use);
610 }
611
Chris Lattneree8760b2006-07-15 07:42:55 +0000612 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000613 /// for each macro argument, the list of tokens that were provided to the
614 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000615 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000616
617 // If this is a function-like macro, read the arguments.
618 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000619 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000620 // name isn't a '(', this macro should not be expanded. Otherwise, consume
621 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000622 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000623 return true;
624
Chris Lattner78186052006-07-09 00:45:31 +0000625 // Remember that we are now parsing the arguments to a macro invocation.
626 // Preprocessor directives used inside macro arguments are not portable, and
627 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000628 InMacroArgs = true;
629 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000630
631 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000632 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000633
634 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000635 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000636
637 ++NumFnMacroExpanded;
638 } else {
639 ++NumMacroExpanded;
640 }
Chris Lattner13044d92006-07-03 05:16:44 +0000641
642 // Notice that this macro has been used.
643 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000644
645 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000646
647 // If this macro expands to no tokens, don't bother to push it onto the
648 // expansion stack, only to take it right back off.
649 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000650 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000651 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000652
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000653 // Ignore this macro use, just return the next token in the current
654 // buffer.
655 bool HadLeadingSpace = Identifier.hasLeadingSpace();
656 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
657
658 Lex(Identifier);
659
660 // If the identifier isn't on some OTHER line, inherit the leading
661 // whitespace/first-on-a-line property of this token. This handles
662 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
663 // empty.
664 if (!Identifier.isAtStartOfLine()) {
Chris Lattner146762e2007-07-20 16:59:19 +0000665 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
666 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000667 }
668 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000669 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000670
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000671 } else if (MI->getNumTokens() == 1 &&
672 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000673 // Otherwise, if this macro expands into a single trivially-expanded
674 // token: expand it now. This handles common cases like
675 // "#define VAL 42".
676
677 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
678 // identifier to the expanded token.
679 bool isAtStartOfLine = Identifier.isAtStartOfLine();
680 bool hasLeadingSpace = Identifier.hasLeadingSpace();
681
682 // Remember where the token is instantiated.
683 SourceLocation InstantiateLoc = Identifier.getLocation();
684
685 // Replace the result token.
686 Identifier = MI->getReplacementToken(0);
687
688 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner146762e2007-07-20 16:59:19 +0000689 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
690 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000691
692 // Update the tokens location to include both its logical and physical
693 // locations.
694 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000695 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000696 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000697
Chris Lattner6e4bf522006-07-27 06:59:25 +0000698 // If this is #define X X, we must mark the result as unexpandible.
699 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
700 if (NewII->getMacroInfo() == MI)
Chris Lattner146762e2007-07-20 16:59:19 +0000701 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000702
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000703 // Since this is not an identifier token, it can't be macro expanded, so
704 // we're done.
705 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000706 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000707 }
708
Chris Lattner78186052006-07-09 00:45:31 +0000709 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000710 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000711
712 // Now that the macro is at the top of the include stack, ask the
713 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000714 Lex(Identifier);
715 return false;
716}
717
Chris Lattneree8760b2006-07-15 07:42:55 +0000718/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000719/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000720/// invocation. This returns null on error.
Chris Lattner146762e2007-07-20 16:59:19 +0000721MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattneree8760b2006-07-15 07:42:55 +0000722 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000723 // The number of fixed arguments to parse.
724 unsigned NumFixedArgsLeft = MI->getNumArgs();
725 bool isVariadic = MI->isVariadic();
726
Chris Lattner78186052006-07-09 00:45:31 +0000727 // Outer loop, while there are more arguments, keep reading them.
Chris Lattner146762e2007-07-20 16:59:19 +0000728 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000729 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000730 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000731
732 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000733 // argument is separated by an EOF token. Use a SmallVector so we can avoid
734 // heap allocations in the common case.
Chris Lattner146762e2007-07-20 16:59:19 +0000735 llvm::SmallVector<Token, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000736
737 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000738 while (Tok.getKind() == tok::comma) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000739 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
740 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000741 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000742
Chris Lattner78186052006-07-09 00:45:31 +0000743 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000744 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
745 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000746 LexUnexpandedToken(Tok);
747
748 if (Tok.getKind() == tok::eof) {
749 Diag(MacroName, diag::err_unterm_macro_invoc);
750 // Do not lose the EOF. Return it to the client.
751 MacroName = Tok;
752 return 0;
753 } else if (Tok.getKind() == tok::r_paren) {
754 // If we found the ) token, the macro arg list is done.
755 if (NumParens-- == 0)
756 break;
757 } else if (Tok.getKind() == tok::l_paren) {
758 ++NumParens;
759 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
760 // Comma ends this argument if there are more fixed arguments expected.
761 if (NumFixedArgsLeft)
762 break;
763
Chris Lattner2ada5d32006-07-15 07:51:24 +0000764 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000765 if (!isVariadic) {
766 // Emit the diagnostic at the macro name in case there is a missing ).
767 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000768 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000769 return 0;
770 }
771 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000772 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000773 // If this is a comment token in the argument list and we're just in
774 // -C mode (not -CC mode), discard the comment.
775 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000776 }
777
778 ArgTokens.push_back(Tok);
779 }
780
Chris Lattnera12dd152006-07-11 04:09:02 +0000781 // Empty arguments are standard in C99 and supported as an extension in
782 // other modes.
783 if (ArgTokens.empty() && !Features.C99)
784 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000785
Chris Lattner36b6e812006-07-21 06:38:30 +0000786 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattner146762e2007-07-20 16:59:19 +0000787 Token EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000788 EOFTok.startToken();
789 EOFTok.setKind(tok::eof);
790 EOFTok.setLocation(Tok.getLocation());
791 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000792 ArgTokens.push_back(EOFTok);
793 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000794 --NumFixedArgsLeft;
795 };
796
797 // Okay, we either found the r_paren. Check to see if we parsed too few
798 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000799 unsigned MinArgsExpected = MI->getNumArgs();
800
Chris Lattner775d8322006-07-29 04:39:41 +0000801 // See MacroArgs instance var for description of this.
802 bool isVarargsElided = false;
803
Chris Lattner2ada5d32006-07-15 07:51:24 +0000804 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000805 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000806 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000807 // Varargs where the named vararg parameter is missing: ok as extension.
808 // #define A(x, ...)
809 // A("blah")
810 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000811
812 // Remember this occurred if this is a C99 macro invocation with at least
813 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000814 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000815 } else if (MI->getNumArgs() == 1) {
816 // #define A(x)
817 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000818 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000819
820 // Empty arguments are standard in C99 and supported as an extension in
821 // other modes.
822 if (ArgTokens.empty() && !Features.C99)
823 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000824 } else {
825 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000826 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000827 return 0;
828 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000829
830 // Add a marker EOF token to the end of the token list for this argument.
831 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000832 Tok.startToken();
833 Tok.setKind(tok::eof);
834 Tok.setLocation(EndLoc);
835 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000836 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000837 }
838
Chris Lattner775d8322006-07-29 04:39:41 +0000839 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000840}
841
Chris Lattnerc673f902006-06-30 06:10:41 +0000842/// ComputeDATE_TIME - Compute the current time, enter it into the specified
843/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
844/// the identifier tokens inserted.
845static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000846 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000847 time_t TT = time(0);
848 struct tm *TM = localtime(&TT);
849
850 static const char * const Months[] = {
851 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
852 };
853
854 char TmpBuffer[100];
855 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
856 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000857 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000858
859 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000860 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000861}
862
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000863/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
864/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000865void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000866 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000867 IdentifierInfo *II = Tok.getIdentifierInfo();
868 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000869
870 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
871 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000872 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000873 return Handle_Pragma(Tok);
874
Chris Lattner78186052006-07-09 00:45:31 +0000875 ++NumBuiltinMacroExpanded;
876
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000877 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000878
879 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000880 Tok.setIdentifierInfo(0);
Chris Lattner146762e2007-07-20 16:59:19 +0000881 Tok.clearFlag(Token::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000882
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000883 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000884 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000885 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000886 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000887 Tok.setKind(tok::numeric_constant);
888 Tok.setLength(Length);
889 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000890 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000891 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000892 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000893 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000894 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
895 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000896 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000897 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +0000898 }
899 }
900
Chris Lattner0766e592006-07-03 01:07:01 +0000901 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000902 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +0000903 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000904 Tok.setKind(tok::string_literal);
905 Tok.setLength(FN.size());
906 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000907 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000908 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000909 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000910 Tok.setKind(tok::string_literal);
911 Tok.setLength(strlen("\"Mmm dd yyyy\""));
912 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000913 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000914 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000915 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000916 Tok.setKind(tok::string_literal);
917 Tok.setLength(strlen("\"hh:mm:ss\""));
918 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000919 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000920 Diag(Tok, diag::ext_pp_include_level);
921
922 // Compute the include depth of this token.
923 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000924 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
925 for (; Loc.isValid(); ++Depth)
926 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +0000927
928 // __INCLUDE_LEVEL__ expands to a simple numeric value.
929 sprintf(TmpBuffer, "%u", Depth);
930 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000931 Tok.setKind(tok::numeric_constant);
932 Tok.setLength(Length);
933 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000934 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000935 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
936 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
937 Diag(Tok, diag::ext_pp_timestamp);
938
939 // Get the file that we are lexing out of. If we're currently lexing from
940 // a macro, dig into the include stack.
941 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000942 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000943
944 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000945 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +0000946
947 // If this file is older than the file it depends on, emit a diagnostic.
948 const char *Result;
949 if (CurFile) {
950 time_t TT = CurFile->getModificationTime();
951 struct tm *TM = localtime(&TT);
952 Result = asctime(TM);
953 } else {
954 Result = "??? ??? ?? ??:??:?? ????\n";
955 }
956 TmpBuffer[0] = '"';
957 strcpy(TmpBuffer+1, Result);
958 unsigned Len = strlen(TmpBuffer);
959 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000960 Tok.setKind(tok::string_literal);
961 Tok.setLength(Len);
962 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000963 } else {
964 assert(0 && "Unknown identifier!");
965 }
966}
Chris Lattner677757a2006-06-28 05:26:32 +0000967
968//===----------------------------------------------------------------------===//
969// Lexer Event Handling.
970//===----------------------------------------------------------------------===//
971
Chris Lattnercefc7682006-07-08 08:28:12 +0000972/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
973/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +0000974IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +0000975 const char *BufPtr) {
976 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
977 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
978
979 // Look up this token, see if it is a macro, or if it is a language keyword.
980 IdentifierInfo *II;
981 if (BufPtr && !Identifier.needsCleaning()) {
982 // No cleaning needed, just use the characters from the lexed buffer.
983 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
984 } else {
985 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +0000986 llvm::SmallVector<char, 64> IdentifierBuffer;
987 IdentifierBuffer.resize(Identifier.getLength());
988 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +0000989 unsigned Size = getSpelling(Identifier, TmpBuf);
990 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
991 }
Chris Lattner8c204872006-10-14 05:19:21 +0000992 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000993 return II;
994}
995
996
Chris Lattner677757a2006-06-28 05:26:32 +0000997/// HandleIdentifier - This callback is invoked when the lexer reads an
998/// identifier. This callback looks up the identifier in the map and/or
999/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +00001000void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001001 assert(Identifier.getIdentifierInfo() &&
1002 "Can't handle identifiers without identifier info!");
1003
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001004 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001005
1006 // If this identifier was poisoned, and if it was not produced from a macro
1007 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001008 if (II.isPoisoned() && CurLexer) {
1009 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1010 Diag(Identifier, diag::err_pp_used_poisoned_id);
1011 else
1012 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1013 }
Chris Lattner677757a2006-06-28 05:26:32 +00001014
Chris Lattner78186052006-07-09 00:45:31 +00001015 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +00001016 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001017 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1018 if (MI->isEnabled()) {
1019 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1020 return;
1021 } else {
1022 // C99 6.10.3.4p2 says that a disabled macro may never again be
1023 // expanded, even if it's in a context where it could be expanded in the
1024 // future.
Chris Lattner146762e2007-07-20 16:59:19 +00001025 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001026 }
1027 }
Chris Lattner063400e2006-10-14 19:54:15 +00001028 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1029 // If this identifier is a macro on some other target, emit a diagnostic.
1030 // This diagnosic is only emitted when macro expansion is enabled, because
1031 // the macro would not have been expanded for the other target either.
1032 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1033 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1034 diag::port_target_macro_use);
1035
1036 }
Chris Lattner677757a2006-06-28 05:26:32 +00001037
Chris Lattner5b9f4892006-11-21 17:23:33 +00001038 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1039 // then we act as if it is the actual operator and not the textual
1040 // representation of it.
1041 if (II.isCPlusPlusOperatorKeyword())
1042 Identifier.setIdentifierInfo(0);
1043
Chris Lattner677757a2006-06-28 05:26:32 +00001044 // Change the kind of this identifier to the appropriate token kind, e.g.
1045 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001046 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001047
1048 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001049 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1050 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001051 if (II.isExtensionToken() && Features.C99)
1052 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001053}
1054
Chris Lattner22eb9722006-06-18 05:43:12 +00001055/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1056/// the current file. This either returns the EOF token or pops a level off
1057/// the include stack and keeps going.
Chris Lattner146762e2007-07-20 16:59:19 +00001058bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001059 assert(!CurMacroExpander &&
1060 "Ending a file when currently in a macro!");
1061
Chris Lattner371ac8a2006-07-04 07:11:10 +00001062 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001063 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001064 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001065 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001066 // Okay, this has a controlling macro, remember in PerFileInfo.
1067 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001068 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001069 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001070 }
1071 }
1072
Chris Lattner22eb9722006-06-18 05:43:12 +00001073 // If this is a #include'd file, pop it off the include stack and continue
1074 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001075 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001076 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001077 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001078
1079 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001080 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001081 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1082
1083 // Get the file entry for the current file.
1084 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001085 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001086 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001087
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001088 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1089 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001090 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001091
1092 // Client should lex another token.
1093 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001094 }
1095
Chris Lattner8c204872006-10-14 05:19:21 +00001096 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001097 CurLexer->BufferPtr = CurLexer->BufferEnd;
1098 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001099 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001100
1101 // We're done with the #included file.
1102 delete CurLexer;
1103 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001104
Chris Lattner03f83482006-07-10 06:16:26 +00001105 // This is the end of the top-level file. If the diag::pp_macro_not_used
1106 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1107 // have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001108 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1109 for (IdentifierTable::iterator I = Identifiers.begin(),
1110 E = Identifiers.end(); I != E; ++I) {
1111 const IdentifierInfo &II = I->getValue();
1112 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1113 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1114 }
1115 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001116
1117 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001118}
1119
1120/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001121/// the current macro expansion or token stream expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001122bool Preprocessor::HandleEndOfMacro(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001123 assert(CurMacroExpander && !CurLexer &&
1124 "Ending a macro when currently in a #include file!");
1125
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001126 // Delete or cache the now-dead macro expander.
1127 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1128 delete CurMacroExpander;
1129 else
1130 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001131
Chris Lattner69772b02006-07-02 20:34:39 +00001132 // Handle this like a #include file being popped off the stack.
1133 CurMacroExpander = 0;
1134 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001135}
1136
1137
1138//===----------------------------------------------------------------------===//
1139// Utility Methods for Preprocessor Directive Handling.
1140//===----------------------------------------------------------------------===//
1141
1142/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1143/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001144void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner146762e2007-07-20 16:59:19 +00001145 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001146 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001147 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001148 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001149}
1150
Chris Lattner652c1692006-11-21 23:47:30 +00001151/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1152static bool isCXXNamedOperator(const std::string &Spelling) {
1153 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1154 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1155 Spelling == "or" || Spelling == "xor";
1156}
1157
Chris Lattner22eb9722006-06-18 05:43:12 +00001158/// ReadMacroName - Lex and validate a macro name, which occurs after a
1159/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001160/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1161/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001162/// else (e.g. #ifdef).
Chris Lattner146762e2007-07-20 16:59:19 +00001163void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001164 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001165 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001166
1167 // Missing macro name?
1168 if (MacroNameTok.getKind() == tok::eom)
1169 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1170
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001171 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1172 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001173 std::string Spelling = getSpelling(MacroNameTok);
1174 if (isCXXNamedOperator(Spelling))
1175 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1176 // except for their spellings.
1177 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1178 else
1179 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001180 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001181 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001182 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001183 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001184 } else if (isDefineUndef && II->getMacroInfo() &&
1185 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001186 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001187 if (isDefineUndef == 1)
1188 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1189 else
1190 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001191 } else {
1192 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001193 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001194 }
1195
Chris Lattner22eb9722006-06-18 05:43:12 +00001196 // Invalid macro name, read and discard the rest of the line. Then set the
1197 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001198 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001199 return DiscardUntilEndOfDirective();
1200}
1201
1202/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1203/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001204void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner146762e2007-07-20 16:59:19 +00001205 Token Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001206 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001207 // There should be no tokens after the directive, but we allow them as an
1208 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001209 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1210 Lex(Tmp);
1211
Chris Lattner22eb9722006-06-18 05:43:12 +00001212 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001213 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1214 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001215 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001216}
1217
1218
1219
1220/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1221/// decided that the subsequent tokens are in the #if'd out portion of the
1222/// file. Lex the rest of the file, until we see an #endif. If
1223/// FoundNonSkipPortion is true, then we have already emitted code for part of
1224/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1225/// is true, then #else directives are ok, if not, then we have already seen one
1226/// so a #else directive is a duplicate. When this returns, the caller can lex
1227/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001228void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001229 bool FoundNonSkipPortion,
1230 bool FoundElse) {
1231 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001232 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001233 "Lexing a macro, not a file?");
1234
1235 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1236 FoundNonSkipPortion, FoundElse);
1237
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001238 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1239 // disabling warnings, etc.
1240 CurLexer->LexingRawMode = true;
Chris Lattner146762e2007-07-20 16:59:19 +00001241 Token Tok;
Chris Lattner22eb9722006-06-18 05:43:12 +00001242 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001243 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001244
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001245 // If this is the end of the buffer, we have an error.
1246 if (Tok.getKind() == tok::eof) {
1247 // Emit errors for each unterminated conditional on the stack, including
1248 // the current one.
1249 while (!CurLexer->ConditionalStack.empty()) {
1250 Diag(CurLexer->ConditionalStack.back().IfLoc,
1251 diag::err_pp_unterminated_conditional);
1252 CurLexer->ConditionalStack.pop_back();
1253 }
1254
1255 // Just return and let the caller lex after this #include.
1256 break;
1257 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001258
1259 // If this token is not a preprocessor directive, just skip it.
1260 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1261 continue;
1262
1263 // We just parsed a # character at the start of a line, so we're in
1264 // directive mode. Tell the lexer this so any newlines we see will be
1265 // converted into an EOM token (this terminates the macro).
1266 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001267 CurLexer->KeepCommentMode = false;
1268
Chris Lattner22eb9722006-06-18 05:43:12 +00001269
1270 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001271 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001272
1273 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1274 // something bogus), skip it.
1275 if (Tok.getKind() != tok::identifier) {
1276 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001277 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001278 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001279 continue;
1280 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001281
Chris Lattner22eb9722006-06-18 05:43:12 +00001282 // If the first letter isn't i or e, it isn't intesting to us. We know that
1283 // this is safe in the face of spelling differences, because there is no way
1284 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001285 // allows us to avoid looking up the identifier info for #define/#undef and
1286 // other common directives.
1287 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1288 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001289 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1290 FirstChar != 'i' && FirstChar != 'e') {
1291 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001292 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001293 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001294 continue;
1295 }
1296
Chris Lattnere60165f2006-06-22 06:36:29 +00001297 // Get the identifier name without trigraphs or embedded newlines. Note
1298 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1299 // when skipping.
1300 // TODO: could do this with zero copies in the no-clean case by using
1301 // strncmp below.
1302 char Directive[20];
1303 unsigned IdLen;
1304 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1305 IdLen = Tok.getLength();
1306 memcpy(Directive, RawCharData, IdLen);
1307 Directive[IdLen] = 0;
1308 } else {
1309 std::string DirectiveStr = getSpelling(Tok);
1310 IdLen = DirectiveStr.size();
1311 if (IdLen >= 20) {
1312 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001313 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001314 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001315 continue;
1316 }
1317 memcpy(Directive, &DirectiveStr[0], IdLen);
1318 Directive[IdLen] = 0;
1319 }
1320
Chris Lattner22eb9722006-06-18 05:43:12 +00001321 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001322 if ((IdLen == 2) || // "if"
1323 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1324 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001325 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1326 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001327 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001328 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001329 /*foundnonskip*/false,
1330 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001331 }
1332 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001333 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001334 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001335 PPConditionalInfo CondInfo;
1336 CondInfo.WasSkipping = true; // Silence bogus warning.
1337 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001338 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001339 assert(!InCond && "Can't be skipping if not in a conditional!");
1340
1341 // If we popped the outermost skipping block, we're done skipping!
1342 if (!CondInfo.WasSkipping)
1343 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001344 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 // #else directive in a skipping conditional. If not in some other
1346 // skipping conditional, and if #else hasn't already been seen, enter it
1347 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001348 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001349 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1350
1351 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001352 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001353
1354 // Note that we've seen a #else in this conditional.
1355 CondInfo.FoundElse = true;
1356
1357 // If the conditional is at the top level, and the #if block wasn't
1358 // entered, enter the #else block now.
1359 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1360 CondInfo.FoundNonSkip = true;
1361 break;
1362 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001363 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001364 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1365
1366 bool ShouldEnter;
1367 // If this is in a skipping block or if we're already handled this #if
1368 // block, don't bother parsing the condition.
1369 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001370 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001371 ShouldEnter = false;
1372 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001373 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001374 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001375 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1376 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001377 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001378 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001379 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 }
1381
1382 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001383 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001384
1385 // If this condition is true, enter it!
1386 if (ShouldEnter) {
1387 CondInfo.FoundNonSkip = true;
1388 break;
1389 }
1390 }
1391 }
1392
1393 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001394 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001395 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001396 }
1397
1398 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1399 // of the file, just stop skipping and return to lexing whatever came after
1400 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001401 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001402}
1403
1404//===----------------------------------------------------------------------===//
1405// Preprocessor Directive Handling.
1406//===----------------------------------------------------------------------===//
1407
1408/// HandleDirective - This callback is invoked when the lexer sees a # token
1409/// at the start of a line. This consumes the directive, modifies the
1410/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1411/// read is the correct one.
Chris Lattner146762e2007-07-20 16:59:19 +00001412void Preprocessor::HandleDirective(Token &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001413 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001414
1415 // We just parsed a # character at the start of a line, so we're in directive
1416 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001417 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001418 CurLexer->ParsingPreprocessorDirective = true;
1419
1420 ++NumDirectives;
1421
Chris Lattner371ac8a2006-07-04 07:11:10 +00001422 // We are about to read a token. For the multiple-include optimization FA to
1423 // work, we have to remember if we had read any tokens *before* this
1424 // pp-directive.
1425 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1426
Chris Lattner78186052006-07-09 00:45:31 +00001427 // Read the next token, the directive flavor. This isn't expanded due to
1428 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001429 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001430
Chris Lattner78186052006-07-09 00:45:31 +00001431 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1432 // #define A(x) #x
1433 // A(abc
1434 // #warning blah
1435 // def)
1436 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001437 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001438 Diag(Result, diag::ext_embedded_directive);
1439
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001440TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001441 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001442 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001443 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001444 case tok::comment:
1445 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1446 LexUnexpandedToken(Result);
1447 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001448
Chris Lattner22eb9722006-06-18 05:43:12 +00001449 case tok::numeric_constant:
1450 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001451 DiscardUntilEndOfDirective();
1452 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001453 default:
1454 IdentifierInfo *II = Result.getIdentifierInfo();
1455 if (II == 0) break; // Not an identifier.
1456
1457 // Ask what the preprocessor keyword ID is.
1458 switch (II->getPPKeywordID()) {
1459 default: break;
1460 // C99 6.10.1 - Conditional Inclusion.
1461 case tok::pp_if:
1462 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1463 case tok::pp_ifdef:
1464 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1465 case tok::pp_ifndef:
1466 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1467 case tok::pp_elif:
1468 return HandleElifDirective(Result);
1469 case tok::pp_else:
1470 return HandleElseDirective(Result);
1471 case tok::pp_endif:
1472 return HandleEndifDirective(Result);
1473
1474 // C99 6.10.2 - Source File Inclusion.
1475 case tok::pp_include:
1476 return HandleIncludeDirective(Result); // Handle #include.
1477
1478 // C99 6.10.3 - Macro Replacement.
1479 case tok::pp_define:
1480 return HandleDefineDirective(Result, false);
1481 case tok::pp_undef:
1482 return HandleUndefDirective(Result);
1483
1484 // C99 6.10.4 - Line Control.
1485 case tok::pp_line:
1486 // FIXME: implement #line
1487 DiscardUntilEndOfDirective();
1488 return;
1489
1490 // C99 6.10.5 - Error Directive.
1491 case tok::pp_error:
1492 return HandleUserDiagnosticDirective(Result, false);
1493
1494 // C99 6.10.6 - Pragma Directive.
1495 case tok::pp_pragma:
1496 return HandlePragmaDirective();
1497
1498 // GNU Extensions.
1499 case tok::pp_import:
1500 return HandleImportDirective(Result);
1501 case tok::pp_include_next:
1502 return HandleIncludeNextDirective(Result);
1503
1504 case tok::pp_warning:
1505 Diag(Result, diag::ext_pp_warning_directive);
1506 return HandleUserDiagnosticDirective(Result, true);
1507 case tok::pp_ident:
1508 return HandleIdentSCCSDirective(Result);
1509 case tok::pp_sccs:
1510 return HandleIdentSCCSDirective(Result);
1511 case tok::pp_assert:
1512 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001513 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001514 case tok::pp_unassert:
1515 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001516 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001517
1518 // clang extensions.
1519 case tok::pp_define_target:
1520 return HandleDefineDirective(Result, true);
1521 case tok::pp_define_other_target:
1522 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001523 }
1524 break;
1525 }
1526
1527 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001528 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001529
1530 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001531 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001532
1533 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001534}
1535
Chris Lattner146762e2007-07-20 16:59:19 +00001536void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001537 bool isWarning) {
1538 // Read the rest of the line raw. We do this because we don't want macros
1539 // to be expanded and we don't require that the tokens be valid preprocessing
1540 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1541 // collapse multiple consequtive white space between tokens, but this isn't
1542 // specified by the standard.
1543 std::string Message = CurLexer->ReadToEndOfLine();
1544
1545 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001546 return Diag(Tok, DiagID, Message);
1547}
1548
1549/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1550///
Chris Lattner146762e2007-07-20 16:59:19 +00001551void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001552 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001553 Diag(Tok, diag::ext_pp_ident_directive);
1554
Chris Lattner371ac8a2006-07-04 07:11:10 +00001555 // Read the string argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001556 Token StrTok;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001557 Lex(StrTok);
1558
1559 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001560 if (StrTok.getKind() != tok::string_literal &&
1561 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001562 return Diag(StrTok, diag::err_pp_malformed_ident);
1563
1564 // Verify that there is nothing after the string, other than EOM.
1565 CheckEndOfDirective("#ident");
1566
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001567 if (Callbacks)
1568 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001569}
1570
Chris Lattnerb8761832006-06-24 21:31:03 +00001571//===----------------------------------------------------------------------===//
1572// Preprocessor Include Directive Handling.
1573//===----------------------------------------------------------------------===//
1574
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001575/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1576/// checked and spelled filename, e.g. as an operand of #include. This returns
1577/// true if the input filename was in <>'s or false if it were in ""'s. The
1578/// caller is expected to provide a buffer that is large enough to hold the
1579/// spelling of the filename, but is also expected to handle the case when
1580/// this method decides to use a different buffer.
Chris Lattner146762e2007-07-20 16:59:19 +00001581bool Preprocessor::GetIncludeFilenameSpelling(const Token &FilenameTok,
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001582 const char *&BufStart,
1583 const char *&BufEnd) {
1584 // Get the text form of the filename.
1585 unsigned Len = getSpelling(FilenameTok, BufStart);
1586 BufEnd = BufStart+Len;
1587 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1588
1589 // Make sure the filename is <x> or "x".
1590 bool isAngled;
1591 if (BufStart[0] == '<') {
1592 if (BufEnd[-1] != '>') {
1593 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1594 BufStart = 0;
1595 return true;
1596 }
1597 isAngled = true;
1598 } else if (BufStart[0] == '"') {
1599 if (BufEnd[-1] != '"') {
1600 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1601 BufStart = 0;
1602 return true;
1603 }
1604 isAngled = false;
1605 } else {
1606 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1607 BufStart = 0;
1608 return true;
1609 }
1610
1611 // Diagnose #include "" as invalid.
1612 if (BufEnd-BufStart <= 2) {
1613 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1614 BufStart = 0;
1615 return "";
1616 }
1617
1618 // Skip the brackets.
1619 ++BufStart;
1620 --BufEnd;
1621 return isAngled;
1622}
1623
Chris Lattner22eb9722006-06-18 05:43:12 +00001624/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1625/// file to be included from the lexer, then include it! This is a common
1626/// routine with functionality shared between #include, #include_next and
1627/// #import.
Chris Lattner146762e2007-07-20 16:59:19 +00001628void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001629 const DirectoryLookup *LookupFrom,
1630 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001631
Chris Lattner146762e2007-07-20 16:59:19 +00001632 Token FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001633 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001634
1635 // If the token kind is EOM, the error has already been diagnosed.
1636 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001637 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001638
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001639 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001640 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001641 FilenameBuffer.resize(FilenameTok.getLength());
1642
1643 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1644 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1645 FilenameStart, FilenameEnd);
1646 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1647 // error.
1648 if (FilenameStart == 0)
1649 return;
1650
Chris Lattner269c2322006-06-25 06:23:00 +00001651 // Verify that there is nothing after the filename, other than EOM. Use the
1652 // preprocessor to lex this in case lexing the filename entered a macro.
1653 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001654
1655 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001656 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001657 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1658
Chris Lattner22eb9722006-06-18 05:43:12 +00001659 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001660 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001661 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001662 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001663 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001664 return Diag(FilenameTok, diag::err_pp_file_not_found,
1665 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001666
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001667 // Ask HeaderInfo if we should enter this #include file.
1668 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1669 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001670 return;
1671 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001672
1673 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001674 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001675 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001676 return Diag(FilenameTok, diag::err_pp_file_not_found,
1677 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001678
1679 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001680 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001681}
1682
1683/// HandleIncludeNextDirective - Implements #include_next.
1684///
Chris Lattner146762e2007-07-20 16:59:19 +00001685void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001686 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001687
1688 // #include_next is like #include, except that we start searching after
1689 // the current found directory. If we can't do this, issue a
1690 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001691 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001692 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001693 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001694 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001695 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001696 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001697 } else {
1698 // Start looking up in the next directory.
1699 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001700 }
1701
1702 return HandleIncludeDirective(IncludeNextTok, Lookup);
1703}
1704
1705/// HandleImportDirective - Implements #import.
1706///
Chris Lattner146762e2007-07-20 16:59:19 +00001707void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001708 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001709
1710 return HandleIncludeDirective(ImportTok, 0, true);
1711}
1712
Chris Lattnerb8761832006-06-24 21:31:03 +00001713//===----------------------------------------------------------------------===//
1714// Preprocessor Macro Directive Handling.
1715//===----------------------------------------------------------------------===//
1716
Chris Lattnercefc7682006-07-08 08:28:12 +00001717/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1718/// definition has just been read. Lex the rest of the arguments and the
1719/// closing ), updating MI with what we learn. Return true if an error occurs
1720/// parsing the arg list.
1721bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001722 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1723
Chris Lattner146762e2007-07-20 16:59:19 +00001724 Token Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001725 while (1) {
1726 LexUnexpandedToken(Tok);
1727 switch (Tok.getKind()) {
1728 case tok::r_paren:
1729 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001730 if (Arguments.empty()) { // #define FOO()
1731 MI->setArgumentList(Arguments.begin(), Arguments.end());
1732 return false;
1733 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001734 // Otherwise we have #define FOO(A,)
1735 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1736 return true;
1737 case tok::ellipsis: // #define X(... -> C99 varargs
1738 // Warn if use of C99 feature in non-C99 mode.
1739 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1740
1741 // Lex the token after the identifier.
1742 LexUnexpandedToken(Tok);
1743 if (Tok.getKind() != tok::r_paren) {
1744 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1745 return true;
1746 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001747 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001748 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001749 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001750 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001751 return false;
1752 case tok::eom: // #define X(
1753 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1754 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001755 default:
1756 // Handle keywords and identifiers here to accept things like
1757 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001758 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001759 if (II == 0) {
1760 // #define X(1
1761 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1762 return true;
1763 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001764
1765 // If this is already used as an argument, it is used multiple times (e.g.
1766 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00001767 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1768 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001769 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1770 return true;
1771 }
1772
1773 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00001774 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001775
1776 // Lex the token after the identifier.
1777 LexUnexpandedToken(Tok);
1778
1779 switch (Tok.getKind()) {
1780 default: // #define X(A B
1781 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1782 return true;
1783 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00001784 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001785 return false;
1786 case tok::comma: // #define X(A,
1787 break;
1788 case tok::ellipsis: // #define X(A... -> GCC extension
1789 // Diagnose extension.
1790 Diag(Tok, diag::ext_named_variadic_macro);
1791
1792 // Lex the token after the identifier.
1793 LexUnexpandedToken(Tok);
1794 if (Tok.getKind() != tok::r_paren) {
1795 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1796 return true;
1797 }
1798
1799 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001800 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001801 return false;
1802 }
1803 }
1804 }
1805}
1806
Chris Lattner22eb9722006-06-18 05:43:12 +00001807/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001808/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1809/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001810///
Chris Lattner146762e2007-07-20 16:59:19 +00001811void Preprocessor::HandleDefineDirective(Token &DefineTok,
Chris Lattner81278c62006-10-14 19:03:49 +00001812 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001813 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001814
Chris Lattner146762e2007-07-20 16:59:19 +00001815 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001816 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001817
1818 // Error reading macro name? If so, diagnostic already issued.
1819 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001820 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00001821
Chris Lattner457fc152006-07-29 06:30:25 +00001822 // If we are supposed to keep comments in #defines, reenable comment saving
1823 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001824 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001825
Chris Lattner063400e2006-10-14 19:54:15 +00001826 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001827 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001828 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001829
Chris Lattner063400e2006-10-14 19:54:15 +00001830 // If the identifier is an 'other target' macro, clear this bit.
1831 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1832
1833
Chris Lattner146762e2007-07-20 16:59:19 +00001834 Token Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001835 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001836
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001837 // If this is a function-like macro definition, parse the argument list,
1838 // marking each of the identifiers as being used as macro arguments. Also,
1839 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001840 if (Tok.getKind() == tok::eom) {
1841 // If there is no body to this macro, we have no special handling here.
1842 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001843 // This is a function-like macro definition. Read the argument list.
1844 MI->setIsFunctionLike();
1845 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001846 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001847 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001848 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001849 if (CurLexer->ParsingPreprocessorDirective)
1850 DiscardUntilEndOfDirective();
1851 return;
1852 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001853
Chris Lattner815a1f92006-07-08 20:48:04 +00001854 // Read the first token after the arg list for down below.
1855 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001856 } else if (!Tok.hasLeadingSpace()) {
1857 // C99 requires whitespace between the macro definition and the body. Emit
1858 // a diagnostic for something like "#define X+".
1859 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001860 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001861 } else {
1862 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1863 // one in some cases!
1864 }
1865 } else {
1866 // This is a normal token with leading space. Clear the leading space
1867 // marker on the first token to get proper expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001868 Tok.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001869 }
1870
Chris Lattner7e374832006-07-29 03:46:57 +00001871 // If this is a definition of a variadic C99 function-like macro, not using
1872 // the GNU named varargs extension, enabled __VA_ARGS__.
1873
1874 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1875 // This gets unpoisoned where it is allowed.
1876 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1877 if (MI->isC99Varargs())
1878 Ident__VA_ARGS__->setIsPoisoned(false);
1879
Chris Lattner22eb9722006-06-18 05:43:12 +00001880 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00001881 if (MI->isObjectLike()) {
1882 // Object-like macros are very simple, just read their body.
1883 while (Tok.getKind() != tok::eom) {
1884 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001885 // Get the next token of the macro.
1886 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001887 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001888
Chris Lattnera3834342007-07-14 21:54:03 +00001889 } else {
1890 // Otherwise, read the body of a function-like macro. This has to validate
1891 // the # (stringize) operator.
1892 while (Tok.getKind() != tok::eom) {
1893 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001894
Chris Lattnera3834342007-07-14 21:54:03 +00001895 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1896 // parameters in function-like macro expansions.
1897 if (Tok.getKind() != tok::hash) {
1898 // Get the next token of the macro.
1899 LexUnexpandedToken(Tok);
1900 continue;
1901 }
1902
1903 // Get the next token of the macro.
1904 LexUnexpandedToken(Tok);
1905
1906 // Not a macro arg identifier?
1907 if (!Tok.getIdentifierInfo() ||
1908 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1909 Diag(Tok, diag::err_pp_stringize_not_parameter);
1910 delete MI;
1911
1912 // Disable __VA_ARGS__ again.
1913 Ident__VA_ARGS__->setIsPoisoned(true);
1914 return;
1915 }
1916
1917 // Things look ok, add the param name token to the macro.
1918 MI->AddTokenToBody(Tok);
1919
1920 // Get the next token of the macro.
1921 LexUnexpandedToken(Tok);
1922 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001923 }
Chris Lattner7e374832006-07-29 03:46:57 +00001924
Chris Lattnerf40fe992007-07-14 22:11:41 +00001925
Chris Lattner7e374832006-07-29 03:46:57 +00001926 // Disable __VA_ARGS__ again.
1927 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001928
Chris Lattnerbff18d52006-07-06 04:49:18 +00001929 // Check that there is no paste (##) operator at the begining or end of the
1930 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001931 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001932 if (NumTokens != 0) {
1933 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001934 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001935 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001936 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001937 }
1938 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001939 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001940 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001941 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001942 }
1943 }
1944
Chris Lattner13044d92006-07-03 05:16:44 +00001945 // If this is the primary source file, remember that this macro hasn't been
1946 // used yet.
1947 if (isInPrimaryFile())
1948 MI->setIsUsed(false);
1949
Chris Lattner22eb9722006-06-18 05:43:12 +00001950 // Finally, if this identifier already had a macro defined for it, verify that
1951 // the macro bodies are identical and free the old definition.
1952 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001953 if (!OtherMI->isUsed())
1954 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1955
Chris Lattner22eb9722006-06-18 05:43:12 +00001956 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001957 // must be the same. C99 6.10.3.2.
1958 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001959 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1960 MacroNameTok.getIdentifierInfo()->getName());
1961 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1962 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001963 delete OtherMI;
1964 }
1965
1966 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001967}
1968
Chris Lattner063400e2006-10-14 19:54:15 +00001969/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattner146762e2007-07-20 16:59:19 +00001970void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
1971 Token MacroNameTok;
Chris Lattner063400e2006-10-14 19:54:15 +00001972 ReadMacroName(MacroNameTok, 1);
1973
1974 // Error reading macro name? If so, diagnostic already issued.
1975 if (MacroNameTok.getKind() == tok::eom)
1976 return;
1977
1978 // Check to see if this is the last token on the #undef line.
1979 CheckEndOfDirective("#define_other_target");
1980
1981 // If there is already a macro defined by this name, turn it into a
1982 // target-specific define.
1983 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1984 MI->setIsTargetSpecific(true);
1985 return;
1986 }
1987
1988 // Mark the identifier as being a macro on some other target.
1989 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1990}
1991
Chris Lattner22eb9722006-06-18 05:43:12 +00001992
1993/// HandleUndefDirective - Implements #undef.
1994///
Chris Lattner146762e2007-07-20 16:59:19 +00001995void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001996 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001997
Chris Lattner146762e2007-07-20 16:59:19 +00001998 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001999 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002000
2001 // Error reading macro name? If so, diagnostic already issued.
2002 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00002003 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002004
2005 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002006 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002007
2008 // Okay, we finally have a valid identifier to undef.
2009 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
2010
Chris Lattner063400e2006-10-14 19:54:15 +00002011 // #undef untaints an identifier if it were marked by define_other_target.
2012 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2013
Chris Lattner22eb9722006-06-18 05:43:12 +00002014 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002015 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002016
Chris Lattner13044d92006-07-03 05:16:44 +00002017 if (!MI->isUsed())
2018 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002019
2020 // Free macro definition.
2021 delete MI;
2022 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002023}
2024
2025
Chris Lattnerb8761832006-06-24 21:31:03 +00002026//===----------------------------------------------------------------------===//
2027// Preprocessor Conditional Directive Handling.
2028//===----------------------------------------------------------------------===//
2029
Chris Lattner22eb9722006-06-18 05:43:12 +00002030/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002031/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2032/// if any tokens have been returned or pp-directives activated before this
2033/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002034///
Chris Lattner146762e2007-07-20 16:59:19 +00002035void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Chris Lattner371ac8a2006-07-04 07:11:10 +00002036 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002037 ++NumIf;
Chris Lattner146762e2007-07-20 16:59:19 +00002038 Token DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002039
Chris Lattner146762e2007-07-20 16:59:19 +00002040 Token MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002041 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002042
2043 // Error reading macro name? If so, diagnostic already issued.
2044 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00002045 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002046
2047 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002048 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2049
2050 // If the start of a top-level #ifdef, inform MIOpt.
2051 if (!ReadAnyTokensBeforeDirective &&
2052 CurLexer->getConditionalStackDepth() == 0) {
2053 assert(isIfndef && "#ifdef shouldn't reach here");
2054 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2055 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002056
Chris Lattner063400e2006-10-14 19:54:15 +00002057 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2058 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00002059
Chris Lattner81278c62006-10-14 19:03:49 +00002060 // If there is a macro, process it.
2061 if (MI) {
2062 // Mark it used.
2063 MI->setIsUsed(true);
2064
2065 // If this is the first use of a target-specific macro, warn about it.
2066 if (MI->isTargetSpecific()) {
2067 MI->setIsTargetSpecific(false); // Don't warn on second use.
2068 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2069 diag::port_target_macro_use);
2070 }
Chris Lattner063400e2006-10-14 19:54:15 +00002071 } else {
2072 // Use of a target-specific macro for some other target? If so, warn.
2073 if (MII->isOtherTargetMacro()) {
2074 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2075 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2076 diag::port_target_macro_use);
2077 }
Chris Lattner81278c62006-10-14 19:03:49 +00002078 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002079
Chris Lattner22eb9722006-06-18 05:43:12 +00002080 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002081 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002082 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002083 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002084 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002085 } else {
2086 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002087 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002088 /*Foundnonskip*/false,
2089 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002090 }
2091}
2092
2093/// HandleIfDirective - Implements the #if directive.
2094///
Chris Lattner146762e2007-07-20 16:59:19 +00002095void Preprocessor::HandleIfDirective(Token &IfToken,
Chris Lattnera8654ca2006-07-04 17:42:08 +00002096 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002097 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002098
Chris Lattner371ac8a2006-07-04 07:11:10 +00002099 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002100 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002101 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002102
2103 // Should we include the stuff contained by this directive?
2104 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002105 // If this condition is equivalent to #ifndef X, and if this is the first
2106 // directive seen, handle it for the multiple-include optimization.
2107 if (!ReadAnyTokensBeforeDirective &&
2108 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2109 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2110
Chris Lattner22eb9722006-06-18 05:43:12 +00002111 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002112 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002113 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002114 } else {
2115 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002116 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002117 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002118 }
2119}
2120
2121/// HandleEndifDirective - Implements the #endif directive.
2122///
Chris Lattner146762e2007-07-20 16:59:19 +00002123void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002124 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002125
Chris Lattner22eb9722006-06-18 05:43:12 +00002126 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002127 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002128
2129 PPConditionalInfo CondInfo;
2130 if (CurLexer->popConditionalLevel(CondInfo)) {
2131 // No conditionals on the stack: this is an #endif without an #if.
2132 return Diag(EndifToken, diag::err_pp_endif_without_if);
2133 }
2134
Chris Lattner371ac8a2006-07-04 07:11:10 +00002135 // If this the end of a top-level #endif, inform MIOpt.
2136 if (CurLexer->getConditionalStackDepth() == 0)
2137 CurLexer->MIOpt.ExitTopLevelConditional();
2138
Chris Lattner538d7f32006-07-20 04:31:52 +00002139 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002140 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002141}
2142
2143
Chris Lattner146762e2007-07-20 16:59:19 +00002144void Preprocessor::HandleElseDirective(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002145 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002146
Chris Lattner22eb9722006-06-18 05:43:12 +00002147 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002148 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002149
2150 PPConditionalInfo CI;
2151 if (CurLexer->popConditionalLevel(CI))
2152 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002153
2154 // If this is a top-level #else, inform the MIOpt.
2155 if (CurLexer->getConditionalStackDepth() == 0)
2156 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002157
2158 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002159 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002160
2161 // Finally, skip the rest of the contents of this block and return the first
2162 // token after it.
2163 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2164 /*FoundElse*/true);
2165}
2166
Chris Lattner146762e2007-07-20 16:59:19 +00002167void Preprocessor::HandleElifDirective(Token &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002168 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002169
Chris Lattner22eb9722006-06-18 05:43:12 +00002170 // #elif directive in a non-skipping conditional... start skipping.
2171 // We don't care what the condition is, because we will always skip it (since
2172 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002173 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002174
2175 PPConditionalInfo CI;
2176 if (CurLexer->popConditionalLevel(CI))
2177 return Diag(ElifToken, diag::pp_err_elif_without_if);
2178
Chris Lattner371ac8a2006-07-04 07:11:10 +00002179 // If this is a top-level #elif, inform the MIOpt.
2180 if (CurLexer->getConditionalStackDepth() == 0)
2181 CurLexer->MIOpt.FoundTopLevelElse();
2182
Chris Lattner22eb9722006-06-18 05:43:12 +00002183 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002184 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002185
2186 // Finally, skip the rest of the contents of this block and return the first
2187 // token after it.
2188 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2189 /*FoundElse*/CI.FoundElse);
2190}
Chris Lattnerb8761832006-06-24 21:31:03 +00002191